Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- parrot/lib/python3.10/idlelib/CREDITS.txt +47 -0
- parrot/lib/python3.10/idlelib/HISTORY.txt +296 -0
- parrot/lib/python3.10/idlelib/__init__.py +10 -0
- parrot/lib/python3.10/idlelib/codecontext.py +270 -0
- parrot/lib/python3.10/idlelib/colorizer.py +384 -0
- parrot/lib/python3.10/idlelib/config-extensions.def +62 -0
- parrot/lib/python3.10/idlelib/config-keys.def +309 -0
- parrot/lib/python3.10/idlelib/config-main.def +93 -0
- parrot/lib/python3.10/idlelib/configdialog.py +0 -0
- parrot/lib/python3.10/idlelib/debugger.py +550 -0
- parrot/lib/python3.10/idlelib/debugger_r.py +393 -0
- parrot/lib/python3.10/idlelib/dynoption.py +55 -0
- parrot/lib/python3.10/idlelib/extend.txt +83 -0
- parrot/lib/python3.10/idlelib/filelist.py +131 -0
- parrot/lib/python3.10/idlelib/help_about.py +212 -0
- parrot/lib/python3.10/idlelib/hyperparser.py +312 -0
- parrot/lib/python3.10/idlelib/idle.bat +4 -0
- parrot/lib/python3.10/idlelib/idle_test/README.txt +238 -0
- parrot/lib/python3.10/idlelib/idle_test/__pycache__/test_debugobj_r.cpython-310.pyc +0 -0
- parrot/lib/python3.10/idlelib/idle_test/__pycache__/test_iomenu.cpython-310.pyc +0 -0
- parrot/lib/python3.10/idlelib/idle_test/__pycache__/test_scrolledlist.cpython-310.pyc +0 -0
- parrot/lib/python3.10/idlelib/idle_test/__pycache__/test_squeezer.cpython-310.pyc +0 -0
- parrot/lib/python3.10/idlelib/idle_test/__pycache__/tkinter_testing_utils.cpython-310.pyc +0 -0
- parrot/lib/python3.10/idlelib/idle_test/test_autocomplete_w.py +32 -0
- parrot/lib/python3.10/idlelib/idle_test/test_browser.py +257 -0
- parrot/lib/python3.10/idlelib/idle_test/test_calltip.py +363 -0
- parrot/lib/python3.10/idlelib/idle_test/test_config_key.py +356 -0
- parrot/lib/python3.10/idlelib/idle_test/test_delegator.py +44 -0
- parrot/lib/python3.10/idlelib/idle_test/test_help.py +34 -0
- parrot/lib/python3.10/idlelib/idle_test/test_help_about.py +182 -0
- parrot/lib/python3.10/idlelib/idle_test/test_multicall.py +48 -0
- parrot/lib/python3.10/idlelib/idle_test/test_parenmatch.py +112 -0
- parrot/lib/python3.10/idlelib/idle_test/test_pathbrowser.py +86 -0
- parrot/lib/python3.10/idlelib/idle_test/test_replace.py +294 -0
- parrot/lib/python3.10/idlelib/idle_test/test_run.py +429 -0
- parrot/lib/python3.10/idlelib/idle_test/test_search.py +80 -0
- parrot/lib/python3.10/idlelib/idle_test/test_searchbase.py +160 -0
- parrot/lib/python3.10/idlelib/idle_test/test_sidebar.py +768 -0
- parrot/lib/python3.10/idlelib/idle_test/test_stackviewer.py +47 -0
- parrot/lib/python3.10/idlelib/idle_test/test_statusbar.py +41 -0
- parrot/lib/python3.10/idlelib/idle_test/test_undo.py +135 -0
- parrot/lib/python3.10/idlelib/idle_test/test_zzdummy.py +152 -0
- parrot/lib/python3.10/idlelib/mainmenu.py +126 -0
- parrot/lib/python3.10/idlelib/multicall.py +448 -0
- parrot/lib/python3.10/idlelib/outwin.py +187 -0
- parrot/lib/python3.10/idlelib/pyparse.py +589 -0
- parrot/lib/python3.10/idlelib/pyshell.py +1713 -0
- parrot/lib/python3.10/idlelib/redirector.py +174 -0
- parrot/lib/python3.10/idlelib/rpc.py +635 -0
- parrot/lib/python3.10/idlelib/run.py +642 -0
parrot/lib/python3.10/idlelib/CREDITS.txt
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Guido van Rossum, as well as being the creator of the Python language, is the
|
| 2 |
+
original creator of IDLE. Other contributors prior to Version 0.8 include
|
| 3 |
+
Mark Hammond, Jeremy Hylton, Tim Peters, and Moshe Zadka.
|
| 4 |
+
|
| 5 |
+
Until Python 2.3, IDLE's development was carried out in the SF IDLEfork project. The
|
| 6 |
+
objective was to develop a version of IDLE which had an execution environment
|
| 7 |
+
which could be initialized prior to each run of user code.
|
| 8 |
+
IDLefork was merged into the Python code base in 2003.
|
| 9 |
+
|
| 10 |
+
The IDLEfork project was initiated by David Scherer, with some help from Peter
|
| 11 |
+
Schneider-Kamp and Nicholas Riley. David wrote the first version of the RPC
|
| 12 |
+
code and designed a fast turn-around environment for VPython. Guido developed
|
| 13 |
+
the RPC code and Remote Debugger currently integrated in IDLE. Bruce Sherwood
|
| 14 |
+
contributed considerable time testing and suggesting improvements.
|
| 15 |
+
|
| 16 |
+
Besides David and Guido, the main developers who were active on IDLEfork
|
| 17 |
+
are Stephen M. Gava, who implemented the configuration GUI, the new
|
| 18 |
+
configuration system, and the About dialog, and Kurt B. Kaiser, who completed
|
| 19 |
+
the integration of the RPC and remote debugger, implemented the threaded
|
| 20 |
+
subprocess, and made a number of usability enhancements.
|
| 21 |
+
|
| 22 |
+
Other contributors include Raymond Hettinger, Tony Lownds (Mac integration),
|
| 23 |
+
Neal Norwitz (code check and clean-up), Ronald Oussoren (Mac integration),
|
| 24 |
+
Noam Raphael (Code Context, Call Tips, many other patches), and Chui Tey (RPC
|
| 25 |
+
integration, debugger integration and persistent breakpoints).
|
| 26 |
+
|
| 27 |
+
Scott David Daniels, Tal Einat, Hernan Foffani, Christos Georgiou,
|
| 28 |
+
Jim Jewett, Martin v. Löwis, Jason Orendorff, Guilherme Polo, Josh Robb,
|
| 29 |
+
Nigel Rowe, Bruce Sherwood, Jeff Shute, and Weeble have submitted useful
|
| 30 |
+
patches. Thanks, guys!
|
| 31 |
+
|
| 32 |
+
Major contributors since 2005:
|
| 33 |
+
|
| 34 |
+
- 2005: Tal Einat
|
| 35 |
+
- 2010: Terry Jan Reedy (current maintainer)
|
| 36 |
+
- 2013: Roger Serwys
|
| 37 |
+
- 2014: Saimadhav Heblikar
|
| 38 |
+
- 2015: Mark Roseman
|
| 39 |
+
- 2017: Louie Lu, Cheryl Sabella, and Serhiy Storchaka
|
| 40 |
+
|
| 41 |
+
For additional details refer to NEWS.txt and Changelog.
|
| 42 |
+
|
| 43 |
+
Please contact the IDLE maintainer (kbk@shore.net) to have yourself included
|
| 44 |
+
here if you are one of those we missed!
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
|
parrot/lib/python3.10/idlelib/HISTORY.txt
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
IDLE History
|
| 2 |
+
============
|
| 3 |
+
|
| 4 |
+
This file contains the release messages for previous IDLE releases.
|
| 5 |
+
As you read on you go back to the dark ages of IDLE's history.
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
What's New in IDLEfork 0.8.1?
|
| 9 |
+
=============================
|
| 10 |
+
|
| 11 |
+
*Release date: 22-Jul-2001*
|
| 12 |
+
|
| 13 |
+
- New tarball released as a result of the 'revitalisation' of the IDLEfork
|
| 14 |
+
project.
|
| 15 |
+
|
| 16 |
+
- This release requires python 2.1 or better. Compatibility with earlier
|
| 17 |
+
versions of python (especially ancient ones like 1.5x) is no longer a
|
| 18 |
+
priority in IDLEfork development.
|
| 19 |
+
|
| 20 |
+
- This release is based on a merging of the earlier IDLE fork work with current
|
| 21 |
+
cvs IDLE (post IDLE version 0.8), with some minor additional coding by Kurt
|
| 22 |
+
B. Kaiser and Stephen M. Gava.
|
| 23 |
+
|
| 24 |
+
- This release is basically functional but also contains some known breakages,
|
| 25 |
+
particularly with running things from the shell window. Also the debugger is
|
| 26 |
+
not working, but I believe this was the case with the previous IDLE fork
|
| 27 |
+
release (0.7.1) as well.
|
| 28 |
+
|
| 29 |
+
- This release is being made now to mark the point at which IDLEfork is
|
| 30 |
+
launching into a new stage of development.
|
| 31 |
+
|
| 32 |
+
- IDLEfork CVS will now be branched to enable further development and
|
| 33 |
+
exploration of the two "execution in a remote process" patches submitted by
|
| 34 |
+
David Scherer (David's is currently in IDLEfork) and GvR, while stabilisation
|
| 35 |
+
and development of less heavyweight improvements (like user customisation)
|
| 36 |
+
can continue on the trunk.
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
What's New in IDLEfork 0.7.1?
|
| 40 |
+
==============================
|
| 41 |
+
|
| 42 |
+
*Release date: 15-Aug-2000*
|
| 43 |
+
|
| 44 |
+
- First project tarball released.
|
| 45 |
+
|
| 46 |
+
- This was the first release of IDLE fork, which at this stage was a
|
| 47 |
+
combination of IDLE 0.5 and the VPython idle fork, with additional changes
|
| 48 |
+
coded by David Scherer, Peter Schneider-Kamp and Nicholas Riley.
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
IDLEfork 0.7.1 - 29 May 2000
|
| 53 |
+
-----------------------------
|
| 54 |
+
|
| 55 |
+
David Scherer <dscherer@cmu.edu>
|
| 56 |
+
|
| 57 |
+
- This is a modification of the CVS version of IDLE 0.5, updated as of
|
| 58 |
+
2000-03-09. It is alpha software and might be unstable. If it breaks, you
|
| 59 |
+
get to keep both pieces.
|
| 60 |
+
|
| 61 |
+
- If you have problems or suggestions, you should either contact me or post to
|
| 62 |
+
the list at http://www.python.org/mailman/listinfo/idle-dev (making it clear
|
| 63 |
+
that you are using this modified version of IDLE).
|
| 64 |
+
|
| 65 |
+
- Changes:
|
| 66 |
+
|
| 67 |
+
- The ExecBinding module, a replacement for ScriptBinding, executes programs
|
| 68 |
+
in a separate process, piping standard I/O through an RPC mechanism to an
|
| 69 |
+
OnDemandOutputWindow in IDLE. It supports executing unnamed programs
|
| 70 |
+
(through a temporary file). It does not yet support debugging.
|
| 71 |
+
|
| 72 |
+
- When running programs with ExecBinding, tracebacks will be clipped to
|
| 73 |
+
exclude system modules. If, however, a system module calls back into the
|
| 74 |
+
user program, that part of the traceback will be shown.
|
| 75 |
+
|
| 76 |
+
- The OnDemandOutputWindow class has been improved. In particular, it now
|
| 77 |
+
supports a readline() function used to implement user input, and a
|
| 78 |
+
scroll_clear() operation which is used to hide the output of a previous run
|
| 79 |
+
by scrolling it out of the window.
|
| 80 |
+
|
| 81 |
+
- Startup behavior has been changed. By default IDLE starts up with just a
|
| 82 |
+
blank editor window, rather than an interactive window. Opening a file in
|
| 83 |
+
such a blank window replaces the (nonexistent) contents of that window
|
| 84 |
+
instead of creating another window. Because of the need to have a
|
| 85 |
+
well-known port for the ExecBinding protocol, only one copy of IDLE can be
|
| 86 |
+
running. Additional invocations use the RPC mechanism to report their
|
| 87 |
+
command line arguments to the copy already running.
|
| 88 |
+
|
| 89 |
+
- The menus have been reorganized. In particular, the excessively large
|
| 90 |
+
'edit' menu has been split up into 'edit', 'format', and 'run'.
|
| 91 |
+
|
| 92 |
+
- 'Python Documentation' now works on Windows, if the win32api module is
|
| 93 |
+
present.
|
| 94 |
+
|
| 95 |
+
- A few key bindings have been changed: F1 now loads Python Documentation
|
| 96 |
+
instead of the IDLE help; shift-TAB is now a synonym for unindent.
|
| 97 |
+
|
| 98 |
+
- New modules:
|
| 99 |
+
|
| 100 |
+
ExecBinding.py Executes program through loader
|
| 101 |
+
loader.py Bootstraps user program
|
| 102 |
+
protocol.py RPC protocol
|
| 103 |
+
Remote.py User-process interpreter
|
| 104 |
+
spawn.py OS-specific code to start programs
|
| 105 |
+
|
| 106 |
+
- Files modified:
|
| 107 |
+
|
| 108 |
+
autoindent.py ( bindings tweaked )
|
| 109 |
+
bindings.py ( menus reorganized )
|
| 110 |
+
config.txt ( execbinding enabled )
|
| 111 |
+
editorwindow.py ( new menus, fixed 'Python Documentation' )
|
| 112 |
+
filelist.py ( hook for "open in same window" )
|
| 113 |
+
formatparagraph.py ( bindings tweaked )
|
| 114 |
+
idle.bat ( removed absolute pathname )
|
| 115 |
+
idle.pyw ( weird bug due to import with same name? )
|
| 116 |
+
iobinding.py ( open in same window, EOL convention )
|
| 117 |
+
keydefs.py ( bindings tweaked )
|
| 118 |
+
outputwindow.py ( readline, scroll_clear, etc )
|
| 119 |
+
pyshell.py ( changed startup behavior )
|
| 120 |
+
readme.txt ( <Recursion on file with id=1234567> )
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
IDLE 0.5 - February 2000 - Release Notes
|
| 125 |
+
----------------------------------------
|
| 126 |
+
|
| 127 |
+
This is an early release of IDLE, my own attempt at a Tkinter-based
|
| 128 |
+
IDE for Python.
|
| 129 |
+
|
| 130 |
+
(For a more detailed change log, see the file ChangeLog.)
|
| 131 |
+
|
| 132 |
+
FEATURES
|
| 133 |
+
|
| 134 |
+
IDLE has the following features:
|
| 135 |
+
|
| 136 |
+
- coded in 100% pure Python, using the Tkinter GUI toolkit (i.e. Tcl/Tk)
|
| 137 |
+
|
| 138 |
+
- cross-platform: works on Windows and Unix (on the Mac, there are
|
| 139 |
+
currently problems with Tcl/Tk)
|
| 140 |
+
|
| 141 |
+
- multi-window text editor with multiple undo, Python colorizing
|
| 142 |
+
and many other features, e.g. smart indent and call tips
|
| 143 |
+
|
| 144 |
+
- Python shell window (a.k.a. interactive interpreter)
|
| 145 |
+
|
| 146 |
+
- debugger (not complete, but you can set breakpoints, view and step)
|
| 147 |
+
|
| 148 |
+
USAGE
|
| 149 |
+
|
| 150 |
+
The main program is in the file "idle.py"; on Unix, you should be able
|
| 151 |
+
to run it by typing "./idle.py" to your shell. On Windows, you can
|
| 152 |
+
run it by double-clicking it; you can use idle.pyw to avoid popping up
|
| 153 |
+
a DOS console. If you want to pass command line arguments on Windows,
|
| 154 |
+
use the batch file idle.bat.
|
| 155 |
+
|
| 156 |
+
Command line arguments: files passed on the command line are executed,
|
| 157 |
+
not opened for editing, unless you give the -e command line option.
|
| 158 |
+
Try "./idle.py -h" to see other command line options.
|
| 159 |
+
|
| 160 |
+
IDLE requires Python 1.5.2, so it is currently only usable with a
|
| 161 |
+
Python 1.5.2 distribution. (An older version of IDLE is distributed
|
| 162 |
+
with Python 1.5.2; you can drop this version on top of it.)
|
| 163 |
+
|
| 164 |
+
COPYRIGHT
|
| 165 |
+
|
| 166 |
+
IDLE is covered by the standard Python copyright notice
|
| 167 |
+
(http://www.python.org/doc/Copyright.html).
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
New in IDLE 0.5 (2/15/2000)
|
| 171 |
+
---------------------------
|
| 172 |
+
|
| 173 |
+
Tons of stuff, much of it contributed by Tim Peters and Mark Hammond:
|
| 174 |
+
|
| 175 |
+
- Status bar, displaying current line/column (Moshe Zadka).
|
| 176 |
+
|
| 177 |
+
- Better stack viewer, using tree widget. (XXX Only used by Stack
|
| 178 |
+
Viewer menu, not by the debugger.)
|
| 179 |
+
|
| 180 |
+
- Format paragraph now recognizes Python block comments and reformats
|
| 181 |
+
them correctly (MH)
|
| 182 |
+
|
| 183 |
+
- New version of pyclbr.py parses top-level functions and understands
|
| 184 |
+
much more of Python's syntax; this is reflected in the class and path
|
| 185 |
+
browsers (TP)
|
| 186 |
+
|
| 187 |
+
- Much better auto-indent; knows how to indent the insides of
|
| 188 |
+
multi-line statements (TP)
|
| 189 |
+
|
| 190 |
+
- Call tip window pops up when you type the name of a known function
|
| 191 |
+
followed by an open parenthesis. Hit ESC or click elsewhere in the
|
| 192 |
+
window to close the tip window (MH)
|
| 193 |
+
|
| 194 |
+
- Comment out region now inserts ## to make it stand out more (TP)
|
| 195 |
+
|
| 196 |
+
- New path and class browsers based on a tree widget that looks
|
| 197 |
+
familiar to Windows users
|
| 198 |
+
|
| 199 |
+
- Reworked script running commands to be more intuitive: I/O now
|
| 200 |
+
always goes to the *Python Shell* window, and raw_input() works
|
| 201 |
+
correctly. You use F5 to import/reload a module: this adds the module
|
| 202 |
+
name to the __main__ namespace. You use Control-F5 to run a script:
|
| 203 |
+
this runs the script *in* the __main__ namespace. The latter also
|
| 204 |
+
sets sys.argv[] to the script name
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
New in IDLE 0.4 (4/7/99)
|
| 208 |
+
------------------------
|
| 209 |
+
|
| 210 |
+
Most important change: a new menu entry "File -> Path browser", shows
|
| 211 |
+
a 4-column hierarchical browser which lets you browse sys.path,
|
| 212 |
+
directories, modules, and classes. Yes, it's a superset of the Class
|
| 213 |
+
browser menu entry. There's also a new internal module,
|
| 214 |
+
MultiScrolledLists.py, which provides the framework for this dialog.
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
New in IDLE 0.3 (2/17/99)
|
| 218 |
+
-------------------------
|
| 219 |
+
|
| 220 |
+
Most important changes:
|
| 221 |
+
|
| 222 |
+
- Enabled support for running a module, with or without the debugger.
|
| 223 |
+
Output goes to a new window. Pressing F5 in a module is effectively a
|
| 224 |
+
reload of that module; Control-F5 loads it under the debugger.
|
| 225 |
+
|
| 226 |
+
- Re-enable tearing off the Windows menu, and make a torn-off Windows
|
| 227 |
+
menu update itself whenever a window is opened or closed.
|
| 228 |
+
|
| 229 |
+
- Menu items can now be have a checkbox (when the menu label starts
|
| 230 |
+
with "!"); use this for the Debugger and "Auto-open stack viewer"
|
| 231 |
+
(was: JIT stack viewer) menu items.
|
| 232 |
+
|
| 233 |
+
- Added a Quit button to the Debugger API.
|
| 234 |
+
|
| 235 |
+
- The current directory is explicitly inserted into sys.path.
|
| 236 |
+
|
| 237 |
+
- Fix the debugger (when using Python 1.5.2b2) to use canonical
|
| 238 |
+
filenames for breakpoints, so these actually work. (There's still a
|
| 239 |
+
lot of work to be done to the management of breakpoints in the
|
| 240 |
+
debugger though.)
|
| 241 |
+
|
| 242 |
+
- Closing a window that is still colorizing now actually works.
|
| 243 |
+
|
| 244 |
+
- Allow dragging of the separator between the two list boxes in the
|
| 245 |
+
class browser.
|
| 246 |
+
|
| 247 |
+
- Bind ESC to "close window" of the debugger, stack viewer and class
|
| 248 |
+
browser. It removes the selection highlighting in regular text
|
| 249 |
+
windows. (These are standard Windows conventions.)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
New in IDLE 0.2 (1/8/99)
|
| 253 |
+
------------------------
|
| 254 |
+
|
| 255 |
+
Lots of changes; here are the highlights:
|
| 256 |
+
|
| 257 |
+
General:
|
| 258 |
+
|
| 259 |
+
- You can now write and configure your own IDLE extension modules; see
|
| 260 |
+
extend.txt.
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
File menu:
|
| 264 |
+
|
| 265 |
+
The command to open the Python shell window is now in the File menu.
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
Edit menu:
|
| 269 |
+
|
| 270 |
+
New Find dialog with more options; replace dialog; find in files dialog.
|
| 271 |
+
|
| 272 |
+
Commands to tabify or untabify a region.
|
| 273 |
+
|
| 274 |
+
Command to format a paragraph.
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
Debug menu:
|
| 278 |
+
|
| 279 |
+
JIT (Just-In-Time) stack viewer toggle -- if set, the stack viewer
|
| 280 |
+
automaticall pops up when you get a traceback.
|
| 281 |
+
|
| 282 |
+
Windows menu:
|
| 283 |
+
|
| 284 |
+
Zoom height -- make the window full height.
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
Help menu:
|
| 288 |
+
|
| 289 |
+
The help text now show up in a regular window so you can search and
|
| 290 |
+
even edit it if you like.
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
IDLE 0.1 was distributed with the Python 1.5.2b1 release on 12/22/98.
|
| 295 |
+
|
| 296 |
+
======================================================================
|
parrot/lib/python3.10/idlelib/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The idlelib package implements the Idle application.
|
| 2 |
+
|
| 3 |
+
Idle includes an interactive shell and editor.
|
| 4 |
+
Starting with Python 3.6, IDLE requires tcl/tk 8.5 or later.
|
| 5 |
+
Use the files named idle.* to start Idle.
|
| 6 |
+
|
| 7 |
+
The other files are private implementations. Their details are subject to
|
| 8 |
+
change. See PEP 434 for more. Import them at your own risk.
|
| 9 |
+
"""
|
| 10 |
+
testing = False # Set True by test.test_idle.
|
parrot/lib/python3.10/idlelib/codecontext.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""codecontext - display the block context above the edit window
|
| 2 |
+
|
| 3 |
+
Once code has scrolled off the top of a window, it can be difficult to
|
| 4 |
+
determine which block you are in. This extension implements a pane at the top
|
| 5 |
+
of each IDLE edit window which provides block structure hints. These hints are
|
| 6 |
+
the lines which contain the block opening keywords, e.g. 'if', for the
|
| 7 |
+
enclosing block. The number of hint lines is determined by the maxlines
|
| 8 |
+
variable in the codecontext section of config-extensions.def. Lines which do
|
| 9 |
+
not open blocks are not shown in the context hints pane.
|
| 10 |
+
|
| 11 |
+
For EditorWindows, <<toggle-code-context>> is bound to CodeContext(self).
|
| 12 |
+
toggle_code_context_event.
|
| 13 |
+
"""
|
| 14 |
+
import re
|
| 15 |
+
from sys import maxsize as INFINITY
|
| 16 |
+
|
| 17 |
+
from tkinter import Frame, Text, TclError
|
| 18 |
+
from tkinter.constants import NSEW, SUNKEN
|
| 19 |
+
|
| 20 |
+
from idlelib.config import idleConf
|
| 21 |
+
|
| 22 |
+
BLOCKOPENERS = {'class', 'def', 'if', 'elif', 'else', 'while', 'for',
|
| 23 |
+
'try', 'except', 'finally', 'with', 'async'}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_spaces_firstword(codeline, c=re.compile(r"^(\s*)(\w*)")):
|
| 27 |
+
"Extract the beginning whitespace and first word from codeline."
|
| 28 |
+
return c.match(codeline).groups()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_line_info(codeline):
|
| 32 |
+
"""Return tuple of (line indent value, codeline, block start keyword).
|
| 33 |
+
|
| 34 |
+
The indentation of empty lines (or comment lines) is INFINITY.
|
| 35 |
+
If the line does not start a block, the keyword value is False.
|
| 36 |
+
"""
|
| 37 |
+
spaces, firstword = get_spaces_firstword(codeline)
|
| 38 |
+
indent = len(spaces)
|
| 39 |
+
if len(codeline) == indent or codeline[indent] == '#':
|
| 40 |
+
indent = INFINITY
|
| 41 |
+
opener = firstword in BLOCKOPENERS and firstword
|
| 42 |
+
return indent, codeline, opener
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class CodeContext:
|
| 46 |
+
"Display block context above the edit window."
|
| 47 |
+
UPDATEINTERVAL = 100 # millisec
|
| 48 |
+
|
| 49 |
+
def __init__(self, editwin):
|
| 50 |
+
"""Initialize settings for context block.
|
| 51 |
+
|
| 52 |
+
editwin is the Editor window for the context block.
|
| 53 |
+
self.text is the editor window text widget.
|
| 54 |
+
|
| 55 |
+
self.context displays the code context text above the editor text.
|
| 56 |
+
Initially None, it is toggled via <<toggle-code-context>>.
|
| 57 |
+
self.topvisible is the number of the top text line displayed.
|
| 58 |
+
self.info is a list of (line number, indent level, line text,
|
| 59 |
+
block keyword) tuples for the block structure above topvisible.
|
| 60 |
+
self.info[0] is initialized with a 'dummy' line which
|
| 61 |
+
starts the toplevel 'block' of the module.
|
| 62 |
+
|
| 63 |
+
self.t1 and self.t2 are two timer events on the editor text widget to
|
| 64 |
+
monitor for changes to the context text or editor font.
|
| 65 |
+
"""
|
| 66 |
+
self.editwin = editwin
|
| 67 |
+
self.text = editwin.text
|
| 68 |
+
self._reset()
|
| 69 |
+
|
| 70 |
+
def _reset(self):
|
| 71 |
+
self.context = None
|
| 72 |
+
self.cell00 = None
|
| 73 |
+
self.t1 = None
|
| 74 |
+
self.topvisible = 1
|
| 75 |
+
self.info = [(0, -1, "", False)]
|
| 76 |
+
|
| 77 |
+
@classmethod
|
| 78 |
+
def reload(cls):
|
| 79 |
+
"Load class variables from config."
|
| 80 |
+
cls.context_depth = idleConf.GetOption("extensions", "CodeContext",
|
| 81 |
+
"maxlines", type="int",
|
| 82 |
+
default=15)
|
| 83 |
+
|
| 84 |
+
def __del__(self):
|
| 85 |
+
"Cancel scheduled events."
|
| 86 |
+
if self.t1 is not None:
|
| 87 |
+
try:
|
| 88 |
+
self.text.after_cancel(self.t1)
|
| 89 |
+
except TclError: # pragma: no cover
|
| 90 |
+
pass
|
| 91 |
+
self.t1 = None
|
| 92 |
+
|
| 93 |
+
def toggle_code_context_event(self, event=None):
|
| 94 |
+
"""Toggle code context display.
|
| 95 |
+
|
| 96 |
+
If self.context doesn't exist, create it to match the size of the editor
|
| 97 |
+
window text (toggle on). If it does exist, destroy it (toggle off).
|
| 98 |
+
Return 'break' to complete the processing of the binding.
|
| 99 |
+
"""
|
| 100 |
+
if self.context is None:
|
| 101 |
+
# Calculate the border width and horizontal padding required to
|
| 102 |
+
# align the context with the text in the main Text widget.
|
| 103 |
+
#
|
| 104 |
+
# All values are passed through getint(), since some
|
| 105 |
+
# values may be pixel objects, which can't simply be added to ints.
|
| 106 |
+
widgets = self.editwin.text, self.editwin.text_frame
|
| 107 |
+
# Calculate the required horizontal padding and border width.
|
| 108 |
+
padx = 0
|
| 109 |
+
border = 0
|
| 110 |
+
for widget in widgets:
|
| 111 |
+
info = (widget.grid_info()
|
| 112 |
+
if widget is self.editwin.text
|
| 113 |
+
else widget.pack_info())
|
| 114 |
+
padx += widget.tk.getint(info['padx'])
|
| 115 |
+
padx += widget.tk.getint(widget.cget('padx'))
|
| 116 |
+
border += widget.tk.getint(widget.cget('border'))
|
| 117 |
+
context = self.context = Text(
|
| 118 |
+
self.editwin.text_frame,
|
| 119 |
+
height=1,
|
| 120 |
+
width=1, # Don't request more than we get.
|
| 121 |
+
highlightthickness=0,
|
| 122 |
+
padx=padx, border=border, relief=SUNKEN, state='disabled')
|
| 123 |
+
self.update_font()
|
| 124 |
+
self.update_highlight_colors()
|
| 125 |
+
context.bind('<ButtonRelease-1>', self.jumptoline)
|
| 126 |
+
# Get the current context and initiate the recurring update event.
|
| 127 |
+
self.timer_event()
|
| 128 |
+
# Grid the context widget above the text widget.
|
| 129 |
+
context.grid(row=0, column=1, sticky=NSEW)
|
| 130 |
+
|
| 131 |
+
line_number_colors = idleConf.GetHighlight(idleConf.CurrentTheme(),
|
| 132 |
+
'linenumber')
|
| 133 |
+
self.cell00 = Frame(self.editwin.text_frame,
|
| 134 |
+
bg=line_number_colors['background'])
|
| 135 |
+
self.cell00.grid(row=0, column=0, sticky=NSEW)
|
| 136 |
+
menu_status = 'Hide'
|
| 137 |
+
else:
|
| 138 |
+
self.context.destroy()
|
| 139 |
+
self.context = None
|
| 140 |
+
self.cell00.destroy()
|
| 141 |
+
self.cell00 = None
|
| 142 |
+
self.text.after_cancel(self.t1)
|
| 143 |
+
self._reset()
|
| 144 |
+
menu_status = 'Show'
|
| 145 |
+
self.editwin.update_menu_label(menu='options', index='*ode*ontext',
|
| 146 |
+
label=f'{menu_status} Code Context')
|
| 147 |
+
return "break"
|
| 148 |
+
|
| 149 |
+
def get_context(self, new_topvisible, stopline=1, stopindent=0):
|
| 150 |
+
"""Return a list of block line tuples and the 'last' indent.
|
| 151 |
+
|
| 152 |
+
The tuple fields are (linenum, indent, text, opener).
|
| 153 |
+
The list represents header lines from new_topvisible back to
|
| 154 |
+
stopline with successively shorter indents > stopindent.
|
| 155 |
+
The list is returned ordered by line number.
|
| 156 |
+
Last indent returned is the smallest indent observed.
|
| 157 |
+
"""
|
| 158 |
+
assert stopline > 0
|
| 159 |
+
lines = []
|
| 160 |
+
# The indentation level we are currently in.
|
| 161 |
+
lastindent = INFINITY
|
| 162 |
+
# For a line to be interesting, it must begin with a block opening
|
| 163 |
+
# keyword, and have less indentation than lastindent.
|
| 164 |
+
for linenum in range(new_topvisible, stopline-1, -1):
|
| 165 |
+
codeline = self.text.get(f'{linenum}.0', f'{linenum}.end')
|
| 166 |
+
indent, text, opener = get_line_info(codeline)
|
| 167 |
+
if indent < lastindent:
|
| 168 |
+
lastindent = indent
|
| 169 |
+
if opener in ("else", "elif"):
|
| 170 |
+
# Also show the if statement.
|
| 171 |
+
lastindent += 1
|
| 172 |
+
if opener and linenum < new_topvisible and indent >= stopindent:
|
| 173 |
+
lines.append((linenum, indent, text, opener))
|
| 174 |
+
if lastindent <= stopindent:
|
| 175 |
+
break
|
| 176 |
+
lines.reverse()
|
| 177 |
+
return lines, lastindent
|
| 178 |
+
|
| 179 |
+
def update_code_context(self):
|
| 180 |
+
"""Update context information and lines visible in the context pane.
|
| 181 |
+
|
| 182 |
+
No update is done if the text hasn't been scrolled. If the text
|
| 183 |
+
was scrolled, the lines that should be shown in the context will
|
| 184 |
+
be retrieved and the context area will be updated with the code,
|
| 185 |
+
up to the number of maxlines.
|
| 186 |
+
"""
|
| 187 |
+
new_topvisible = self.editwin.getlineno("@0,0")
|
| 188 |
+
if self.topvisible == new_topvisible: # Haven't scrolled.
|
| 189 |
+
return
|
| 190 |
+
if self.topvisible < new_topvisible: # Scroll down.
|
| 191 |
+
lines, lastindent = self.get_context(new_topvisible,
|
| 192 |
+
self.topvisible)
|
| 193 |
+
# Retain only context info applicable to the region
|
| 194 |
+
# between topvisible and new_topvisible.
|
| 195 |
+
while self.info[-1][1] >= lastindent:
|
| 196 |
+
del self.info[-1]
|
| 197 |
+
else: # self.topvisible > new_topvisible: # Scroll up.
|
| 198 |
+
stopindent = self.info[-1][1] + 1
|
| 199 |
+
# Retain only context info associated
|
| 200 |
+
# with lines above new_topvisible.
|
| 201 |
+
while self.info[-1][0] >= new_topvisible:
|
| 202 |
+
stopindent = self.info[-1][1]
|
| 203 |
+
del self.info[-1]
|
| 204 |
+
lines, lastindent = self.get_context(new_topvisible,
|
| 205 |
+
self.info[-1][0]+1,
|
| 206 |
+
stopindent)
|
| 207 |
+
self.info.extend(lines)
|
| 208 |
+
self.topvisible = new_topvisible
|
| 209 |
+
# Last context_depth context lines.
|
| 210 |
+
context_strings = [x[2] for x in self.info[-self.context_depth:]]
|
| 211 |
+
showfirst = 0 if context_strings[0] else 1
|
| 212 |
+
# Update widget.
|
| 213 |
+
self.context['height'] = len(context_strings) - showfirst
|
| 214 |
+
self.context['state'] = 'normal'
|
| 215 |
+
self.context.delete('1.0', 'end')
|
| 216 |
+
self.context.insert('end', '\n'.join(context_strings[showfirst:]))
|
| 217 |
+
self.context['state'] = 'disabled'
|
| 218 |
+
|
| 219 |
+
def jumptoline(self, event=None):
|
| 220 |
+
""" Show clicked context line at top of editor.
|
| 221 |
+
|
| 222 |
+
If a selection was made, don't jump; allow copying.
|
| 223 |
+
If no visible context, show the top line of the file.
|
| 224 |
+
"""
|
| 225 |
+
try:
|
| 226 |
+
self.context.index("sel.first")
|
| 227 |
+
except TclError:
|
| 228 |
+
lines = len(self.info)
|
| 229 |
+
if lines == 1: # No context lines are showing.
|
| 230 |
+
newtop = 1
|
| 231 |
+
else:
|
| 232 |
+
# Line number clicked.
|
| 233 |
+
contextline = int(float(self.context.index('insert')))
|
| 234 |
+
# Lines not displayed due to maxlines.
|
| 235 |
+
offset = max(1, lines - self.context_depth) - 1
|
| 236 |
+
newtop = self.info[offset + contextline][0]
|
| 237 |
+
self.text.yview(f'{newtop}.0')
|
| 238 |
+
self.update_code_context()
|
| 239 |
+
|
| 240 |
+
def timer_event(self):
|
| 241 |
+
"Event on editor text widget triggered every UPDATEINTERVAL ms."
|
| 242 |
+
if self.context is not None:
|
| 243 |
+
self.update_code_context()
|
| 244 |
+
self.t1 = self.text.after(self.UPDATEINTERVAL, self.timer_event)
|
| 245 |
+
|
| 246 |
+
def update_font(self):
|
| 247 |
+
if self.context is not None:
|
| 248 |
+
font = idleConf.GetFont(self.text, 'main', 'EditorWindow')
|
| 249 |
+
self.context['font'] = font
|
| 250 |
+
|
| 251 |
+
def update_highlight_colors(self):
|
| 252 |
+
if self.context is not None:
|
| 253 |
+
colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'context')
|
| 254 |
+
self.context['background'] = colors['background']
|
| 255 |
+
self.context['foreground'] = colors['foreground']
|
| 256 |
+
|
| 257 |
+
if self.cell00 is not None:
|
| 258 |
+
line_number_colors = idleConf.GetHighlight(idleConf.CurrentTheme(),
|
| 259 |
+
'linenumber')
|
| 260 |
+
self.cell00.config(bg=line_number_colors['background'])
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
CodeContext.reload()
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
if __name__ == "__main__":
|
| 267 |
+
from unittest import main
|
| 268 |
+
main('idlelib.idle_test.test_codecontext', verbosity=2, exit=False)
|
| 269 |
+
|
| 270 |
+
# Add htest.
|
parrot/lib/python3.10/idlelib/colorizer.py
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
|
| 12 |
+
def any(name, alternates):
|
| 13 |
+
"Return a named group pattern matching list of alternates."
|
| 14 |
+
return "(?P<%s>" % name + "|".join(alternates) + ")"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def make_pat():
|
| 18 |
+
kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b"
|
| 19 |
+
match_softkw = (
|
| 20 |
+
r"^[ \t]*" + # at beginning of line + possible indentation
|
| 21 |
+
r"(?P<MATCH_SOFTKW>match)\b" +
|
| 22 |
+
r"(?![ \t]*(?:" + "|".join([ # not followed by ...
|
| 23 |
+
r"[:,;=^&|@~)\]}]", # a character which means it can't be a
|
| 24 |
+
# pattern-matching statement
|
| 25 |
+
r"\b(?:" + r"|".join(keyword.kwlist) + r")\b", # a keyword
|
| 26 |
+
]) +
|
| 27 |
+
r"))"
|
| 28 |
+
)
|
| 29 |
+
case_default = (
|
| 30 |
+
r"^[ \t]*" + # at beginning of line + possible indentation
|
| 31 |
+
r"(?P<CASE_SOFTKW>case)" +
|
| 32 |
+
r"[ \t]+(?P<CASE_DEFAULT_UNDERSCORE>_\b)"
|
| 33 |
+
)
|
| 34 |
+
case_softkw_and_pattern = (
|
| 35 |
+
r"^[ \t]*" + # at beginning of line + possible indentation
|
| 36 |
+
r"(?P<CASE_SOFTKW2>case)\b" +
|
| 37 |
+
r"(?![ \t]*(?:" + "|".join([ # not followed by ...
|
| 38 |
+
r"_\b", # a lone underscore
|
| 39 |
+
r"[:,;=^&|@~)\]}]", # a character which means it can't be a
|
| 40 |
+
# pattern-matching case
|
| 41 |
+
r"\b(?:" + r"|".join(keyword.kwlist) + r")\b", # a keyword
|
| 42 |
+
]) +
|
| 43 |
+
r"))"
|
| 44 |
+
)
|
| 45 |
+
builtinlist = [str(name) for name in dir(builtins)
|
| 46 |
+
if not name.startswith('_') and
|
| 47 |
+
name not in keyword.kwlist]
|
| 48 |
+
builtin = r"([^.'\"\\#]\b|^)" + any("BUILTIN", builtinlist) + r"\b"
|
| 49 |
+
comment = any("COMMENT", [r"#[^\n]*"])
|
| 50 |
+
stringprefix = r"(?i:r|u|f|fr|rf|b|br|rb)?"
|
| 51 |
+
sqstring = stringprefix + r"'[^'\\\n]*(\\.[^'\\\n]*)*'?"
|
| 52 |
+
dqstring = stringprefix + r'"[^"\\\n]*(\\.[^"\\\n]*)*"?'
|
| 53 |
+
sq3string = stringprefix + r"'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?"
|
| 54 |
+
dq3string = stringprefix + r'"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?'
|
| 55 |
+
string = any("STRING", [sq3string, dq3string, sqstring, dqstring])
|
| 56 |
+
prog = re.compile("|".join([
|
| 57 |
+
builtin, comment, string, kw,
|
| 58 |
+
match_softkw, case_default,
|
| 59 |
+
case_softkw_and_pattern,
|
| 60 |
+
any("SYNC", [r"\n"]),
|
| 61 |
+
]),
|
| 62 |
+
re.DOTALL | re.MULTILINE)
|
| 63 |
+
return prog
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
prog = make_pat()
|
| 67 |
+
idprog = re.compile(r"\s+(\w+)")
|
| 68 |
+
prog_group_name_to_tag = {
|
| 69 |
+
"MATCH_SOFTKW": "KEYWORD",
|
| 70 |
+
"CASE_SOFTKW": "KEYWORD",
|
| 71 |
+
"CASE_DEFAULT_UNDERSCORE": "KEYWORD",
|
| 72 |
+
"CASE_SOFTKW2": "KEYWORD",
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def matched_named_groups(re_match):
|
| 77 |
+
"Get only the non-empty named groups from an re.Match object."
|
| 78 |
+
return ((k, v) for (k, v) in re_match.groupdict().items() if v)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def color_config(text):
|
| 82 |
+
"""Set color options of Text widget.
|
| 83 |
+
|
| 84 |
+
If ColorDelegator is used, this should be called first.
|
| 85 |
+
"""
|
| 86 |
+
# Called from htest, TextFrame, Editor, and Turtledemo.
|
| 87 |
+
# Not automatic because ColorDelegator does not know 'text'.
|
| 88 |
+
theme = idleConf.CurrentTheme()
|
| 89 |
+
normal_colors = idleConf.GetHighlight(theme, 'normal')
|
| 90 |
+
cursor_color = idleConf.GetHighlight(theme, 'cursor')['foreground']
|
| 91 |
+
select_colors = idleConf.GetHighlight(theme, 'hilite')
|
| 92 |
+
text.config(
|
| 93 |
+
foreground=normal_colors['foreground'],
|
| 94 |
+
background=normal_colors['background'],
|
| 95 |
+
insertbackground=cursor_color,
|
| 96 |
+
selectforeground=select_colors['foreground'],
|
| 97 |
+
selectbackground=select_colors['background'],
|
| 98 |
+
inactiveselectbackground=select_colors['background'], # new in 8.5
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class ColorDelegator(Delegator):
|
| 103 |
+
"""Delegator for syntax highlighting (text coloring).
|
| 104 |
+
|
| 105 |
+
Instance variables:
|
| 106 |
+
delegate: Delegator below this one in the stack, meaning the
|
| 107 |
+
one this one delegates to.
|
| 108 |
+
|
| 109 |
+
Used to track state:
|
| 110 |
+
after_id: Identifier for scheduled after event, which is a
|
| 111 |
+
timer for colorizing the text.
|
| 112 |
+
allow_colorizing: Boolean toggle for applying colorizing.
|
| 113 |
+
colorizing: Boolean flag when colorizing is in process.
|
| 114 |
+
stop_colorizing: Boolean flag to end an active colorizing
|
| 115 |
+
process.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
def __init__(self):
|
| 119 |
+
Delegator.__init__(self)
|
| 120 |
+
self.init_state()
|
| 121 |
+
self.prog = prog
|
| 122 |
+
self.idprog = idprog
|
| 123 |
+
self.LoadTagDefs()
|
| 124 |
+
|
| 125 |
+
def init_state(self):
|
| 126 |
+
"Initialize variables that track colorizing state."
|
| 127 |
+
self.after_id = None
|
| 128 |
+
self.allow_colorizing = True
|
| 129 |
+
self.stop_colorizing = False
|
| 130 |
+
self.colorizing = False
|
| 131 |
+
|
| 132 |
+
def setdelegate(self, delegate):
|
| 133 |
+
"""Set the delegate for this instance.
|
| 134 |
+
|
| 135 |
+
A delegate is an instance of a Delegator class and each
|
| 136 |
+
delegate points to the next delegator in the stack. This
|
| 137 |
+
allows multiple delegators to be chained together for a
|
| 138 |
+
widget. The bottom delegate for a colorizer is a Text
|
| 139 |
+
widget.
|
| 140 |
+
|
| 141 |
+
If there is a delegate, also start the colorizing process.
|
| 142 |
+
"""
|
| 143 |
+
if self.delegate is not None:
|
| 144 |
+
self.unbind("<<toggle-auto-coloring>>")
|
| 145 |
+
Delegator.setdelegate(self, delegate)
|
| 146 |
+
if delegate is not None:
|
| 147 |
+
self.config_colors()
|
| 148 |
+
self.bind("<<toggle-auto-coloring>>", self.toggle_colorize_event)
|
| 149 |
+
self.notify_range("1.0", "end")
|
| 150 |
+
else:
|
| 151 |
+
# No delegate - stop any colorizing.
|
| 152 |
+
self.stop_colorizing = True
|
| 153 |
+
self.allow_colorizing = False
|
| 154 |
+
|
| 155 |
+
def config_colors(self):
|
| 156 |
+
"Configure text widget tags with colors from tagdefs."
|
| 157 |
+
for tag, cnf in self.tagdefs.items():
|
| 158 |
+
self.tag_configure(tag, **cnf)
|
| 159 |
+
self.tag_raise('sel')
|
| 160 |
+
|
| 161 |
+
def LoadTagDefs(self):
|
| 162 |
+
"Create dictionary of tag names to text colors."
|
| 163 |
+
theme = idleConf.CurrentTheme()
|
| 164 |
+
self.tagdefs = {
|
| 165 |
+
"COMMENT": idleConf.GetHighlight(theme, "comment"),
|
| 166 |
+
"KEYWORD": idleConf.GetHighlight(theme, "keyword"),
|
| 167 |
+
"BUILTIN": idleConf.GetHighlight(theme, "builtin"),
|
| 168 |
+
"STRING": idleConf.GetHighlight(theme, "string"),
|
| 169 |
+
"DEFINITION": idleConf.GetHighlight(theme, "definition"),
|
| 170 |
+
"SYNC": {'background': None, 'foreground': None},
|
| 171 |
+
"TODO": {'background': None, 'foreground': None},
|
| 172 |
+
"ERROR": idleConf.GetHighlight(theme, "error"),
|
| 173 |
+
# "hit" is used by ReplaceDialog to mark matches. It shouldn't be changed by Colorizer, but
|
| 174 |
+
# that currently isn't technically possible. This should be moved elsewhere in the future
|
| 175 |
+
# when fixing the "hit" tag's visibility, or when the replace dialog is replaced with a
|
| 176 |
+
# non-modal alternative.
|
| 177 |
+
"hit": idleConf.GetHighlight(theme, "hit"),
|
| 178 |
+
}
|
| 179 |
+
if DEBUG: print('tagdefs', self.tagdefs)
|
| 180 |
+
|
| 181 |
+
def insert(self, index, chars, tags=None):
|
| 182 |
+
"Insert chars into widget at index and mark for colorizing."
|
| 183 |
+
index = self.index(index)
|
| 184 |
+
self.delegate.insert(index, chars, tags)
|
| 185 |
+
self.notify_range(index, index + "+%dc" % len(chars))
|
| 186 |
+
|
| 187 |
+
def delete(self, index1, index2=None):
|
| 188 |
+
"Delete chars between indexes and mark for colorizing."
|
| 189 |
+
index1 = self.index(index1)
|
| 190 |
+
self.delegate.delete(index1, index2)
|
| 191 |
+
self.notify_range(index1)
|
| 192 |
+
|
| 193 |
+
def notify_range(self, index1, index2=None):
|
| 194 |
+
"Mark text changes for processing and restart colorizing, if active."
|
| 195 |
+
self.tag_add("TODO", index1, index2)
|
| 196 |
+
if self.after_id:
|
| 197 |
+
if DEBUG: print("colorizing already scheduled")
|
| 198 |
+
return
|
| 199 |
+
if self.colorizing:
|
| 200 |
+
self.stop_colorizing = True
|
| 201 |
+
if DEBUG: print("stop colorizing")
|
| 202 |
+
if self.allow_colorizing:
|
| 203 |
+
if DEBUG: print("schedule colorizing")
|
| 204 |
+
self.after_id = self.after(1, self.recolorize)
|
| 205 |
+
return
|
| 206 |
+
|
| 207 |
+
def close(self):
|
| 208 |
+
if self.after_id:
|
| 209 |
+
after_id = self.after_id
|
| 210 |
+
self.after_id = None
|
| 211 |
+
if DEBUG: print("cancel scheduled recolorizer")
|
| 212 |
+
self.after_cancel(after_id)
|
| 213 |
+
self.allow_colorizing = False
|
| 214 |
+
self.stop_colorizing = True
|
| 215 |
+
|
| 216 |
+
def toggle_colorize_event(self, event=None):
|
| 217 |
+
"""Toggle colorizing on and off.
|
| 218 |
+
|
| 219 |
+
When toggling off, if colorizing is scheduled or is in
|
| 220 |
+
process, it will be cancelled and/or stopped.
|
| 221 |
+
|
| 222 |
+
When toggling on, colorizing will be scheduled.
|
| 223 |
+
"""
|
| 224 |
+
if self.after_id:
|
| 225 |
+
after_id = self.after_id
|
| 226 |
+
self.after_id = None
|
| 227 |
+
if DEBUG: print("cancel scheduled recolorizer")
|
| 228 |
+
self.after_cancel(after_id)
|
| 229 |
+
if self.allow_colorizing and self.colorizing:
|
| 230 |
+
if DEBUG: print("stop colorizing")
|
| 231 |
+
self.stop_colorizing = True
|
| 232 |
+
self.allow_colorizing = not self.allow_colorizing
|
| 233 |
+
if self.allow_colorizing and not self.colorizing:
|
| 234 |
+
self.after_id = self.after(1, self.recolorize)
|
| 235 |
+
if DEBUG:
|
| 236 |
+
print("auto colorizing turned",
|
| 237 |
+
"on" if self.allow_colorizing else "off")
|
| 238 |
+
return "break"
|
| 239 |
+
|
| 240 |
+
def recolorize(self):
|
| 241 |
+
"""Timer event (every 1ms) to colorize text.
|
| 242 |
+
|
| 243 |
+
Colorizing is only attempted when the text widget exists,
|
| 244 |
+
when colorizing is toggled on, and when the colorizing
|
| 245 |
+
process is not already running.
|
| 246 |
+
|
| 247 |
+
After colorizing is complete, some cleanup is done to
|
| 248 |
+
make sure that all the text has been colorized.
|
| 249 |
+
"""
|
| 250 |
+
self.after_id = None
|
| 251 |
+
if not self.delegate:
|
| 252 |
+
if DEBUG: print("no delegate")
|
| 253 |
+
return
|
| 254 |
+
if not self.allow_colorizing:
|
| 255 |
+
if DEBUG: print("auto colorizing is off")
|
| 256 |
+
return
|
| 257 |
+
if self.colorizing:
|
| 258 |
+
if DEBUG: print("already colorizing")
|
| 259 |
+
return
|
| 260 |
+
try:
|
| 261 |
+
self.stop_colorizing = False
|
| 262 |
+
self.colorizing = True
|
| 263 |
+
if DEBUG: print("colorizing...")
|
| 264 |
+
t0 = time.perf_counter()
|
| 265 |
+
self.recolorize_main()
|
| 266 |
+
t1 = time.perf_counter()
|
| 267 |
+
if DEBUG: print("%.3f seconds" % (t1-t0))
|
| 268 |
+
finally:
|
| 269 |
+
self.colorizing = False
|
| 270 |
+
if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"):
|
| 271 |
+
if DEBUG: print("reschedule colorizing")
|
| 272 |
+
self.after_id = self.after(1, self.recolorize)
|
| 273 |
+
|
| 274 |
+
def recolorize_main(self):
|
| 275 |
+
"Evaluate text and apply colorizing tags."
|
| 276 |
+
next = "1.0"
|
| 277 |
+
while todo_tag_range := self.tag_nextrange("TODO", next):
|
| 278 |
+
self.tag_remove("SYNC", todo_tag_range[0], todo_tag_range[1])
|
| 279 |
+
sync_tag_range = self.tag_prevrange("SYNC", todo_tag_range[0])
|
| 280 |
+
head = sync_tag_range[1] if sync_tag_range else "1.0"
|
| 281 |
+
|
| 282 |
+
chars = ""
|
| 283 |
+
next = head
|
| 284 |
+
lines_to_get = 1
|
| 285 |
+
ok = False
|
| 286 |
+
while not ok:
|
| 287 |
+
mark = next
|
| 288 |
+
next = self.index(mark + "+%d lines linestart" %
|
| 289 |
+
lines_to_get)
|
| 290 |
+
lines_to_get = min(lines_to_get * 2, 100)
|
| 291 |
+
ok = "SYNC" in self.tag_names(next + "-1c")
|
| 292 |
+
line = self.get(mark, next)
|
| 293 |
+
##print head, "get", mark, next, "->", repr(line)
|
| 294 |
+
if not line:
|
| 295 |
+
return
|
| 296 |
+
for tag in self.tagdefs:
|
| 297 |
+
self.tag_remove(tag, mark, next)
|
| 298 |
+
chars += line
|
| 299 |
+
self._add_tags_in_section(chars, head)
|
| 300 |
+
if "SYNC" in self.tag_names(next + "-1c"):
|
| 301 |
+
head = next
|
| 302 |
+
chars = ""
|
| 303 |
+
else:
|
| 304 |
+
ok = False
|
| 305 |
+
if not ok:
|
| 306 |
+
# We're in an inconsistent state, and the call to
|
| 307 |
+
# update may tell us to stop. It may also change
|
| 308 |
+
# the correct value for "next" (since this is a
|
| 309 |
+
# line.col string, not a true mark). So leave a
|
| 310 |
+
# crumb telling the next invocation to resume here
|
| 311 |
+
# in case update tells us to leave.
|
| 312 |
+
self.tag_add("TODO", next)
|
| 313 |
+
self.update()
|
| 314 |
+
if self.stop_colorizing:
|
| 315 |
+
if DEBUG: print("colorizing stopped")
|
| 316 |
+
return
|
| 317 |
+
|
| 318 |
+
def _add_tag(self, start, end, head, matched_group_name):
|
| 319 |
+
"""Add a tag to a given range in the text widget.
|
| 320 |
+
|
| 321 |
+
This is a utility function, receiving the range as `start` and
|
| 322 |
+
`end` positions, each of which is a number of characters
|
| 323 |
+
relative to the given `head` index in the text widget.
|
| 324 |
+
|
| 325 |
+
The tag to add is determined by `matched_group_name`, which is
|
| 326 |
+
the name of a regular expression "named group" as matched by
|
| 327 |
+
by the relevant highlighting regexps.
|
| 328 |
+
"""
|
| 329 |
+
tag = prog_group_name_to_tag.get(matched_group_name,
|
| 330 |
+
matched_group_name)
|
| 331 |
+
self.tag_add(tag,
|
| 332 |
+
f"{head}+{start:d}c",
|
| 333 |
+
f"{head}+{end:d}c")
|
| 334 |
+
|
| 335 |
+
def _add_tags_in_section(self, chars, head):
|
| 336 |
+
"""Parse and add highlighting tags to a given part of the text.
|
| 337 |
+
|
| 338 |
+
`chars` is a string with the text to parse and to which
|
| 339 |
+
highlighting is to be applied.
|
| 340 |
+
|
| 341 |
+
`head` is the index in the text widget where the text is found.
|
| 342 |
+
"""
|
| 343 |
+
for m in self.prog.finditer(chars):
|
| 344 |
+
for name, matched_text in matched_named_groups(m):
|
| 345 |
+
a, b = m.span(name)
|
| 346 |
+
self._add_tag(a, b, head, name)
|
| 347 |
+
if matched_text in ("def", "class"):
|
| 348 |
+
if m1 := self.idprog.match(chars, b):
|
| 349 |
+
a, b = m1.span(1)
|
| 350 |
+
self._add_tag(a, b, head, "DEFINITION")
|
| 351 |
+
|
| 352 |
+
def removecolors(self):
|
| 353 |
+
"Remove all colorizing tags."
|
| 354 |
+
for tag in self.tagdefs:
|
| 355 |
+
self.tag_remove(tag, "1.0", "end")
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def _color_delegator(parent): # htest #
|
| 359 |
+
from tkinter import Toplevel, Text
|
| 360 |
+
from idlelib.idle_test.test_colorizer import source
|
| 361 |
+
from idlelib.percolator import Percolator
|
| 362 |
+
|
| 363 |
+
top = Toplevel(parent)
|
| 364 |
+
top.title("Test ColorDelegator")
|
| 365 |
+
x, y = map(int, parent.geometry().split('+')[1:])
|
| 366 |
+
top.geometry("700x550+%d+%d" % (x + 20, y + 175))
|
| 367 |
+
|
| 368 |
+
text = Text(top, background="white")
|
| 369 |
+
text.pack(expand=1, fill="both")
|
| 370 |
+
text.insert("insert", source)
|
| 371 |
+
text.focus_set()
|
| 372 |
+
|
| 373 |
+
color_config(text)
|
| 374 |
+
p = Percolator(text)
|
| 375 |
+
d = ColorDelegator()
|
| 376 |
+
p.insertfilter(d)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
if __name__ == "__main__":
|
| 380 |
+
from unittest import main
|
| 381 |
+
main('idlelib.idle_test.test_colorizer', verbosity=2, exit=False)
|
| 382 |
+
|
| 383 |
+
from idlelib.idle_test.htest import run
|
| 384 |
+
run(_color_delegator)
|
parrot/lib/python3.10/idlelib/config-extensions.def
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# config-extensions.def
|
| 2 |
+
#
|
| 3 |
+
# The following sections are for features that are no longer extensions.
|
| 4 |
+
# Their options values are left here for back-compatibility.
|
| 5 |
+
|
| 6 |
+
[AutoComplete]
|
| 7 |
+
popupwait= 2000
|
| 8 |
+
|
| 9 |
+
[CodeContext]
|
| 10 |
+
maxlines= 15
|
| 11 |
+
|
| 12 |
+
[FormatParagraph]
|
| 13 |
+
max-width= 72
|
| 14 |
+
|
| 15 |
+
[ParenMatch]
|
| 16 |
+
style= expression
|
| 17 |
+
flash-delay= 500
|
| 18 |
+
bell= True
|
| 19 |
+
|
| 20 |
+
# IDLE reads several config files to determine user preferences. This
|
| 21 |
+
# file is the default configuration file for IDLE extensions settings.
|
| 22 |
+
#
|
| 23 |
+
# Each extension must have at least one section, named after the
|
| 24 |
+
# extension module. This section must contain an 'enable' item (=True to
|
| 25 |
+
# enable the extension, =False to disable it), it may contain
|
| 26 |
+
# 'enable_editor' or 'enable_shell' items, to apply it only to editor ir
|
| 27 |
+
# shell windows, and may also contain any other general configuration
|
| 28 |
+
# items for the extension. Other True/False values will also be
|
| 29 |
+
# recognized as boolean by the Extension Configuration dialog.
|
| 30 |
+
#
|
| 31 |
+
# Each extension must define at least one section named
|
| 32 |
+
# ExtensionName_bindings or ExtensionName_cfgBindings. If present,
|
| 33 |
+
# ExtensionName_bindings defines virtual event bindings for the
|
| 34 |
+
# extension that are not user re-configurable. If present,
|
| 35 |
+
# ExtensionName_cfgBindings defines virtual event bindings for the
|
| 36 |
+
# extension that may be sensibly re-configured.
|
| 37 |
+
#
|
| 38 |
+
# If there are no keybindings for a menus' virtual events, include lines
|
| 39 |
+
# like <<toggle-code-context>>=.
|
| 40 |
+
#
|
| 41 |
+
# Currently it is necessary to manually modify this file to change
|
| 42 |
+
# extension key bindings and default values. To customize, create
|
| 43 |
+
# ~/.idlerc/config-extensions.cfg and append the appropriate customized
|
| 44 |
+
# section(s). Those sections will override the defaults in this file.
|
| 45 |
+
#
|
| 46 |
+
# Note: If a keybinding is already in use when the extension is loaded,
|
| 47 |
+
# the extension's virtual event's keybinding will be set to ''.
|
| 48 |
+
#
|
| 49 |
+
# See config-keys.def for notes on specifying keys and extend.txt for
|
| 50 |
+
# information on creating IDLE extensions.
|
| 51 |
+
|
| 52 |
+
# A fake extension for testing and example purposes. When enabled and
|
| 53 |
+
# invoked, inserts or deletes z-text at beginning of every line.
|
| 54 |
+
[ZzDummy]
|
| 55 |
+
enable= False
|
| 56 |
+
enable_shell = False
|
| 57 |
+
enable_editor = True
|
| 58 |
+
z-text= Z
|
| 59 |
+
[ZzDummy_cfgBindings]
|
| 60 |
+
z-in= <Control-Shift-KeyRelease-Insert>
|
| 61 |
+
[ZzDummy_bindings]
|
| 62 |
+
z-out= <Control-Shift-KeyRelease-Delete>
|
parrot/lib/python3.10/idlelib/config-keys.def
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# IDLE reads several config files to determine user preferences. This
|
| 2 |
+
# file is the default config file for idle key binding settings.
|
| 3 |
+
# Where multiple keys are specified for an action: if they are separated
|
| 4 |
+
# by a space (eg. action=<key1> <key2>) then the keys are alternatives, if
|
| 5 |
+
# there is no space (eg. action=<key1><key2>) then the keys comprise a
|
| 6 |
+
# single 'emacs style' multi-keystoke binding. The tk event specifier 'Key'
|
| 7 |
+
# is used in all cases, for consistency in auto key conflict checking in the
|
| 8 |
+
# configuration gui.
|
| 9 |
+
|
| 10 |
+
[IDLE Classic Windows]
|
| 11 |
+
copy=<Control-Key-c> <Control-Key-C>
|
| 12 |
+
cut=<Control-Key-x> <Control-Key-X>
|
| 13 |
+
paste=<Control-Key-v> <Control-Key-V>
|
| 14 |
+
beginning-of-line= <Key-Home>
|
| 15 |
+
center-insert=<Control-Key-l> <Control-Key-L>
|
| 16 |
+
close-all-windows=<Control-Key-q> <Control-Key-Q>
|
| 17 |
+
close-window=<Alt-Key-F4> <Meta-Key-F4>
|
| 18 |
+
do-nothing=<Control-Key-F12>
|
| 19 |
+
end-of-file=<Control-Key-d> <Control-Key-D>
|
| 20 |
+
python-docs=<Key-F1>
|
| 21 |
+
python-context-help=<Shift-Key-F1>
|
| 22 |
+
history-next=<Alt-Key-n> <Meta-Key-n> <Alt-Key-N> <Meta-Key-N>
|
| 23 |
+
history-previous=<Alt-Key-p> <Meta-Key-p> <Alt-Key-P> <Meta-Key-P>
|
| 24 |
+
interrupt-execution=<Control-Key-c> <Control-Key-C>
|
| 25 |
+
view-restart=<Key-F6>
|
| 26 |
+
restart-shell=<Control-Key-F6>
|
| 27 |
+
open-class-browser=<Alt-Key-c> <Meta-Key-c> <Alt-Key-C> <Meta-Key-C>
|
| 28 |
+
open-module=<Alt-Key-m> <Meta-Key-m> <Alt-Key-M> <Meta-Key-M>
|
| 29 |
+
open-new-window=<Control-Key-n> <Control-Key-N>
|
| 30 |
+
open-window-from-file=<Control-Key-o> <Control-Key-O>
|
| 31 |
+
plain-newline-and-indent=<Control-Key-j> <Control-Key-J>
|
| 32 |
+
print-window=<Control-Key-p> <Control-Key-P>
|
| 33 |
+
redo=<Control-Shift-Key-Z> <Control-Shift-Key-z>
|
| 34 |
+
remove-selection=<Key-Escape>
|
| 35 |
+
save-copy-of-window-as-file=<Alt-Shift-Key-S> <Alt-Shift-Key-s>
|
| 36 |
+
save-window-as-file=<Control-Shift-Key-S> <Control-Shift-Key-s>
|
| 37 |
+
save-window=<Control-Key-s> <Control-Key-S>
|
| 38 |
+
select-all=<Control-Key-a> <Control-Key-A>
|
| 39 |
+
toggle-auto-coloring=<Control-Key-slash>
|
| 40 |
+
undo=<Control-Key-z> <Control-Key-Z>
|
| 41 |
+
find=<Control-Key-f> <Control-Key-F>
|
| 42 |
+
find-again=<Control-Key-g> <Key-F3> <Control-Key-G>
|
| 43 |
+
find-in-files=<Alt-Key-F3> <Meta-Key-F3>
|
| 44 |
+
find-selection=<Control-Key-F3>
|
| 45 |
+
replace=<Control-Key-h> <Control-Key-H>
|
| 46 |
+
goto-line=<Alt-Key-g> <Meta-Key-g> <Alt-Key-G> <Meta-Key-G>
|
| 47 |
+
smart-backspace=<Key-BackSpace>
|
| 48 |
+
newline-and-indent=<Key-Return> <Key-KP_Enter>
|
| 49 |
+
smart-indent=<Key-Tab>
|
| 50 |
+
indent-region=<Control-Key-bracketright>
|
| 51 |
+
dedent-region=<Control-Key-bracketleft>
|
| 52 |
+
comment-region=<Alt-Key-3> <Meta-Key-3>
|
| 53 |
+
uncomment-region=<Alt-Key-4> <Meta-Key-4>
|
| 54 |
+
tabify-region=<Alt-Key-5> <Meta-Key-5>
|
| 55 |
+
untabify-region=<Alt-Key-6> <Meta-Key-6>
|
| 56 |
+
toggle-tabs=<Alt-Key-t> <Meta-Key-t> <Alt-Key-T> <Meta-Key-T>
|
| 57 |
+
change-indentwidth=<Alt-Key-u> <Meta-Key-u> <Alt-Key-U> <Meta-Key-U>
|
| 58 |
+
del-word-left=<Control-Key-BackSpace>
|
| 59 |
+
del-word-right=<Control-Key-Delete>
|
| 60 |
+
force-open-completions= <Control-Key-space>
|
| 61 |
+
expand-word= <Alt-Key-slash>
|
| 62 |
+
force-open-calltip= <Control-Key-backslash>
|
| 63 |
+
format-paragraph= <Alt-Key-q>
|
| 64 |
+
flash-paren= <Control-Key-0>
|
| 65 |
+
run-module= <Key-F5>
|
| 66 |
+
run-custom= <Shift-Key-F5>
|
| 67 |
+
check-module= <Alt-Key-x>
|
| 68 |
+
zoom-height= <Alt-Key-2>
|
| 69 |
+
|
| 70 |
+
[IDLE Classic Unix]
|
| 71 |
+
copy=<Alt-Key-w> <Meta-Key-w>
|
| 72 |
+
cut=<Control-Key-w>
|
| 73 |
+
paste=<Control-Key-y>
|
| 74 |
+
beginning-of-line=<Control-Key-a> <Key-Home>
|
| 75 |
+
center-insert=<Control-Key-l>
|
| 76 |
+
close-all-windows=<Control-Key-x><Control-Key-c>
|
| 77 |
+
close-window=<Control-Key-x><Control-Key-0>
|
| 78 |
+
do-nothing=<Control-Key-x>
|
| 79 |
+
end-of-file=<Control-Key-d>
|
| 80 |
+
history-next=<Alt-Key-n> <Meta-Key-n>
|
| 81 |
+
history-previous=<Alt-Key-p> <Meta-Key-p>
|
| 82 |
+
interrupt-execution=<Control-Key-c>
|
| 83 |
+
view-restart=<Key-F6>
|
| 84 |
+
restart-shell=<Control-Key-F6>
|
| 85 |
+
open-class-browser=<Control-Key-x><Control-Key-b>
|
| 86 |
+
open-module=<Control-Key-x><Control-Key-m>
|
| 87 |
+
open-new-window=<Control-Key-x><Control-Key-n>
|
| 88 |
+
open-window-from-file=<Control-Key-x><Control-Key-f>
|
| 89 |
+
plain-newline-and-indent=<Control-Key-j>
|
| 90 |
+
print-window=<Control-x><Control-Key-p>
|
| 91 |
+
python-docs=<Control-Key-h>
|
| 92 |
+
python-context-help=<Control-Shift-Key-H>
|
| 93 |
+
redo=<Alt-Key-z> <Meta-Key-z>
|
| 94 |
+
remove-selection=<Key-Escape>
|
| 95 |
+
save-copy-of-window-as-file=<Control-Key-x><Control-Key-y>
|
| 96 |
+
save-window-as-file=<Control-Key-x><Control-Key-w>
|
| 97 |
+
save-window=<Control-Key-x><Control-Key-s>
|
| 98 |
+
select-all=<Alt-Key-a> <Meta-Key-a>
|
| 99 |
+
toggle-auto-coloring=<Control-Key-slash>
|
| 100 |
+
undo=<Control-Key-z>
|
| 101 |
+
find=<Control-Key-u><Control-Key-u><Control-Key-s>
|
| 102 |
+
find-again=<Control-Key-u><Control-Key-s>
|
| 103 |
+
find-in-files=<Alt-Key-s> <Meta-Key-s>
|
| 104 |
+
find-selection=<Control-Key-s>
|
| 105 |
+
replace=<Control-Key-r>
|
| 106 |
+
goto-line=<Alt-Key-g> <Meta-Key-g>
|
| 107 |
+
smart-backspace=<Key-BackSpace>
|
| 108 |
+
newline-and-indent=<Key-Return> <Key-KP_Enter>
|
| 109 |
+
smart-indent=<Key-Tab>
|
| 110 |
+
indent-region=<Control-Key-bracketright>
|
| 111 |
+
dedent-region=<Control-Key-bracketleft>
|
| 112 |
+
comment-region=<Alt-Key-3>
|
| 113 |
+
uncomment-region=<Alt-Key-4>
|
| 114 |
+
tabify-region=<Alt-Key-5>
|
| 115 |
+
untabify-region=<Alt-Key-6>
|
| 116 |
+
toggle-tabs=<Alt-Key-t>
|
| 117 |
+
change-indentwidth=<Alt-Key-u>
|
| 118 |
+
del-word-left=<Alt-Key-BackSpace>
|
| 119 |
+
del-word-right=<Alt-Key-d>
|
| 120 |
+
force-open-completions= <Control-Key-space>
|
| 121 |
+
expand-word= <Alt-Key-slash>
|
| 122 |
+
force-open-calltip= <Control-Key-backslash>
|
| 123 |
+
format-paragraph= <Alt-Key-q>
|
| 124 |
+
flash-paren= <Control-Key-0>
|
| 125 |
+
run-module= <Key-F5>
|
| 126 |
+
run-custom= <Shift-Key-F5>
|
| 127 |
+
check-module= <Alt-Key-x>
|
| 128 |
+
zoom-height= <Alt-Key-2>
|
| 129 |
+
|
| 130 |
+
[IDLE Modern Unix]
|
| 131 |
+
copy = <Control-Shift-Key-C> <Control-Key-Insert>
|
| 132 |
+
cut = <Control-Key-x> <Shift-Key-Delete>
|
| 133 |
+
paste = <Control-Key-v> <Shift-Key-Insert>
|
| 134 |
+
beginning-of-line = <Key-Home>
|
| 135 |
+
center-insert = <Control-Key-l>
|
| 136 |
+
close-all-windows = <Control-Key-q>
|
| 137 |
+
close-window = <Control-Key-w> <Control-Shift-Key-W>
|
| 138 |
+
do-nothing = <Control-Key-F12>
|
| 139 |
+
end-of-file = <Control-Key-d>
|
| 140 |
+
history-next = <Alt-Key-n> <Meta-Key-n>
|
| 141 |
+
history-previous = <Alt-Key-p> <Meta-Key-p>
|
| 142 |
+
interrupt-execution = <Control-Key-c>
|
| 143 |
+
view-restart = <Key-F6>
|
| 144 |
+
restart-shell = <Control-Key-F6>
|
| 145 |
+
open-class-browser = <Control-Key-b>
|
| 146 |
+
open-module = <Control-Key-m>
|
| 147 |
+
open-new-window = <Control-Key-n>
|
| 148 |
+
open-window-from-file = <Control-Key-o>
|
| 149 |
+
plain-newline-and-indent = <Control-Key-j>
|
| 150 |
+
print-window = <Control-Key-p>
|
| 151 |
+
python-context-help = <Shift-Key-F1>
|
| 152 |
+
python-docs = <Key-F1>
|
| 153 |
+
redo = <Control-Shift-Key-Z>
|
| 154 |
+
remove-selection = <Key-Escape>
|
| 155 |
+
save-copy-of-window-as-file = <Alt-Shift-Key-S>
|
| 156 |
+
save-window-as-file = <Control-Shift-Key-S>
|
| 157 |
+
save-window = <Control-Key-s>
|
| 158 |
+
select-all = <Control-Key-a>
|
| 159 |
+
toggle-auto-coloring = <Control-Key-slash>
|
| 160 |
+
undo = <Control-Key-z>
|
| 161 |
+
find = <Control-Key-f>
|
| 162 |
+
find-again = <Key-F3>
|
| 163 |
+
find-in-files = <Control-Shift-Key-f>
|
| 164 |
+
find-selection = <Control-Key-h>
|
| 165 |
+
replace = <Control-Key-r>
|
| 166 |
+
goto-line = <Control-Key-g>
|
| 167 |
+
smart-backspace = <Key-BackSpace>
|
| 168 |
+
newline-and-indent = <Key-Return> <Key-KP_Enter>
|
| 169 |
+
smart-indent = <Key-Tab>
|
| 170 |
+
indent-region = <Control-Key-bracketright>
|
| 171 |
+
dedent-region = <Control-Key-bracketleft>
|
| 172 |
+
comment-region = <Control-Key-d>
|
| 173 |
+
uncomment-region = <Control-Shift-Key-D>
|
| 174 |
+
tabify-region = <Alt-Key-5>
|
| 175 |
+
untabify-region = <Alt-Key-6>
|
| 176 |
+
toggle-tabs = <Control-Key-T>
|
| 177 |
+
change-indentwidth = <Alt-Key-u>
|
| 178 |
+
del-word-left = <Control-Key-BackSpace>
|
| 179 |
+
del-word-right = <Control-Key-Delete>
|
| 180 |
+
force-open-completions= <Control-Key-space>
|
| 181 |
+
expand-word= <Alt-Key-slash>
|
| 182 |
+
force-open-calltip= <Control-Key-backslash>
|
| 183 |
+
format-paragraph= <Alt-Key-q>
|
| 184 |
+
flash-paren= <Control-Key-0>
|
| 185 |
+
run-module= <Key-F5>
|
| 186 |
+
run-custom= <Shift-Key-F5>
|
| 187 |
+
check-module= <Alt-Key-x>
|
| 188 |
+
zoom-height= <Alt-Key-2>
|
| 189 |
+
|
| 190 |
+
[IDLE Classic Mac]
|
| 191 |
+
copy=<Command-Key-c>
|
| 192 |
+
cut=<Command-Key-x>
|
| 193 |
+
paste=<Command-Key-v>
|
| 194 |
+
beginning-of-line= <Key-Home>
|
| 195 |
+
center-insert=<Control-Key-l>
|
| 196 |
+
close-all-windows=<Command-Key-q>
|
| 197 |
+
close-window=<Command-Key-w>
|
| 198 |
+
do-nothing=<Control-Key-F12>
|
| 199 |
+
end-of-file=<Control-Key-d>
|
| 200 |
+
python-docs=<Key-F1>
|
| 201 |
+
python-context-help=<Shift-Key-F1>
|
| 202 |
+
history-next=<Control-Key-n>
|
| 203 |
+
history-previous=<Control-Key-p>
|
| 204 |
+
interrupt-execution=<Control-Key-c>
|
| 205 |
+
view-restart=<Key-F6>
|
| 206 |
+
restart-shell=<Control-Key-F6>
|
| 207 |
+
open-class-browser=<Command-Key-b>
|
| 208 |
+
open-module=<Command-Key-m>
|
| 209 |
+
open-new-window=<Command-Key-n>
|
| 210 |
+
open-window-from-file=<Command-Key-o>
|
| 211 |
+
plain-newline-and-indent=<Control-Key-j>
|
| 212 |
+
print-window=<Command-Key-p>
|
| 213 |
+
redo=<Shift-Command-Key-Z>
|
| 214 |
+
remove-selection=<Key-Escape>
|
| 215 |
+
save-window-as-file=<Shift-Command-Key-S>
|
| 216 |
+
save-window=<Command-Key-s>
|
| 217 |
+
save-copy-of-window-as-file=<Option-Command-Key-s>
|
| 218 |
+
select-all=<Command-Key-a>
|
| 219 |
+
toggle-auto-coloring=<Control-Key-slash>
|
| 220 |
+
undo=<Command-Key-z>
|
| 221 |
+
find=<Command-Key-f>
|
| 222 |
+
find-again=<Command-Key-g> <Key-F3>
|
| 223 |
+
find-in-files=<Command-Key-F3>
|
| 224 |
+
find-selection=<Shift-Command-Key-F3>
|
| 225 |
+
replace=<Command-Key-r>
|
| 226 |
+
goto-line=<Command-Key-j>
|
| 227 |
+
smart-backspace=<Key-BackSpace>
|
| 228 |
+
newline-and-indent=<Key-Return> <Key-KP_Enter>
|
| 229 |
+
smart-indent=<Key-Tab>
|
| 230 |
+
indent-region=<Command-Key-bracketright>
|
| 231 |
+
dedent-region=<Command-Key-bracketleft>
|
| 232 |
+
comment-region=<Control-Key-3>
|
| 233 |
+
uncomment-region=<Control-Key-4>
|
| 234 |
+
tabify-region=<Control-Key-5>
|
| 235 |
+
untabify-region=<Control-Key-6>
|
| 236 |
+
toggle-tabs=<Control-Key-t>
|
| 237 |
+
change-indentwidth=<Control-Key-u>
|
| 238 |
+
del-word-left=<Control-Key-BackSpace>
|
| 239 |
+
del-word-right=<Control-Key-Delete>
|
| 240 |
+
force-open-completions= <Control-Key-space>
|
| 241 |
+
expand-word= <Option-Key-slash>
|
| 242 |
+
force-open-calltip= <Control-Key-backslash>
|
| 243 |
+
format-paragraph= <Option-Key-q>
|
| 244 |
+
flash-paren= <Control-Key-0>
|
| 245 |
+
run-module= <Key-F5>
|
| 246 |
+
run-custom= <Shift-Key-F5>
|
| 247 |
+
check-module= <Option-Key-x>
|
| 248 |
+
zoom-height= <Option-Key-0>
|
| 249 |
+
|
| 250 |
+
[IDLE Classic OSX]
|
| 251 |
+
toggle-tabs = <Control-Key-t>
|
| 252 |
+
interrupt-execution = <Control-Key-c>
|
| 253 |
+
untabify-region = <Control-Key-6>
|
| 254 |
+
remove-selection = <Key-Escape>
|
| 255 |
+
print-window = <Command-Key-p>
|
| 256 |
+
replace = <Command-Key-r>
|
| 257 |
+
goto-line = <Command-Key-j>
|
| 258 |
+
plain-newline-and-indent = <Control-Key-j>
|
| 259 |
+
history-previous = <Control-Key-p>
|
| 260 |
+
beginning-of-line = <Control-Key-Left>
|
| 261 |
+
end-of-line = <Control-Key-Right>
|
| 262 |
+
comment-region = <Control-Key-3>
|
| 263 |
+
redo = <Shift-Command-Key-Z>
|
| 264 |
+
close-window = <Command-Key-w>
|
| 265 |
+
restart-shell = <Control-Key-F6>
|
| 266 |
+
save-window-as-file = <Shift-Command-Key-S>
|
| 267 |
+
close-all-windows = <Command-Key-q>
|
| 268 |
+
view-restart = <Key-F6>
|
| 269 |
+
tabify-region = <Control-Key-5>
|
| 270 |
+
find-again = <Command-Key-g> <Key-F3>
|
| 271 |
+
find = <Command-Key-f>
|
| 272 |
+
toggle-auto-coloring = <Control-Key-slash>
|
| 273 |
+
select-all = <Command-Key-a>
|
| 274 |
+
smart-backspace = <Key-BackSpace>
|
| 275 |
+
change-indentwidth = <Control-Key-u>
|
| 276 |
+
do-nothing = <Control-Key-F12>
|
| 277 |
+
smart-indent = <Key-Tab>
|
| 278 |
+
center-insert = <Control-Key-l>
|
| 279 |
+
history-next = <Control-Key-n>
|
| 280 |
+
del-word-right = <Option-Key-Delete>
|
| 281 |
+
undo = <Command-Key-z>
|
| 282 |
+
save-window = <Command-Key-s>
|
| 283 |
+
uncomment-region = <Control-Key-4>
|
| 284 |
+
cut = <Command-Key-x>
|
| 285 |
+
find-in-files = <Command-Key-F3>
|
| 286 |
+
dedent-region = <Command-Key-bracketleft>
|
| 287 |
+
copy = <Command-Key-c>
|
| 288 |
+
paste = <Command-Key-v>
|
| 289 |
+
indent-region = <Command-Key-bracketright>
|
| 290 |
+
del-word-left = <Option-Key-BackSpace> <Option-Command-Key-BackSpace>
|
| 291 |
+
newline-and-indent = <Key-Return> <Key-KP_Enter>
|
| 292 |
+
end-of-file = <Control-Key-d>
|
| 293 |
+
open-class-browser = <Command-Key-b>
|
| 294 |
+
open-new-window = <Command-Key-n>
|
| 295 |
+
open-module = <Command-Key-m>
|
| 296 |
+
find-selection = <Shift-Command-Key-F3>
|
| 297 |
+
python-context-help = <Shift-Key-F1>
|
| 298 |
+
save-copy-of-window-as-file = <Option-Command-Key-s>
|
| 299 |
+
open-window-from-file = <Command-Key-o>
|
| 300 |
+
python-docs = <Key-F1>
|
| 301 |
+
force-open-completions= <Control-Key-space>
|
| 302 |
+
expand-word= <Option-Key-slash>
|
| 303 |
+
force-open-calltip= <Control-Key-backslash>
|
| 304 |
+
format-paragraph= <Option-Key-q>
|
| 305 |
+
flash-paren= <Control-Key-0>
|
| 306 |
+
run-module= <Key-F5>
|
| 307 |
+
run-custom= <Shift-Key-F5>
|
| 308 |
+
check-module= <Option-Key-x>
|
| 309 |
+
zoom-height= <Option-Key-0>
|
parrot/lib/python3.10/idlelib/config-main.def
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# IDLE reads several config files to determine user preferences. This
|
| 2 |
+
# file is the default config file for general idle settings.
|
| 3 |
+
#
|
| 4 |
+
# When IDLE starts, it will look in
|
| 5 |
+
# the following two sets of files, in order:
|
| 6 |
+
#
|
| 7 |
+
# default configuration files in idlelib
|
| 8 |
+
# --------------------------------------
|
| 9 |
+
# config-main.def default general config file
|
| 10 |
+
# config-extensions.def default extension config file
|
| 11 |
+
# config-highlight.def default highlighting config file
|
| 12 |
+
# config-keys.def default keybinding config file
|
| 13 |
+
#
|
| 14 |
+
# user configuration files in ~/.idlerc
|
| 15 |
+
# -------------------------------------
|
| 16 |
+
# config-main.cfg user general config file
|
| 17 |
+
# config-extensions.cfg user extension config file
|
| 18 |
+
# config-highlight.cfg user highlighting config file
|
| 19 |
+
# config-keys.cfg user keybinding config file
|
| 20 |
+
#
|
| 21 |
+
# On Windows, the default location of the home directory ('~' above)
|
| 22 |
+
# depends on the version. For Windows 10, it is C:\Users\<username>.
|
| 23 |
+
#
|
| 24 |
+
# Any options the user saves through the config dialog will be saved to
|
| 25 |
+
# the relevant user config file. Reverting any general or extension
|
| 26 |
+
# setting to the default causes that entry to be wiped from the user
|
| 27 |
+
# file and re-read from the default file. This rule applies to each
|
| 28 |
+
# item, except that the three editor font items are saved as a group.
|
| 29 |
+
#
|
| 30 |
+
# User highlighting themes and keybinding sets must have (section) names
|
| 31 |
+
# distinct from the default names. All items are added and saved as a
|
| 32 |
+
# group. They are retained unless specifically deleted within the config
|
| 33 |
+
# dialog. Choosing one of the default themes or keysets just applies the
|
| 34 |
+
# relevant settings from the default file.
|
| 35 |
+
#
|
| 36 |
+
# Additional help sources are listed in the [HelpFiles] section below
|
| 37 |
+
# and should be viewable by a web browser (or the Windows Help viewer in
|
| 38 |
+
# the case of .chm files). These sources will be listed on the Help
|
| 39 |
+
# menu. The pattern, and two examples, are:
|
| 40 |
+
#
|
| 41 |
+
# <sequence_number = menu item;/path/to/help/source>
|
| 42 |
+
# 1 = IDLE;C:/Programs/Python36/Lib/idlelib/help.html
|
| 43 |
+
# 2 = Pillow;https://pillow.readthedocs.io/en/latest/
|
| 44 |
+
#
|
| 45 |
+
# You can't use a semi-colon in a menu item or path. The path will be
|
| 46 |
+
# platform specific because of path separators, drive specs etc.
|
| 47 |
+
#
|
| 48 |
+
# The default files should not be edited except to add new sections to
|
| 49 |
+
# config-extensions.def for added extensions. The user files should be
|
| 50 |
+
# modified through the Settings dialog.
|
| 51 |
+
|
| 52 |
+
[General]
|
| 53 |
+
editor-on-startup= 0
|
| 54 |
+
autosave= 0
|
| 55 |
+
print-command-posix=lpr %%s
|
| 56 |
+
print-command-win=start /min notepad /p %%s
|
| 57 |
+
delete-exitfunc= 1
|
| 58 |
+
|
| 59 |
+
[EditorWindow]
|
| 60 |
+
width= 80
|
| 61 |
+
height= 40
|
| 62 |
+
cursor-blink= 1
|
| 63 |
+
font= TkFixedFont
|
| 64 |
+
# For TkFixedFont, the actual size and boldness are obtained from tk
|
| 65 |
+
# and override 10 and 0. See idlelib.config.IdleConf.GetFont
|
| 66 |
+
font-size= 10
|
| 67 |
+
font-bold= 0
|
| 68 |
+
encoding= none
|
| 69 |
+
line-numbers-default= 0
|
| 70 |
+
|
| 71 |
+
[PyShell]
|
| 72 |
+
auto-squeeze-min-lines= 50
|
| 73 |
+
|
| 74 |
+
[Indent]
|
| 75 |
+
use-spaces= 1
|
| 76 |
+
num-spaces= 4
|
| 77 |
+
|
| 78 |
+
[Theme]
|
| 79 |
+
default= 1
|
| 80 |
+
name= IDLE Classic
|
| 81 |
+
name2=
|
| 82 |
+
# name2 set in user config-main.cfg for themes added after 2015 Oct 1
|
| 83 |
+
|
| 84 |
+
[Keys]
|
| 85 |
+
default= 1
|
| 86 |
+
name=
|
| 87 |
+
name2=
|
| 88 |
+
# name2 set in user config-main.cfg for keys added after 2016 July 1
|
| 89 |
+
|
| 90 |
+
[History]
|
| 91 |
+
cyclic=1
|
| 92 |
+
|
| 93 |
+
[HelpFiles]
|
parrot/lib/python3.10/idlelib/configdialog.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
parrot/lib/python3.10/idlelib/debugger.py
ADDED
|
@@ -0,0 +1,550 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
from tkinter.ttk import Frame, Scrollbar
|
| 6 |
+
|
| 7 |
+
from idlelib import macosx
|
| 8 |
+
from idlelib.scrolledlist import ScrolledList
|
| 9 |
+
from idlelib.window import ListedToplevel
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Idb(bdb.Bdb):
|
| 13 |
+
|
| 14 |
+
def __init__(self, gui):
|
| 15 |
+
self.gui = gui # An instance of Debugger or proxy of remote.
|
| 16 |
+
bdb.Bdb.__init__(self)
|
| 17 |
+
|
| 18 |
+
def user_line(self, frame):
|
| 19 |
+
if self.in_rpc_code(frame):
|
| 20 |
+
self.set_step()
|
| 21 |
+
return
|
| 22 |
+
message = self.__frame2message(frame)
|
| 23 |
+
try:
|
| 24 |
+
self.gui.interaction(message, frame)
|
| 25 |
+
except TclError: # When closing debugger window with [x] in 3.x
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
def user_exception(self, frame, info):
|
| 29 |
+
if self.in_rpc_code(frame):
|
| 30 |
+
self.set_step()
|
| 31 |
+
return
|
| 32 |
+
message = self.__frame2message(frame)
|
| 33 |
+
self.gui.interaction(message, frame, info)
|
| 34 |
+
|
| 35 |
+
def in_rpc_code(self, frame):
|
| 36 |
+
if frame.f_code.co_filename.count('rpc.py'):
|
| 37 |
+
return True
|
| 38 |
+
else:
|
| 39 |
+
prev_frame = frame.f_back
|
| 40 |
+
prev_name = prev_frame.f_code.co_filename
|
| 41 |
+
if 'idlelib' in prev_name and 'debugger' in prev_name:
|
| 42 |
+
# catch both idlelib/debugger.py and idlelib/debugger_r.py
|
| 43 |
+
# on both Posix and Windows
|
| 44 |
+
return False
|
| 45 |
+
return self.in_rpc_code(prev_frame)
|
| 46 |
+
|
| 47 |
+
def __frame2message(self, frame):
|
| 48 |
+
code = frame.f_code
|
| 49 |
+
filename = code.co_filename
|
| 50 |
+
lineno = frame.f_lineno
|
| 51 |
+
basename = os.path.basename(filename)
|
| 52 |
+
message = "%s:%s" % (basename, lineno)
|
| 53 |
+
if code.co_name != "?":
|
| 54 |
+
message = "%s: %s()" % (message, code.co_name)
|
| 55 |
+
return message
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class Debugger:
|
| 59 |
+
|
| 60 |
+
vstack = vsource = vlocals = vglobals = None
|
| 61 |
+
|
| 62 |
+
def __init__(self, pyshell, idb=None):
|
| 63 |
+
if idb is None:
|
| 64 |
+
idb = Idb(self)
|
| 65 |
+
self.pyshell = pyshell
|
| 66 |
+
self.idb = idb # If passed, a proxy of remote instance.
|
| 67 |
+
self.frame = None
|
| 68 |
+
self.make_gui()
|
| 69 |
+
self.interacting = 0
|
| 70 |
+
self.nesting_level = 0
|
| 71 |
+
|
| 72 |
+
def run(self, *args):
|
| 73 |
+
# Deal with the scenario where we've already got a program running
|
| 74 |
+
# in the debugger and we want to start another. If that is the case,
|
| 75 |
+
# our second 'run' was invoked from an event dispatched not from
|
| 76 |
+
# the main event loop, but from the nested event loop in 'interaction'
|
| 77 |
+
# below. So our stack looks something like this:
|
| 78 |
+
# outer main event loop
|
| 79 |
+
# run()
|
| 80 |
+
# <running program with traces>
|
| 81 |
+
# callback to debugger's interaction()
|
| 82 |
+
# nested event loop
|
| 83 |
+
# run() for second command
|
| 84 |
+
#
|
| 85 |
+
# This kind of nesting of event loops causes all kinds of problems
|
| 86 |
+
# (see e.g. issue #24455) especially when dealing with running as a
|
| 87 |
+
# subprocess, where there's all kinds of extra stuff happening in
|
| 88 |
+
# there - insert a traceback.print_stack() to check it out.
|
| 89 |
+
#
|
| 90 |
+
# By this point, we've already called restart_subprocess() in
|
| 91 |
+
# ScriptBinding. However, we also need to unwind the stack back to
|
| 92 |
+
# that outer event loop. To accomplish this, we:
|
| 93 |
+
# - return immediately from the nested run()
|
| 94 |
+
# - abort_loop ensures the nested event loop will terminate
|
| 95 |
+
# - the debugger's interaction routine completes normally
|
| 96 |
+
# - the restart_subprocess() will have taken care of stopping
|
| 97 |
+
# the running program, which will also let the outer run complete
|
| 98 |
+
#
|
| 99 |
+
# That leaves us back at the outer main event loop, at which point our
|
| 100 |
+
# after event can fire, and we'll come back to this routine with a
|
| 101 |
+
# clean stack.
|
| 102 |
+
if self.nesting_level > 0:
|
| 103 |
+
self.abort_loop()
|
| 104 |
+
self.root.after(100, lambda: self.run(*args))
|
| 105 |
+
return
|
| 106 |
+
try:
|
| 107 |
+
self.interacting = 1
|
| 108 |
+
return self.idb.run(*args)
|
| 109 |
+
finally:
|
| 110 |
+
self.interacting = 0
|
| 111 |
+
|
| 112 |
+
def close(self, event=None):
|
| 113 |
+
try:
|
| 114 |
+
self.quit()
|
| 115 |
+
except Exception:
|
| 116 |
+
pass
|
| 117 |
+
if self.interacting:
|
| 118 |
+
self.top.bell()
|
| 119 |
+
return
|
| 120 |
+
if self.stackviewer:
|
| 121 |
+
self.stackviewer.close(); self.stackviewer = None
|
| 122 |
+
# Clean up pyshell if user clicked debugger control close widget.
|
| 123 |
+
# (Causes a harmless extra cycle through close_debugger() if user
|
| 124 |
+
# toggled debugger from pyshell Debug menu)
|
| 125 |
+
self.pyshell.close_debugger()
|
| 126 |
+
# Now close the debugger control window....
|
| 127 |
+
self.top.destroy()
|
| 128 |
+
|
| 129 |
+
def make_gui(self):
|
| 130 |
+
pyshell = self.pyshell
|
| 131 |
+
self.flist = pyshell.flist
|
| 132 |
+
self.root = root = pyshell.root
|
| 133 |
+
self.top = top = ListedToplevel(root)
|
| 134 |
+
self.top.wm_title("Debug Control")
|
| 135 |
+
self.top.wm_iconname("Debug")
|
| 136 |
+
top.wm_protocol("WM_DELETE_WINDOW", self.close)
|
| 137 |
+
self.top.bind("<Escape>", self.close)
|
| 138 |
+
#
|
| 139 |
+
self.bframe = bframe = Frame(top)
|
| 140 |
+
self.bframe.pack(anchor="w")
|
| 141 |
+
self.buttons = bl = []
|
| 142 |
+
#
|
| 143 |
+
self.bcont = b = Button(bframe, text="Go", command=self.cont)
|
| 144 |
+
bl.append(b)
|
| 145 |
+
self.bstep = b = Button(bframe, text="Step", command=self.step)
|
| 146 |
+
bl.append(b)
|
| 147 |
+
self.bnext = b = Button(bframe, text="Over", command=self.next)
|
| 148 |
+
bl.append(b)
|
| 149 |
+
self.bret = b = Button(bframe, text="Out", command=self.ret)
|
| 150 |
+
bl.append(b)
|
| 151 |
+
self.bret = b = Button(bframe, text="Quit", command=self.quit)
|
| 152 |
+
bl.append(b)
|
| 153 |
+
#
|
| 154 |
+
for b in bl:
|
| 155 |
+
b.configure(state="disabled")
|
| 156 |
+
b.pack(side="left")
|
| 157 |
+
#
|
| 158 |
+
self.cframe = cframe = Frame(bframe)
|
| 159 |
+
self.cframe.pack(side="left")
|
| 160 |
+
#
|
| 161 |
+
if not self.vstack:
|
| 162 |
+
self.__class__.vstack = BooleanVar(top)
|
| 163 |
+
self.vstack.set(1)
|
| 164 |
+
self.bstack = Checkbutton(cframe,
|
| 165 |
+
text="Stack", command=self.show_stack, variable=self.vstack)
|
| 166 |
+
self.bstack.grid(row=0, column=0)
|
| 167 |
+
if not self.vsource:
|
| 168 |
+
self.__class__.vsource = BooleanVar(top)
|
| 169 |
+
self.bsource = Checkbutton(cframe,
|
| 170 |
+
text="Source", command=self.show_source, variable=self.vsource)
|
| 171 |
+
self.bsource.grid(row=0, column=1)
|
| 172 |
+
if not self.vlocals:
|
| 173 |
+
self.__class__.vlocals = BooleanVar(top)
|
| 174 |
+
self.vlocals.set(1)
|
| 175 |
+
self.blocals = Checkbutton(cframe,
|
| 176 |
+
text="Locals", command=self.show_locals, variable=self.vlocals)
|
| 177 |
+
self.blocals.grid(row=1, column=0)
|
| 178 |
+
if not self.vglobals:
|
| 179 |
+
self.__class__.vglobals = BooleanVar(top)
|
| 180 |
+
self.bglobals = Checkbutton(cframe,
|
| 181 |
+
text="Globals", command=self.show_globals, variable=self.vglobals)
|
| 182 |
+
self.bglobals.grid(row=1, column=1)
|
| 183 |
+
#
|
| 184 |
+
self.status = Label(top, anchor="w")
|
| 185 |
+
self.status.pack(anchor="w")
|
| 186 |
+
self.error = Label(top, anchor="w")
|
| 187 |
+
self.error.pack(anchor="w", fill="x")
|
| 188 |
+
self.errorbg = self.error.cget("background")
|
| 189 |
+
#
|
| 190 |
+
self.fstack = Frame(top, height=1)
|
| 191 |
+
self.fstack.pack(expand=1, fill="both")
|
| 192 |
+
self.flocals = Frame(top)
|
| 193 |
+
self.flocals.pack(expand=1, fill="both")
|
| 194 |
+
self.fglobals = Frame(top, height=1)
|
| 195 |
+
self.fglobals.pack(expand=1, fill="both")
|
| 196 |
+
#
|
| 197 |
+
if self.vstack.get():
|
| 198 |
+
self.show_stack()
|
| 199 |
+
if self.vlocals.get():
|
| 200 |
+
self.show_locals()
|
| 201 |
+
if self.vglobals.get():
|
| 202 |
+
self.show_globals()
|
| 203 |
+
|
| 204 |
+
def interaction(self, message, frame, info=None):
|
| 205 |
+
self.frame = frame
|
| 206 |
+
self.status.configure(text=message)
|
| 207 |
+
#
|
| 208 |
+
if info:
|
| 209 |
+
type, value, tb = info
|
| 210 |
+
try:
|
| 211 |
+
m1 = type.__name__
|
| 212 |
+
except AttributeError:
|
| 213 |
+
m1 = "%s" % str(type)
|
| 214 |
+
if value is not None:
|
| 215 |
+
try:
|
| 216 |
+
m1 = "%s: %s" % (m1, str(value))
|
| 217 |
+
except:
|
| 218 |
+
pass
|
| 219 |
+
bg = "yellow"
|
| 220 |
+
else:
|
| 221 |
+
m1 = ""
|
| 222 |
+
tb = None
|
| 223 |
+
bg = self.errorbg
|
| 224 |
+
self.error.configure(text=m1, background=bg)
|
| 225 |
+
#
|
| 226 |
+
sv = self.stackviewer
|
| 227 |
+
if sv:
|
| 228 |
+
stack, i = self.idb.get_stack(self.frame, tb)
|
| 229 |
+
sv.load_stack(stack, i)
|
| 230 |
+
#
|
| 231 |
+
self.show_variables(1)
|
| 232 |
+
#
|
| 233 |
+
if self.vsource.get():
|
| 234 |
+
self.sync_source_line()
|
| 235 |
+
#
|
| 236 |
+
for b in self.buttons:
|
| 237 |
+
b.configure(state="normal")
|
| 238 |
+
#
|
| 239 |
+
self.top.wakeup()
|
| 240 |
+
# Nested main loop: Tkinter's main loop is not reentrant, so use
|
| 241 |
+
# Tcl's vwait facility, which reenters the event loop until an
|
| 242 |
+
# event handler sets the variable we're waiting on
|
| 243 |
+
self.nesting_level += 1
|
| 244 |
+
self.root.tk.call('vwait', '::idledebugwait')
|
| 245 |
+
self.nesting_level -= 1
|
| 246 |
+
#
|
| 247 |
+
for b in self.buttons:
|
| 248 |
+
b.configure(state="disabled")
|
| 249 |
+
self.status.configure(text="")
|
| 250 |
+
self.error.configure(text="", background=self.errorbg)
|
| 251 |
+
self.frame = None
|
| 252 |
+
|
| 253 |
+
def sync_source_line(self):
|
| 254 |
+
frame = self.frame
|
| 255 |
+
if not frame:
|
| 256 |
+
return
|
| 257 |
+
filename, lineno = self.__frame2fileline(frame)
|
| 258 |
+
if filename[:1] + filename[-1:] != "<>" and os.path.exists(filename):
|
| 259 |
+
self.flist.gotofileline(filename, lineno)
|
| 260 |
+
|
| 261 |
+
def __frame2fileline(self, frame):
|
| 262 |
+
code = frame.f_code
|
| 263 |
+
filename = code.co_filename
|
| 264 |
+
lineno = frame.f_lineno
|
| 265 |
+
return filename, lineno
|
| 266 |
+
|
| 267 |
+
def cont(self):
|
| 268 |
+
self.idb.set_continue()
|
| 269 |
+
self.abort_loop()
|
| 270 |
+
|
| 271 |
+
def step(self):
|
| 272 |
+
self.idb.set_step()
|
| 273 |
+
self.abort_loop()
|
| 274 |
+
|
| 275 |
+
def next(self):
|
| 276 |
+
self.idb.set_next(self.frame)
|
| 277 |
+
self.abort_loop()
|
| 278 |
+
|
| 279 |
+
def ret(self):
|
| 280 |
+
self.idb.set_return(self.frame)
|
| 281 |
+
self.abort_loop()
|
| 282 |
+
|
| 283 |
+
def quit(self):
|
| 284 |
+
self.idb.set_quit()
|
| 285 |
+
self.abort_loop()
|
| 286 |
+
|
| 287 |
+
def abort_loop(self):
|
| 288 |
+
self.root.tk.call('set', '::idledebugwait', '1')
|
| 289 |
+
|
| 290 |
+
stackviewer = None
|
| 291 |
+
|
| 292 |
+
def show_stack(self):
|
| 293 |
+
if not self.stackviewer and self.vstack.get():
|
| 294 |
+
self.stackviewer = sv = StackViewer(self.fstack, self.flist, self)
|
| 295 |
+
if self.frame:
|
| 296 |
+
stack, i = self.idb.get_stack(self.frame, None)
|
| 297 |
+
sv.load_stack(stack, i)
|
| 298 |
+
else:
|
| 299 |
+
sv = self.stackviewer
|
| 300 |
+
if sv and not self.vstack.get():
|
| 301 |
+
self.stackviewer = None
|
| 302 |
+
sv.close()
|
| 303 |
+
self.fstack['height'] = 1
|
| 304 |
+
|
| 305 |
+
def show_source(self):
|
| 306 |
+
if self.vsource.get():
|
| 307 |
+
self.sync_source_line()
|
| 308 |
+
|
| 309 |
+
def show_frame(self, stackitem):
|
| 310 |
+
self.frame = stackitem[0] # lineno is stackitem[1]
|
| 311 |
+
self.show_variables()
|
| 312 |
+
|
| 313 |
+
localsviewer = None
|
| 314 |
+
globalsviewer = None
|
| 315 |
+
|
| 316 |
+
def show_locals(self):
|
| 317 |
+
lv = self.localsviewer
|
| 318 |
+
if self.vlocals.get():
|
| 319 |
+
if not lv:
|
| 320 |
+
self.localsviewer = NamespaceViewer(self.flocals, "Locals")
|
| 321 |
+
else:
|
| 322 |
+
if lv:
|
| 323 |
+
self.localsviewer = None
|
| 324 |
+
lv.close()
|
| 325 |
+
self.flocals['height'] = 1
|
| 326 |
+
self.show_variables()
|
| 327 |
+
|
| 328 |
+
def show_globals(self):
|
| 329 |
+
gv = self.globalsviewer
|
| 330 |
+
if self.vglobals.get():
|
| 331 |
+
if not gv:
|
| 332 |
+
self.globalsviewer = NamespaceViewer(self.fglobals, "Globals")
|
| 333 |
+
else:
|
| 334 |
+
if gv:
|
| 335 |
+
self.globalsviewer = None
|
| 336 |
+
gv.close()
|
| 337 |
+
self.fglobals['height'] = 1
|
| 338 |
+
self.show_variables()
|
| 339 |
+
|
| 340 |
+
def show_variables(self, force=0):
|
| 341 |
+
lv = self.localsviewer
|
| 342 |
+
gv = self.globalsviewer
|
| 343 |
+
frame = self.frame
|
| 344 |
+
if not frame:
|
| 345 |
+
ldict = gdict = None
|
| 346 |
+
else:
|
| 347 |
+
ldict = frame.f_locals
|
| 348 |
+
gdict = frame.f_globals
|
| 349 |
+
if lv and gv and ldict is gdict:
|
| 350 |
+
ldict = None
|
| 351 |
+
if lv:
|
| 352 |
+
lv.load_dict(ldict, force, self.pyshell.interp.rpcclt)
|
| 353 |
+
if gv:
|
| 354 |
+
gv.load_dict(gdict, force, self.pyshell.interp.rpcclt)
|
| 355 |
+
|
| 356 |
+
def set_breakpoint_here(self, filename, lineno):
|
| 357 |
+
self.idb.set_break(filename, lineno)
|
| 358 |
+
|
| 359 |
+
def clear_breakpoint_here(self, filename, lineno):
|
| 360 |
+
self.idb.clear_break(filename, lineno)
|
| 361 |
+
|
| 362 |
+
def clear_file_breaks(self, filename):
|
| 363 |
+
self.idb.clear_all_file_breaks(filename)
|
| 364 |
+
|
| 365 |
+
def load_breakpoints(self):
|
| 366 |
+
"Load PyShellEditorWindow breakpoints into subprocess debugger"
|
| 367 |
+
for editwin in self.pyshell.flist.inversedict:
|
| 368 |
+
filename = editwin.io.filename
|
| 369 |
+
try:
|
| 370 |
+
for lineno in editwin.breakpoints:
|
| 371 |
+
self.set_breakpoint_here(filename, lineno)
|
| 372 |
+
except AttributeError:
|
| 373 |
+
continue
|
| 374 |
+
|
| 375 |
+
class StackViewer(ScrolledList):
|
| 376 |
+
|
| 377 |
+
def __init__(self, master, flist, gui):
|
| 378 |
+
if macosx.isAquaTk():
|
| 379 |
+
# At least on with the stock AquaTk version on OSX 10.4 you'll
|
| 380 |
+
# get a shaking GUI that eventually kills IDLE if the width
|
| 381 |
+
# argument is specified.
|
| 382 |
+
ScrolledList.__init__(self, master)
|
| 383 |
+
else:
|
| 384 |
+
ScrolledList.__init__(self, master, width=80)
|
| 385 |
+
self.flist = flist
|
| 386 |
+
self.gui = gui
|
| 387 |
+
self.stack = []
|
| 388 |
+
|
| 389 |
+
def load_stack(self, stack, index=None):
|
| 390 |
+
self.stack = stack
|
| 391 |
+
self.clear()
|
| 392 |
+
for i in range(len(stack)):
|
| 393 |
+
frame, lineno = stack[i]
|
| 394 |
+
try:
|
| 395 |
+
modname = frame.f_globals["__name__"]
|
| 396 |
+
except:
|
| 397 |
+
modname = "?"
|
| 398 |
+
code = frame.f_code
|
| 399 |
+
filename = code.co_filename
|
| 400 |
+
funcname = code.co_name
|
| 401 |
+
import linecache
|
| 402 |
+
sourceline = linecache.getline(filename, lineno)
|
| 403 |
+
sourceline = sourceline.strip()
|
| 404 |
+
if funcname in ("?", "", None):
|
| 405 |
+
item = "%s, line %d: %s" % (modname, lineno, sourceline)
|
| 406 |
+
else:
|
| 407 |
+
item = "%s.%s(), line %d: %s" % (modname, funcname,
|
| 408 |
+
lineno, sourceline)
|
| 409 |
+
if i == index:
|
| 410 |
+
item = "> " + item
|
| 411 |
+
self.append(item)
|
| 412 |
+
if index is not None:
|
| 413 |
+
self.select(index)
|
| 414 |
+
|
| 415 |
+
def popup_event(self, event):
|
| 416 |
+
"override base method"
|
| 417 |
+
if self.stack:
|
| 418 |
+
return ScrolledList.popup_event(self, event)
|
| 419 |
+
|
| 420 |
+
def fill_menu(self):
|
| 421 |
+
"override base method"
|
| 422 |
+
menu = self.menu
|
| 423 |
+
menu.add_command(label="Go to source line",
|
| 424 |
+
command=self.goto_source_line)
|
| 425 |
+
menu.add_command(label="Show stack frame",
|
| 426 |
+
command=self.show_stack_frame)
|
| 427 |
+
|
| 428 |
+
def on_select(self, index):
|
| 429 |
+
"override base method"
|
| 430 |
+
if 0 <= index < len(self.stack):
|
| 431 |
+
self.gui.show_frame(self.stack[index])
|
| 432 |
+
|
| 433 |
+
def on_double(self, index):
|
| 434 |
+
"override base method"
|
| 435 |
+
self.show_source(index)
|
| 436 |
+
|
| 437 |
+
def goto_source_line(self):
|
| 438 |
+
index = self.listbox.index("active")
|
| 439 |
+
self.show_source(index)
|
| 440 |
+
|
| 441 |
+
def show_stack_frame(self):
|
| 442 |
+
index = self.listbox.index("active")
|
| 443 |
+
if 0 <= index < len(self.stack):
|
| 444 |
+
self.gui.show_frame(self.stack[index])
|
| 445 |
+
|
| 446 |
+
def show_source(self, index):
|
| 447 |
+
if not (0 <= index < len(self.stack)):
|
| 448 |
+
return
|
| 449 |
+
frame, lineno = self.stack[index]
|
| 450 |
+
code = frame.f_code
|
| 451 |
+
filename = code.co_filename
|
| 452 |
+
if os.path.isfile(filename):
|
| 453 |
+
edit = self.flist.open(filename)
|
| 454 |
+
if edit:
|
| 455 |
+
edit.gotoline(lineno)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
class NamespaceViewer:
|
| 459 |
+
|
| 460 |
+
def __init__(self, master, title, dict=None):
|
| 461 |
+
width = 0
|
| 462 |
+
height = 40
|
| 463 |
+
if dict:
|
| 464 |
+
height = 20*len(dict) # XXX 20 == observed height of Entry widget
|
| 465 |
+
self.master = master
|
| 466 |
+
self.title = title
|
| 467 |
+
import reprlib
|
| 468 |
+
self.repr = reprlib.Repr()
|
| 469 |
+
self.repr.maxstring = 60
|
| 470 |
+
self.repr.maxother = 60
|
| 471 |
+
self.frame = frame = Frame(master)
|
| 472 |
+
self.frame.pack(expand=1, fill="both")
|
| 473 |
+
self.label = Label(frame, text=title, borderwidth=2, relief="groove")
|
| 474 |
+
self.label.pack(fill="x")
|
| 475 |
+
self.vbar = vbar = Scrollbar(frame, name="vbar")
|
| 476 |
+
vbar.pack(side="right", fill="y")
|
| 477 |
+
self.canvas = canvas = Canvas(frame,
|
| 478 |
+
height=min(300, max(40, height)),
|
| 479 |
+
scrollregion=(0, 0, width, height))
|
| 480 |
+
canvas.pack(side="left", fill="both", expand=1)
|
| 481 |
+
vbar["command"] = canvas.yview
|
| 482 |
+
canvas["yscrollcommand"] = vbar.set
|
| 483 |
+
self.subframe = subframe = Frame(canvas)
|
| 484 |
+
self.sfid = canvas.create_window(0, 0, window=subframe, anchor="nw")
|
| 485 |
+
self.load_dict(dict)
|
| 486 |
+
|
| 487 |
+
dict = -1
|
| 488 |
+
|
| 489 |
+
def load_dict(self, dict, force=0, rpc_client=None):
|
| 490 |
+
if dict is self.dict and not force:
|
| 491 |
+
return
|
| 492 |
+
subframe = self.subframe
|
| 493 |
+
frame = self.frame
|
| 494 |
+
for c in list(subframe.children.values()):
|
| 495 |
+
c.destroy()
|
| 496 |
+
self.dict = None
|
| 497 |
+
if not dict:
|
| 498 |
+
l = Label(subframe, text="None")
|
| 499 |
+
l.grid(row=0, column=0)
|
| 500 |
+
else:
|
| 501 |
+
#names = sorted(dict)
|
| 502 |
+
###
|
| 503 |
+
# Because of (temporary) limitations on the dict_keys type (not yet
|
| 504 |
+
# public or pickleable), have the subprocess to send a list of
|
| 505 |
+
# keys, not a dict_keys object. sorted() will take a dict_keys
|
| 506 |
+
# (no subprocess) or a list.
|
| 507 |
+
#
|
| 508 |
+
# There is also an obscure bug in sorted(dict) where the
|
| 509 |
+
# interpreter gets into a loop requesting non-existing dict[0],
|
| 510 |
+
# dict[1], dict[2], etc from the debugger_r.DictProxy.
|
| 511 |
+
###
|
| 512 |
+
keys_list = dict.keys()
|
| 513 |
+
names = sorted(keys_list)
|
| 514 |
+
###
|
| 515 |
+
row = 0
|
| 516 |
+
for name in names:
|
| 517 |
+
value = dict[name]
|
| 518 |
+
svalue = self.repr.repr(value) # repr(value)
|
| 519 |
+
# Strip extra quotes caused by calling repr on the (already)
|
| 520 |
+
# repr'd value sent across the RPC interface:
|
| 521 |
+
if rpc_client:
|
| 522 |
+
svalue = svalue[1:-1]
|
| 523 |
+
l = Label(subframe, text=name)
|
| 524 |
+
l.grid(row=row, column=0, sticky="nw")
|
| 525 |
+
l = Entry(subframe, width=0, borderwidth=0)
|
| 526 |
+
l.insert(0, svalue)
|
| 527 |
+
l.grid(row=row, column=1, sticky="nw")
|
| 528 |
+
row = row+1
|
| 529 |
+
self.dict = dict
|
| 530 |
+
# XXX Could we use a <Configure> callback for the following?
|
| 531 |
+
subframe.update_idletasks() # Alas!
|
| 532 |
+
width = subframe.winfo_reqwidth()
|
| 533 |
+
height = subframe.winfo_reqheight()
|
| 534 |
+
canvas = self.canvas
|
| 535 |
+
self.canvas["scrollregion"] = (0, 0, width, height)
|
| 536 |
+
if height > 300:
|
| 537 |
+
canvas["height"] = 300
|
| 538 |
+
frame.pack(expand=1)
|
| 539 |
+
else:
|
| 540 |
+
canvas["height"] = height
|
| 541 |
+
frame.pack(expand=0)
|
| 542 |
+
|
| 543 |
+
def close(self):
|
| 544 |
+
self.frame.destroy()
|
| 545 |
+
|
| 546 |
+
if __name__ == "__main__":
|
| 547 |
+
from unittest import main
|
| 548 |
+
main('idlelib.idle_test.test_debugger', verbosity=2, exit=False)
|
| 549 |
+
|
| 550 |
+
# TODO: htest?
|
parrot/lib/python3.10/idlelib/debugger_r.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Support for remote Python debugging.
|
| 2 |
+
|
| 3 |
+
Some ASCII art to describe the structure:
|
| 4 |
+
|
| 5 |
+
IN PYTHON SUBPROCESS # IN IDLE PROCESS
|
| 6 |
+
#
|
| 7 |
+
# oid='gui_adapter'
|
| 8 |
+
+----------+ # +------------+ +-----+
|
| 9 |
+
| GUIProxy |--remote#call-->| GUIAdapter |--calls-->| GUI |
|
| 10 |
+
+-----+--calls-->+----------+ # +------------+ +-----+
|
| 11 |
+
| Idb | # /
|
| 12 |
+
+-----+<-calls--+------------+ # +----------+<--calls-/
|
| 13 |
+
| IdbAdapter |<--remote#call--| IdbProxy |
|
| 14 |
+
+------------+ # +----------+
|
| 15 |
+
oid='idb_adapter' #
|
| 16 |
+
|
| 17 |
+
The purpose of the Proxy and Adapter classes is to translate certain
|
| 18 |
+
arguments and return values that cannot be transported through the RPC
|
| 19 |
+
barrier, in particular frame and traceback objects.
|
| 20 |
+
|
| 21 |
+
"""
|
| 22 |
+
import reprlib
|
| 23 |
+
import types
|
| 24 |
+
from idlelib import debugger
|
| 25 |
+
|
| 26 |
+
debugging = 0
|
| 27 |
+
|
| 28 |
+
idb_adap_oid = "idb_adapter"
|
| 29 |
+
gui_adap_oid = "gui_adapter"
|
| 30 |
+
|
| 31 |
+
#=======================================
|
| 32 |
+
#
|
| 33 |
+
# In the PYTHON subprocess:
|
| 34 |
+
|
| 35 |
+
frametable = {}
|
| 36 |
+
dicttable = {}
|
| 37 |
+
codetable = {}
|
| 38 |
+
tracebacktable = {}
|
| 39 |
+
|
| 40 |
+
def wrap_frame(frame):
|
| 41 |
+
fid = id(frame)
|
| 42 |
+
frametable[fid] = frame
|
| 43 |
+
return fid
|
| 44 |
+
|
| 45 |
+
def wrap_info(info):
|
| 46 |
+
"replace info[2], a traceback instance, by its ID"
|
| 47 |
+
if info is None:
|
| 48 |
+
return None
|
| 49 |
+
else:
|
| 50 |
+
traceback = info[2]
|
| 51 |
+
assert isinstance(traceback, types.TracebackType)
|
| 52 |
+
traceback_id = id(traceback)
|
| 53 |
+
tracebacktable[traceback_id] = traceback
|
| 54 |
+
modified_info = (info[0], info[1], traceback_id)
|
| 55 |
+
return modified_info
|
| 56 |
+
|
| 57 |
+
class GUIProxy:
|
| 58 |
+
|
| 59 |
+
def __init__(self, conn, gui_adap_oid):
|
| 60 |
+
self.conn = conn
|
| 61 |
+
self.oid = gui_adap_oid
|
| 62 |
+
|
| 63 |
+
def interaction(self, message, frame, info=None):
|
| 64 |
+
# calls rpc.SocketIO.remotecall() via run.MyHandler instance
|
| 65 |
+
# pass frame and traceback object IDs instead of the objects themselves
|
| 66 |
+
self.conn.remotecall(self.oid, "interaction",
|
| 67 |
+
(message, wrap_frame(frame), wrap_info(info)),
|
| 68 |
+
{})
|
| 69 |
+
|
| 70 |
+
class IdbAdapter:
|
| 71 |
+
|
| 72 |
+
def __init__(self, idb):
|
| 73 |
+
self.idb = idb
|
| 74 |
+
|
| 75 |
+
#----------called by an IdbProxy----------
|
| 76 |
+
|
| 77 |
+
def set_step(self):
|
| 78 |
+
self.idb.set_step()
|
| 79 |
+
|
| 80 |
+
def set_quit(self):
|
| 81 |
+
self.idb.set_quit()
|
| 82 |
+
|
| 83 |
+
def set_continue(self):
|
| 84 |
+
self.idb.set_continue()
|
| 85 |
+
|
| 86 |
+
def set_next(self, fid):
|
| 87 |
+
frame = frametable[fid]
|
| 88 |
+
self.idb.set_next(frame)
|
| 89 |
+
|
| 90 |
+
def set_return(self, fid):
|
| 91 |
+
frame = frametable[fid]
|
| 92 |
+
self.idb.set_return(frame)
|
| 93 |
+
|
| 94 |
+
def get_stack(self, fid, tbid):
|
| 95 |
+
frame = frametable[fid]
|
| 96 |
+
if tbid is None:
|
| 97 |
+
tb = None
|
| 98 |
+
else:
|
| 99 |
+
tb = tracebacktable[tbid]
|
| 100 |
+
stack, i = self.idb.get_stack(frame, tb)
|
| 101 |
+
stack = [(wrap_frame(frame2), k) for frame2, k in stack]
|
| 102 |
+
return stack, i
|
| 103 |
+
|
| 104 |
+
def run(self, cmd):
|
| 105 |
+
import __main__
|
| 106 |
+
self.idb.run(cmd, __main__.__dict__)
|
| 107 |
+
|
| 108 |
+
def set_break(self, filename, lineno):
|
| 109 |
+
msg = self.idb.set_break(filename, lineno)
|
| 110 |
+
return msg
|
| 111 |
+
|
| 112 |
+
def clear_break(self, filename, lineno):
|
| 113 |
+
msg = self.idb.clear_break(filename, lineno)
|
| 114 |
+
return msg
|
| 115 |
+
|
| 116 |
+
def clear_all_file_breaks(self, filename):
|
| 117 |
+
msg = self.idb.clear_all_file_breaks(filename)
|
| 118 |
+
return msg
|
| 119 |
+
|
| 120 |
+
#----------called by a FrameProxy----------
|
| 121 |
+
|
| 122 |
+
def frame_attr(self, fid, name):
|
| 123 |
+
frame = frametable[fid]
|
| 124 |
+
return getattr(frame, name)
|
| 125 |
+
|
| 126 |
+
def frame_globals(self, fid):
|
| 127 |
+
frame = frametable[fid]
|
| 128 |
+
dict = frame.f_globals
|
| 129 |
+
did = id(dict)
|
| 130 |
+
dicttable[did] = dict
|
| 131 |
+
return did
|
| 132 |
+
|
| 133 |
+
def frame_locals(self, fid):
|
| 134 |
+
frame = frametable[fid]
|
| 135 |
+
dict = frame.f_locals
|
| 136 |
+
did = id(dict)
|
| 137 |
+
dicttable[did] = dict
|
| 138 |
+
return did
|
| 139 |
+
|
| 140 |
+
def frame_code(self, fid):
|
| 141 |
+
frame = frametable[fid]
|
| 142 |
+
code = frame.f_code
|
| 143 |
+
cid = id(code)
|
| 144 |
+
codetable[cid] = code
|
| 145 |
+
return cid
|
| 146 |
+
|
| 147 |
+
#----------called by a CodeProxy----------
|
| 148 |
+
|
| 149 |
+
def code_name(self, cid):
|
| 150 |
+
code = codetable[cid]
|
| 151 |
+
return code.co_name
|
| 152 |
+
|
| 153 |
+
def code_filename(self, cid):
|
| 154 |
+
code = codetable[cid]
|
| 155 |
+
return code.co_filename
|
| 156 |
+
|
| 157 |
+
#----------called by a DictProxy----------
|
| 158 |
+
|
| 159 |
+
def dict_keys(self, did):
|
| 160 |
+
raise NotImplementedError("dict_keys not public or pickleable")
|
| 161 |
+
## dict = dicttable[did]
|
| 162 |
+
## return dict.keys()
|
| 163 |
+
|
| 164 |
+
### Needed until dict_keys is type is finished and pickealable.
|
| 165 |
+
### Will probably need to extend rpc.py:SocketIO._proxify at that time.
|
| 166 |
+
def dict_keys_list(self, did):
|
| 167 |
+
dict = dicttable[did]
|
| 168 |
+
return list(dict.keys())
|
| 169 |
+
|
| 170 |
+
def dict_item(self, did, key):
|
| 171 |
+
dict = dicttable[did]
|
| 172 |
+
value = dict[key]
|
| 173 |
+
value = reprlib.repr(value) ### can't pickle module 'builtins'
|
| 174 |
+
return value
|
| 175 |
+
|
| 176 |
+
#----------end class IdbAdapter----------
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def start_debugger(rpchandler, gui_adap_oid):
|
| 180 |
+
"""Start the debugger and its RPC link in the Python subprocess
|
| 181 |
+
|
| 182 |
+
Start the subprocess side of the split debugger and set up that side of the
|
| 183 |
+
RPC link by instantiating the GUIProxy, Idb debugger, and IdbAdapter
|
| 184 |
+
objects and linking them together. Register the IdbAdapter with the
|
| 185 |
+
RPCServer to handle RPC requests from the split debugger GUI via the
|
| 186 |
+
IdbProxy.
|
| 187 |
+
|
| 188 |
+
"""
|
| 189 |
+
gui_proxy = GUIProxy(rpchandler, gui_adap_oid)
|
| 190 |
+
idb = debugger.Idb(gui_proxy)
|
| 191 |
+
idb_adap = IdbAdapter(idb)
|
| 192 |
+
rpchandler.register(idb_adap_oid, idb_adap)
|
| 193 |
+
return idb_adap_oid
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
#=======================================
|
| 197 |
+
#
|
| 198 |
+
# In the IDLE process:
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class FrameProxy:
|
| 202 |
+
|
| 203 |
+
def __init__(self, conn, fid):
|
| 204 |
+
self._conn = conn
|
| 205 |
+
self._fid = fid
|
| 206 |
+
self._oid = "idb_adapter"
|
| 207 |
+
self._dictcache = {}
|
| 208 |
+
|
| 209 |
+
def __getattr__(self, name):
|
| 210 |
+
if name[:1] == "_":
|
| 211 |
+
raise AttributeError(name)
|
| 212 |
+
if name == "f_code":
|
| 213 |
+
return self._get_f_code()
|
| 214 |
+
if name == "f_globals":
|
| 215 |
+
return self._get_f_globals()
|
| 216 |
+
if name == "f_locals":
|
| 217 |
+
return self._get_f_locals()
|
| 218 |
+
return self._conn.remotecall(self._oid, "frame_attr",
|
| 219 |
+
(self._fid, name), {})
|
| 220 |
+
|
| 221 |
+
def _get_f_code(self):
|
| 222 |
+
cid = self._conn.remotecall(self._oid, "frame_code", (self._fid,), {})
|
| 223 |
+
return CodeProxy(self._conn, self._oid, cid)
|
| 224 |
+
|
| 225 |
+
def _get_f_globals(self):
|
| 226 |
+
did = self._conn.remotecall(self._oid, "frame_globals",
|
| 227 |
+
(self._fid,), {})
|
| 228 |
+
return self._get_dict_proxy(did)
|
| 229 |
+
|
| 230 |
+
def _get_f_locals(self):
|
| 231 |
+
did = self._conn.remotecall(self._oid, "frame_locals",
|
| 232 |
+
(self._fid,), {})
|
| 233 |
+
return self._get_dict_proxy(did)
|
| 234 |
+
|
| 235 |
+
def _get_dict_proxy(self, did):
|
| 236 |
+
if did in self._dictcache:
|
| 237 |
+
return self._dictcache[did]
|
| 238 |
+
dp = DictProxy(self._conn, self._oid, did)
|
| 239 |
+
self._dictcache[did] = dp
|
| 240 |
+
return dp
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class CodeProxy:
|
| 244 |
+
|
| 245 |
+
def __init__(self, conn, oid, cid):
|
| 246 |
+
self._conn = conn
|
| 247 |
+
self._oid = oid
|
| 248 |
+
self._cid = cid
|
| 249 |
+
|
| 250 |
+
def __getattr__(self, name):
|
| 251 |
+
if name == "co_name":
|
| 252 |
+
return self._conn.remotecall(self._oid, "code_name",
|
| 253 |
+
(self._cid,), {})
|
| 254 |
+
if name == "co_filename":
|
| 255 |
+
return self._conn.remotecall(self._oid, "code_filename",
|
| 256 |
+
(self._cid,), {})
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class DictProxy:
|
| 260 |
+
|
| 261 |
+
def __init__(self, conn, oid, did):
|
| 262 |
+
self._conn = conn
|
| 263 |
+
self._oid = oid
|
| 264 |
+
self._did = did
|
| 265 |
+
|
| 266 |
+
## def keys(self):
|
| 267 |
+
## return self._conn.remotecall(self._oid, "dict_keys", (self._did,), {})
|
| 268 |
+
|
| 269 |
+
# 'temporary' until dict_keys is a pickleable built-in type
|
| 270 |
+
def keys(self):
|
| 271 |
+
return self._conn.remotecall(self._oid,
|
| 272 |
+
"dict_keys_list", (self._did,), {})
|
| 273 |
+
|
| 274 |
+
def __getitem__(self, key):
|
| 275 |
+
return self._conn.remotecall(self._oid, "dict_item",
|
| 276 |
+
(self._did, key), {})
|
| 277 |
+
|
| 278 |
+
def __getattr__(self, name):
|
| 279 |
+
##print("*** Failed DictProxy.__getattr__:", name)
|
| 280 |
+
raise AttributeError(name)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class GUIAdapter:
|
| 284 |
+
|
| 285 |
+
def __init__(self, conn, gui):
|
| 286 |
+
self.conn = conn
|
| 287 |
+
self.gui = gui
|
| 288 |
+
|
| 289 |
+
def interaction(self, message, fid, modified_info):
|
| 290 |
+
##print("*** Interaction: (%s, %s, %s)" % (message, fid, modified_info))
|
| 291 |
+
frame = FrameProxy(self.conn, fid)
|
| 292 |
+
self.gui.interaction(message, frame, modified_info)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class IdbProxy:
|
| 296 |
+
|
| 297 |
+
def __init__(self, conn, shell, oid):
|
| 298 |
+
self.oid = oid
|
| 299 |
+
self.conn = conn
|
| 300 |
+
self.shell = shell
|
| 301 |
+
|
| 302 |
+
def call(self, methodname, /, *args, **kwargs):
|
| 303 |
+
##print("*** IdbProxy.call %s %s %s" % (methodname, args, kwargs))
|
| 304 |
+
value = self.conn.remotecall(self.oid, methodname, args, kwargs)
|
| 305 |
+
##print("*** IdbProxy.call %s returns %r" % (methodname, value))
|
| 306 |
+
return value
|
| 307 |
+
|
| 308 |
+
def run(self, cmd, locals):
|
| 309 |
+
# Ignores locals on purpose!
|
| 310 |
+
seq = self.conn.asyncqueue(self.oid, "run", (cmd,), {})
|
| 311 |
+
self.shell.interp.active_seq = seq
|
| 312 |
+
|
| 313 |
+
def get_stack(self, frame, tbid):
|
| 314 |
+
# passing frame and traceback IDs, not the objects themselves
|
| 315 |
+
stack, i = self.call("get_stack", frame._fid, tbid)
|
| 316 |
+
stack = [(FrameProxy(self.conn, fid), k) for fid, k in stack]
|
| 317 |
+
return stack, i
|
| 318 |
+
|
| 319 |
+
def set_continue(self):
|
| 320 |
+
self.call("set_continue")
|
| 321 |
+
|
| 322 |
+
def set_step(self):
|
| 323 |
+
self.call("set_step")
|
| 324 |
+
|
| 325 |
+
def set_next(self, frame):
|
| 326 |
+
self.call("set_next", frame._fid)
|
| 327 |
+
|
| 328 |
+
def set_return(self, frame):
|
| 329 |
+
self.call("set_return", frame._fid)
|
| 330 |
+
|
| 331 |
+
def set_quit(self):
|
| 332 |
+
self.call("set_quit")
|
| 333 |
+
|
| 334 |
+
def set_break(self, filename, lineno):
|
| 335 |
+
msg = self.call("set_break", filename, lineno)
|
| 336 |
+
return msg
|
| 337 |
+
|
| 338 |
+
def clear_break(self, filename, lineno):
|
| 339 |
+
msg = self.call("clear_break", filename, lineno)
|
| 340 |
+
return msg
|
| 341 |
+
|
| 342 |
+
def clear_all_file_breaks(self, filename):
|
| 343 |
+
msg = self.call("clear_all_file_breaks", filename)
|
| 344 |
+
return msg
|
| 345 |
+
|
| 346 |
+
def start_remote_debugger(rpcclt, pyshell):
|
| 347 |
+
"""Start the subprocess debugger, initialize the debugger GUI and RPC link
|
| 348 |
+
|
| 349 |
+
Request the RPCServer start the Python subprocess debugger and link. Set
|
| 350 |
+
up the Idle side of the split debugger by instantiating the IdbProxy,
|
| 351 |
+
debugger GUI, and debugger GUIAdapter objects and linking them together.
|
| 352 |
+
|
| 353 |
+
Register the GUIAdapter with the RPCClient to handle debugger GUI
|
| 354 |
+
interaction requests coming from the subprocess debugger via the GUIProxy.
|
| 355 |
+
|
| 356 |
+
The IdbAdapter will pass execution and environment requests coming from the
|
| 357 |
+
Idle debugger GUI to the subprocess debugger via the IdbProxy.
|
| 358 |
+
|
| 359 |
+
"""
|
| 360 |
+
global idb_adap_oid
|
| 361 |
+
|
| 362 |
+
idb_adap_oid = rpcclt.remotecall("exec", "start_the_debugger",\
|
| 363 |
+
(gui_adap_oid,), {})
|
| 364 |
+
idb_proxy = IdbProxy(rpcclt, pyshell, idb_adap_oid)
|
| 365 |
+
gui = debugger.Debugger(pyshell, idb_proxy)
|
| 366 |
+
gui_adap = GUIAdapter(rpcclt, gui)
|
| 367 |
+
rpcclt.register(gui_adap_oid, gui_adap)
|
| 368 |
+
return gui
|
| 369 |
+
|
| 370 |
+
def close_remote_debugger(rpcclt):
|
| 371 |
+
"""Shut down subprocess debugger and Idle side of debugger RPC link
|
| 372 |
+
|
| 373 |
+
Request that the RPCServer shut down the subprocess debugger and link.
|
| 374 |
+
Unregister the GUIAdapter, which will cause a GC on the Idle process
|
| 375 |
+
debugger and RPC link objects. (The second reference to the debugger GUI
|
| 376 |
+
is deleted in pyshell.close_remote_debugger().)
|
| 377 |
+
|
| 378 |
+
"""
|
| 379 |
+
close_subprocess_debugger(rpcclt)
|
| 380 |
+
rpcclt.unregister(gui_adap_oid)
|
| 381 |
+
|
| 382 |
+
def close_subprocess_debugger(rpcclt):
|
| 383 |
+
rpcclt.remotecall("exec", "stop_the_debugger", (idb_adap_oid,), {})
|
| 384 |
+
|
| 385 |
+
def restart_subprocess_debugger(rpcclt):
|
| 386 |
+
idb_adap_oid_ret = rpcclt.remotecall("exec", "start_the_debugger",\
|
| 387 |
+
(gui_adap_oid,), {})
|
| 388 |
+
assert idb_adap_oid_ret == idb_adap_oid, 'Idb restarted with different oid'
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
if __name__ == "__main__":
|
| 392 |
+
from unittest import main
|
| 393 |
+
main('idlelib.idle_test.test_debugger_r', verbosity=2, exit=False)
|
parrot/lib/python3.10/idlelib/dynoption.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
OptionMenu widget modified to allow dynamic menu reconfiguration
|
| 3 |
+
and setting of highlightthickness
|
| 4 |
+
"""
|
| 5 |
+
from tkinter import OptionMenu, _setit, StringVar, Button
|
| 6 |
+
|
| 7 |
+
class DynOptionMenu(OptionMenu):
|
| 8 |
+
"""Add SetMenu and highlightthickness to OptionMenu.
|
| 9 |
+
|
| 10 |
+
Highlightthickness adds space around menu button.
|
| 11 |
+
"""
|
| 12 |
+
def __init__(self, master, variable, value, *values, **kwargs):
|
| 13 |
+
highlightthickness = kwargs.pop('highlightthickness', None)
|
| 14 |
+
OptionMenu.__init__(self, master, variable, value, *values, **kwargs)
|
| 15 |
+
self['highlightthickness'] = highlightthickness
|
| 16 |
+
self.variable = variable
|
| 17 |
+
self.command = kwargs.get('command')
|
| 18 |
+
|
| 19 |
+
def SetMenu(self,valueList,value=None):
|
| 20 |
+
"""
|
| 21 |
+
clear and reload the menu with a new set of options.
|
| 22 |
+
valueList - list of new options
|
| 23 |
+
value - initial value to set the optionmenu's menubutton to
|
| 24 |
+
"""
|
| 25 |
+
self['menu'].delete(0,'end')
|
| 26 |
+
for item in valueList:
|
| 27 |
+
self['menu'].add_command(label=item,
|
| 28 |
+
command=_setit(self.variable,item,self.command))
|
| 29 |
+
if value:
|
| 30 |
+
self.variable.set(value)
|
| 31 |
+
|
| 32 |
+
def _dyn_option_menu(parent): # htest #
|
| 33 |
+
from tkinter import Toplevel # + StringVar, Button
|
| 34 |
+
|
| 35 |
+
top = Toplevel(parent)
|
| 36 |
+
top.title("Test dynamic option menu")
|
| 37 |
+
x, y = map(int, parent.geometry().split('+')[1:])
|
| 38 |
+
top.geometry("200x100+%d+%d" % (x + 250, y + 175))
|
| 39 |
+
top.focus_set()
|
| 40 |
+
|
| 41 |
+
var = StringVar(top)
|
| 42 |
+
var.set("Old option set") #Set the default value
|
| 43 |
+
dyn = DynOptionMenu(top, var, "old1","old2","old3","old4",
|
| 44 |
+
highlightthickness=5)
|
| 45 |
+
dyn.pack()
|
| 46 |
+
|
| 47 |
+
def update():
|
| 48 |
+
dyn.SetMenu(["new1","new2","new3","new4"], value="new option set")
|
| 49 |
+
button = Button(top, text="Change option set", command=update)
|
| 50 |
+
button.pack()
|
| 51 |
+
|
| 52 |
+
if __name__ == '__main__':
|
| 53 |
+
# Only module without unittests because of intention to replace.
|
| 54 |
+
from idlelib.idle_test.htest import run
|
| 55 |
+
run(_dyn_option_menu)
|
parrot/lib/python3.10/idlelib/extend.txt
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Writing an IDLE extension
|
| 2 |
+
=========================
|
| 3 |
+
|
| 4 |
+
An IDLE extension can define new key bindings and menu entries for IDLE
|
| 5 |
+
edit windows. There is a simple mechanism to load extensions when IDLE
|
| 6 |
+
starts up and to attach them to each edit window. (It is also possible
|
| 7 |
+
to make other changes to IDLE, but this must be done by editing the IDLE
|
| 8 |
+
source code.)
|
| 9 |
+
|
| 10 |
+
The list of extensions loaded at startup time is configured by editing
|
| 11 |
+
the file config-extensions.def. See below for details.
|
| 12 |
+
|
| 13 |
+
An IDLE extension is defined by a class. Methods of the class define
|
| 14 |
+
actions that are invoked by event bindings or menu entries. Class (or
|
| 15 |
+
instance) variables define the bindings and menu additions; these are
|
| 16 |
+
automatically applied by IDLE when the extension is linked to an edit
|
| 17 |
+
window.
|
| 18 |
+
|
| 19 |
+
An IDLE extension class is instantiated with a single argument,
|
| 20 |
+
`editwin', an EditorWindow instance. The extension cannot assume much
|
| 21 |
+
about this argument, but it is guaranteed to have the following instance
|
| 22 |
+
variables:
|
| 23 |
+
|
| 24 |
+
text a Text instance (a widget)
|
| 25 |
+
io an IOBinding instance (more about this later)
|
| 26 |
+
flist the FileList instance (shared by all edit windows)
|
| 27 |
+
|
| 28 |
+
(There are a few more, but they are rarely useful.)
|
| 29 |
+
|
| 30 |
+
The extension class must not directly bind Window Manager (e.g. X) events.
|
| 31 |
+
Rather, it must define one or more virtual events, e.g. <<z-in>>, and
|
| 32 |
+
corresponding methods, e.g. z_in_event(). The virtual events will be
|
| 33 |
+
bound to the corresponding methods, and Window Manager events can then be bound
|
| 34 |
+
to the virtual events. (This indirection is done so that the key bindings can
|
| 35 |
+
easily be changed, and so that other sources of virtual events can exist, such
|
| 36 |
+
as menu entries.)
|
| 37 |
+
|
| 38 |
+
An extension can define menu entries. This is done with a class or instance
|
| 39 |
+
variable named menudefs; it should be a list of pairs, where each pair is a
|
| 40 |
+
menu name (lowercase) and a list of menu entries. Each menu entry is either
|
| 41 |
+
None (to insert a separator entry) or a pair of strings (menu_label,
|
| 42 |
+
virtual_event). Here, menu_label is the label of the menu entry, and
|
| 43 |
+
virtual_event is the virtual event to be generated when the entry is selected.
|
| 44 |
+
An underscore in the menu label is removed; the character following the
|
| 45 |
+
underscore is displayed underlined, to indicate the shortcut character (for
|
| 46 |
+
Windows).
|
| 47 |
+
|
| 48 |
+
At the moment, extensions cannot define whole new menus; they must define
|
| 49 |
+
entries in existing menus. Some menus are not present on some windows; such
|
| 50 |
+
entry definitions are then ignored, but key bindings are still applied. (This
|
| 51 |
+
should probably be refined in the future.)
|
| 52 |
+
|
| 53 |
+
Extensions are not required to define menu entries for all the events they
|
| 54 |
+
implement. (They are also not required to create keybindings, but in that
|
| 55 |
+
case there must be empty bindings in cofig-extensions.def)
|
| 56 |
+
|
| 57 |
+
Here is a partial example from zzdummy.py:
|
| 58 |
+
|
| 59 |
+
class ZzDummy:
|
| 60 |
+
|
| 61 |
+
menudefs = [
|
| 62 |
+
('format', [
|
| 63 |
+
('Z in', '<<z-in>>'),
|
| 64 |
+
('Z out', '<<z-out>>'),
|
| 65 |
+
] )
|
| 66 |
+
]
|
| 67 |
+
|
| 68 |
+
def __init__(self, editwin):
|
| 69 |
+
self.editwin = editwin
|
| 70 |
+
|
| 71 |
+
def z_in_event(self, event=None):
|
| 72 |
+
"...Do what you want here..."
|
| 73 |
+
|
| 74 |
+
The final piece of the puzzle is the file "config-extensions.def", which is
|
| 75 |
+
used to configure the loading of extensions and to establish key (or, more
|
| 76 |
+
generally, event) bindings to the virtual events defined in the extensions.
|
| 77 |
+
|
| 78 |
+
See the comments at the top of config-extensions.def for information. It's
|
| 79 |
+
currently necessary to manually modify that file to change IDLE's extension
|
| 80 |
+
loading or extension key bindings.
|
| 81 |
+
|
| 82 |
+
For further information on binding refer to the Tkinter Resources web page at
|
| 83 |
+
python.org and to the Tk Command "bind" man page.
|
parrot/lib/python3.10/idlelib/filelist.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"idlelib.filelist"
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from tkinter import messagebox
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class FileList:
|
| 8 |
+
|
| 9 |
+
# N.B. this import overridden in PyShellFileList.
|
| 10 |
+
from idlelib.editor import EditorWindow
|
| 11 |
+
|
| 12 |
+
def __init__(self, root):
|
| 13 |
+
self.root = root
|
| 14 |
+
self.dict = {}
|
| 15 |
+
self.inversedict = {}
|
| 16 |
+
self.vars = {} # For EditorWindow.getrawvar (shared Tcl variables)
|
| 17 |
+
|
| 18 |
+
def open(self, filename, action=None):
|
| 19 |
+
assert filename
|
| 20 |
+
filename = self.canonize(filename)
|
| 21 |
+
if os.path.isdir(filename):
|
| 22 |
+
# This can happen when bad filename is passed on command line:
|
| 23 |
+
messagebox.showerror(
|
| 24 |
+
"File Error",
|
| 25 |
+
"%r is a directory." % (filename,),
|
| 26 |
+
master=self.root)
|
| 27 |
+
return None
|
| 28 |
+
key = os.path.normcase(filename)
|
| 29 |
+
if key in self.dict:
|
| 30 |
+
edit = self.dict[key]
|
| 31 |
+
edit.top.wakeup()
|
| 32 |
+
return edit
|
| 33 |
+
if action:
|
| 34 |
+
# Don't create window, perform 'action', e.g. open in same window
|
| 35 |
+
return action(filename)
|
| 36 |
+
else:
|
| 37 |
+
edit = self.EditorWindow(self, filename, key)
|
| 38 |
+
if edit.good_load:
|
| 39 |
+
return edit
|
| 40 |
+
else:
|
| 41 |
+
edit._close()
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
def gotofileline(self, filename, lineno=None):
|
| 45 |
+
edit = self.open(filename)
|
| 46 |
+
if edit is not None and lineno is not None:
|
| 47 |
+
edit.gotoline(lineno)
|
| 48 |
+
|
| 49 |
+
def new(self, filename=None):
|
| 50 |
+
return self.EditorWindow(self, filename)
|
| 51 |
+
|
| 52 |
+
def close_all_callback(self, *args, **kwds):
|
| 53 |
+
for edit in list(self.inversedict):
|
| 54 |
+
reply = edit.close()
|
| 55 |
+
if reply == "cancel":
|
| 56 |
+
break
|
| 57 |
+
return "break"
|
| 58 |
+
|
| 59 |
+
def unregister_maybe_terminate(self, edit):
|
| 60 |
+
try:
|
| 61 |
+
key = self.inversedict[edit]
|
| 62 |
+
except KeyError:
|
| 63 |
+
print("Don't know this EditorWindow object. (close)")
|
| 64 |
+
return
|
| 65 |
+
if key:
|
| 66 |
+
del self.dict[key]
|
| 67 |
+
del self.inversedict[edit]
|
| 68 |
+
if not self.inversedict:
|
| 69 |
+
self.root.quit()
|
| 70 |
+
|
| 71 |
+
def filename_changed_edit(self, edit):
|
| 72 |
+
edit.saved_change_hook()
|
| 73 |
+
try:
|
| 74 |
+
key = self.inversedict[edit]
|
| 75 |
+
except KeyError:
|
| 76 |
+
print("Don't know this EditorWindow object. (rename)")
|
| 77 |
+
return
|
| 78 |
+
filename = edit.io.filename
|
| 79 |
+
if not filename:
|
| 80 |
+
if key:
|
| 81 |
+
del self.dict[key]
|
| 82 |
+
self.inversedict[edit] = None
|
| 83 |
+
return
|
| 84 |
+
filename = self.canonize(filename)
|
| 85 |
+
newkey = os.path.normcase(filename)
|
| 86 |
+
if newkey == key:
|
| 87 |
+
return
|
| 88 |
+
if newkey in self.dict:
|
| 89 |
+
conflict = self.dict[newkey]
|
| 90 |
+
self.inversedict[conflict] = None
|
| 91 |
+
messagebox.showerror(
|
| 92 |
+
"Name Conflict",
|
| 93 |
+
"You now have multiple edit windows open for %r" % (filename,),
|
| 94 |
+
master=self.root)
|
| 95 |
+
self.dict[newkey] = edit
|
| 96 |
+
self.inversedict[edit] = newkey
|
| 97 |
+
if key:
|
| 98 |
+
try:
|
| 99 |
+
del self.dict[key]
|
| 100 |
+
except KeyError:
|
| 101 |
+
pass
|
| 102 |
+
|
| 103 |
+
def canonize(self, filename):
|
| 104 |
+
if not os.path.isabs(filename):
|
| 105 |
+
try:
|
| 106 |
+
pwd = os.getcwd()
|
| 107 |
+
except OSError:
|
| 108 |
+
pass
|
| 109 |
+
else:
|
| 110 |
+
filename = os.path.join(pwd, filename)
|
| 111 |
+
return os.path.normpath(filename)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _test(): # TODO check and convert to htest
|
| 115 |
+
from tkinter import Tk
|
| 116 |
+
from idlelib.editor import fixwordbreaks
|
| 117 |
+
from idlelib.run import fix_scaling
|
| 118 |
+
root = Tk()
|
| 119 |
+
fix_scaling(root)
|
| 120 |
+
fixwordbreaks(root)
|
| 121 |
+
root.withdraw()
|
| 122 |
+
flist = FileList(root)
|
| 123 |
+
flist.new()
|
| 124 |
+
if flist.inversedict:
|
| 125 |
+
root.mainloop()
|
| 126 |
+
|
| 127 |
+
if __name__ == '__main__':
|
| 128 |
+
from unittest import main
|
| 129 |
+
main('idlelib.idle_test.test_filelist', verbosity=2)
|
| 130 |
+
|
| 131 |
+
# _test()
|
parrot/lib/python3.10/idlelib/help_about.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""About Dialog for IDLE
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import webbrowser
|
| 7 |
+
from platform import python_version, architecture
|
| 8 |
+
|
| 9 |
+
from tkinter import Toplevel, Frame, Label, Button, PhotoImage
|
| 10 |
+
from tkinter import SUNKEN, TOP, BOTTOM, LEFT, X, BOTH, W, EW, NSEW, E
|
| 11 |
+
|
| 12 |
+
from idlelib import textview
|
| 13 |
+
|
| 14 |
+
version = python_version()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def build_bits():
|
| 18 |
+
"Return bits for platform."
|
| 19 |
+
if sys.platform == 'darwin':
|
| 20 |
+
return '64' if sys.maxsize > 2**32 else '32'
|
| 21 |
+
else:
|
| 22 |
+
return architecture()[0][:2]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class AboutDialog(Toplevel):
|
| 26 |
+
"""Modal about dialog for idle
|
| 27 |
+
|
| 28 |
+
"""
|
| 29 |
+
def __init__(self, parent, title=None, *, _htest=False, _utest=False):
|
| 30 |
+
"""Create popup, do not return until tk widget destroyed.
|
| 31 |
+
|
| 32 |
+
parent - parent of this dialog
|
| 33 |
+
title - string which is title of popup dialog
|
| 34 |
+
_htest - bool, change box location when running htest
|
| 35 |
+
_utest - bool, don't wait_window when running unittest
|
| 36 |
+
"""
|
| 37 |
+
Toplevel.__init__(self, parent)
|
| 38 |
+
self.configure(borderwidth=5)
|
| 39 |
+
# place dialog below parent if running htest
|
| 40 |
+
self.geometry("+%d+%d" % (
|
| 41 |
+
parent.winfo_rootx()+30,
|
| 42 |
+
parent.winfo_rooty()+(30 if not _htest else 100)))
|
| 43 |
+
self.bg = "#bbbbbb"
|
| 44 |
+
self.fg = "#000000"
|
| 45 |
+
self.create_widgets()
|
| 46 |
+
self.resizable(height=False, width=False)
|
| 47 |
+
self.title(title or
|
| 48 |
+
f'About IDLE {version} ({build_bits()} bit)')
|
| 49 |
+
self.transient(parent)
|
| 50 |
+
self.grab_set()
|
| 51 |
+
self.protocol("WM_DELETE_WINDOW", self.ok)
|
| 52 |
+
self.parent = parent
|
| 53 |
+
self.button_ok.focus_set()
|
| 54 |
+
self.bind('<Return>', self.ok) # dismiss dialog
|
| 55 |
+
self.bind('<Escape>', self.ok) # dismiss dialog
|
| 56 |
+
self._current_textview = None
|
| 57 |
+
self._utest = _utest
|
| 58 |
+
|
| 59 |
+
if not _utest:
|
| 60 |
+
self.deiconify()
|
| 61 |
+
self.wait_window()
|
| 62 |
+
|
| 63 |
+
def create_widgets(self):
|
| 64 |
+
frame = Frame(self, borderwidth=2, relief=SUNKEN)
|
| 65 |
+
frame_buttons = Frame(self)
|
| 66 |
+
frame_buttons.pack(side=BOTTOM, fill=X)
|
| 67 |
+
frame.pack(side=TOP, expand=True, fill=BOTH)
|
| 68 |
+
self.button_ok = Button(frame_buttons, text='Close',
|
| 69 |
+
command=self.ok)
|
| 70 |
+
self.button_ok.pack(padx=5, pady=5)
|
| 71 |
+
|
| 72 |
+
frame_background = Frame(frame, bg=self.bg)
|
| 73 |
+
frame_background.pack(expand=True, fill=BOTH)
|
| 74 |
+
|
| 75 |
+
header = Label(frame_background, text='IDLE', fg=self.fg,
|
| 76 |
+
bg=self.bg, font=('courier', 24, 'bold'))
|
| 77 |
+
header.grid(row=0, column=0, sticky=E, padx=10, pady=10)
|
| 78 |
+
|
| 79 |
+
tk_patchlevel = self.tk.call('info', 'patchlevel')
|
| 80 |
+
ext = '.png' if tk_patchlevel >= '8.6' else '.gif'
|
| 81 |
+
icon = os.path.join(os.path.abspath(os.path.dirname(__file__)),
|
| 82 |
+
'Icons', f'idle_48{ext}')
|
| 83 |
+
self.icon_image = PhotoImage(master=self._root(), file=icon)
|
| 84 |
+
logo = Label(frame_background, image=self.icon_image, bg=self.bg)
|
| 85 |
+
logo.grid(row=0, column=0, sticky=W, rowspan=2, padx=10, pady=10)
|
| 86 |
+
|
| 87 |
+
byline_text = "Python's Integrated Development\nand Learning Environment" + 5*'\n'
|
| 88 |
+
byline = Label(frame_background, text=byline_text, justify=LEFT,
|
| 89 |
+
fg=self.fg, bg=self.bg)
|
| 90 |
+
byline.grid(row=2, column=0, sticky=W, columnspan=3, padx=10, pady=5)
|
| 91 |
+
email = Label(frame_background, text='email: idle-dev@python.org',
|
| 92 |
+
justify=LEFT, fg=self.fg, bg=self.bg)
|
| 93 |
+
email.grid(row=6, column=0, columnspan=2, sticky=W, padx=10, pady=0)
|
| 94 |
+
docs_url = ("https://docs.python.org/%d.%d/library/idle.html" %
|
| 95 |
+
sys.version_info[:2])
|
| 96 |
+
docs = Label(frame_background, text=docs_url,
|
| 97 |
+
justify=LEFT, fg=self.fg, bg=self.bg)
|
| 98 |
+
docs.grid(row=7, column=0, columnspan=2, sticky=W, padx=10, pady=0)
|
| 99 |
+
docs.bind("<Button-1>", lambda event: webbrowser.open(docs['text']))
|
| 100 |
+
|
| 101 |
+
Frame(frame_background, borderwidth=1, relief=SUNKEN,
|
| 102 |
+
height=2, bg=self.bg).grid(row=8, column=0, sticky=EW,
|
| 103 |
+
columnspan=3, padx=5, pady=5)
|
| 104 |
+
|
| 105 |
+
pyver = Label(frame_background,
|
| 106 |
+
text='Python version: ' + version,
|
| 107 |
+
fg=self.fg, bg=self.bg)
|
| 108 |
+
pyver.grid(row=9, column=0, sticky=W, padx=10, pady=0)
|
| 109 |
+
tkver = Label(frame_background, text='Tk version: ' + tk_patchlevel,
|
| 110 |
+
fg=self.fg, bg=self.bg)
|
| 111 |
+
tkver.grid(row=9, column=1, sticky=W, padx=2, pady=0)
|
| 112 |
+
py_buttons = Frame(frame_background, bg=self.bg)
|
| 113 |
+
py_buttons.grid(row=10, column=0, columnspan=2, sticky=NSEW)
|
| 114 |
+
self.py_license = Button(py_buttons, text='License', width=8,
|
| 115 |
+
highlightbackground=self.bg,
|
| 116 |
+
command=self.show_py_license)
|
| 117 |
+
self.py_license.pack(side=LEFT, padx=10, pady=10)
|
| 118 |
+
self.py_copyright = Button(py_buttons, text='Copyright', width=8,
|
| 119 |
+
highlightbackground=self.bg,
|
| 120 |
+
command=self.show_py_copyright)
|
| 121 |
+
self.py_copyright.pack(side=LEFT, padx=10, pady=10)
|
| 122 |
+
self.py_credits = Button(py_buttons, text='Credits', width=8,
|
| 123 |
+
highlightbackground=self.bg,
|
| 124 |
+
command=self.show_py_credits)
|
| 125 |
+
self.py_credits.pack(side=LEFT, padx=10, pady=10)
|
| 126 |
+
|
| 127 |
+
Frame(frame_background, borderwidth=1, relief=SUNKEN,
|
| 128 |
+
height=2, bg=self.bg).grid(row=11, column=0, sticky=EW,
|
| 129 |
+
columnspan=3, padx=5, pady=5)
|
| 130 |
+
|
| 131 |
+
idlever = Label(frame_background,
|
| 132 |
+
text='IDLE version: ' + version,
|
| 133 |
+
fg=self.fg, bg=self.bg)
|
| 134 |
+
idlever.grid(row=12, column=0, sticky=W, padx=10, pady=0)
|
| 135 |
+
idle_buttons = Frame(frame_background, bg=self.bg)
|
| 136 |
+
idle_buttons.grid(row=13, column=0, columnspan=3, sticky=NSEW)
|
| 137 |
+
self.readme = Button(idle_buttons, text='README', width=8,
|
| 138 |
+
highlightbackground=self.bg,
|
| 139 |
+
command=self.show_readme)
|
| 140 |
+
self.readme.pack(side=LEFT, padx=10, pady=10)
|
| 141 |
+
self.idle_news = Button(idle_buttons, text='NEWS', width=8,
|
| 142 |
+
highlightbackground=self.bg,
|
| 143 |
+
command=self.show_idle_news)
|
| 144 |
+
self.idle_news.pack(side=LEFT, padx=10, pady=10)
|
| 145 |
+
self.idle_credits = Button(idle_buttons, text='Credits', width=8,
|
| 146 |
+
highlightbackground=self.bg,
|
| 147 |
+
command=self.show_idle_credits)
|
| 148 |
+
self.idle_credits.pack(side=LEFT, padx=10, pady=10)
|
| 149 |
+
|
| 150 |
+
# License, copyright, and credits are of type _sitebuiltins._Printer
|
| 151 |
+
def show_py_license(self):
|
| 152 |
+
"Handle License button event."
|
| 153 |
+
self.display_printer_text('About - License', license)
|
| 154 |
+
|
| 155 |
+
def show_py_copyright(self):
|
| 156 |
+
"Handle Copyright button event."
|
| 157 |
+
self.display_printer_text('About - Copyright', copyright)
|
| 158 |
+
|
| 159 |
+
def show_py_credits(self):
|
| 160 |
+
"Handle Python Credits button event."
|
| 161 |
+
self.display_printer_text('About - Python Credits', credits)
|
| 162 |
+
|
| 163 |
+
# Encode CREDITS.txt to utf-8 for proper version of Loewis.
|
| 164 |
+
# Specify others as ascii until need utf-8, so catch errors.
|
| 165 |
+
def show_idle_credits(self):
|
| 166 |
+
"Handle Idle Credits button event."
|
| 167 |
+
self.display_file_text('About - Credits', 'CREDITS.txt', 'utf-8')
|
| 168 |
+
|
| 169 |
+
def show_readme(self):
|
| 170 |
+
"Handle Readme button event."
|
| 171 |
+
self.display_file_text('About - Readme', 'README.txt', 'ascii')
|
| 172 |
+
|
| 173 |
+
def show_idle_news(self):
|
| 174 |
+
"Handle News button event."
|
| 175 |
+
self.display_file_text('About - NEWS', 'NEWS.txt', 'utf-8')
|
| 176 |
+
|
| 177 |
+
def display_printer_text(self, title, printer):
|
| 178 |
+
"""Create textview for built-in constants.
|
| 179 |
+
|
| 180 |
+
Built-in constants have type _sitebuiltins._Printer. The
|
| 181 |
+
text is extracted from the built-in and then sent to a text
|
| 182 |
+
viewer with self as the parent and title as the title of
|
| 183 |
+
the popup.
|
| 184 |
+
"""
|
| 185 |
+
printer._Printer__setup()
|
| 186 |
+
text = '\n'.join(printer._Printer__lines)
|
| 187 |
+
self._current_textview = textview.view_text(
|
| 188 |
+
self, title, text, _utest=self._utest)
|
| 189 |
+
|
| 190 |
+
def display_file_text(self, title, filename, encoding=None):
|
| 191 |
+
"""Create textview for filename.
|
| 192 |
+
|
| 193 |
+
The filename needs to be in the current directory. The path
|
| 194 |
+
is sent to a text viewer with self as the parent, title as
|
| 195 |
+
the title of the popup, and the file encoding.
|
| 196 |
+
"""
|
| 197 |
+
fn = os.path.join(os.path.abspath(os.path.dirname(__file__)), filename)
|
| 198 |
+
self._current_textview = textview.view_file(
|
| 199 |
+
self, title, fn, encoding, _utest=self._utest)
|
| 200 |
+
|
| 201 |
+
def ok(self, event=None):
|
| 202 |
+
"Dismiss help_about dialog."
|
| 203 |
+
self.grab_release()
|
| 204 |
+
self.destroy()
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
if __name__ == '__main__':
|
| 208 |
+
from unittest import main
|
| 209 |
+
main('idlelib.idle_test.test_help_about', verbosity=2, exit=False)
|
| 210 |
+
|
| 211 |
+
from idlelib.idle_test.htest import run
|
| 212 |
+
run(AboutDialog)
|
parrot/lib/python3.10/idlelib/hyperparser.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provide advanced parsing abilities for ParenMatch and other extensions.
|
| 2 |
+
|
| 3 |
+
HyperParser uses PyParser. PyParser mostly gives information on the
|
| 4 |
+
proper indentation of code. HyperParser gives additional information on
|
| 5 |
+
the structure of code.
|
| 6 |
+
"""
|
| 7 |
+
from keyword import iskeyword
|
| 8 |
+
import string
|
| 9 |
+
|
| 10 |
+
from idlelib import pyparse
|
| 11 |
+
|
| 12 |
+
# all ASCII chars that may be in an identifier
|
| 13 |
+
_ASCII_ID_CHARS = frozenset(string.ascii_letters + string.digits + "_")
|
| 14 |
+
# all ASCII chars that may be the first char of an identifier
|
| 15 |
+
_ASCII_ID_FIRST_CHARS = frozenset(string.ascii_letters + "_")
|
| 16 |
+
|
| 17 |
+
# lookup table for whether 7-bit ASCII chars are valid in a Python identifier
|
| 18 |
+
_IS_ASCII_ID_CHAR = [(chr(x) in _ASCII_ID_CHARS) for x in range(128)]
|
| 19 |
+
# lookup table for whether 7-bit ASCII chars are valid as the first
|
| 20 |
+
# char in a Python identifier
|
| 21 |
+
_IS_ASCII_ID_FIRST_CHAR = \
|
| 22 |
+
[(chr(x) in _ASCII_ID_FIRST_CHARS) for x in range(128)]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class HyperParser:
|
| 26 |
+
def __init__(self, editwin, index):
|
| 27 |
+
"To initialize, analyze the surroundings of the given index."
|
| 28 |
+
|
| 29 |
+
self.editwin = editwin
|
| 30 |
+
self.text = text = editwin.text
|
| 31 |
+
|
| 32 |
+
parser = pyparse.Parser(editwin.indentwidth, editwin.tabwidth)
|
| 33 |
+
|
| 34 |
+
def index2line(index):
|
| 35 |
+
return int(float(index))
|
| 36 |
+
lno = index2line(text.index(index))
|
| 37 |
+
|
| 38 |
+
if not editwin.prompt_last_line:
|
| 39 |
+
for context in editwin.num_context_lines:
|
| 40 |
+
startat = max(lno - context, 1)
|
| 41 |
+
startatindex = repr(startat) + ".0"
|
| 42 |
+
stopatindex = "%d.end" % lno
|
| 43 |
+
# We add the newline because PyParse requires a newline
|
| 44 |
+
# at end. We add a space so that index won't be at end
|
| 45 |
+
# of line, so that its status will be the same as the
|
| 46 |
+
# char before it, if should.
|
| 47 |
+
parser.set_code(text.get(startatindex, stopatindex)+' \n')
|
| 48 |
+
bod = parser.find_good_parse_start(
|
| 49 |
+
editwin._build_char_in_string_func(startatindex))
|
| 50 |
+
if bod is not None or startat == 1:
|
| 51 |
+
break
|
| 52 |
+
parser.set_lo(bod or 0)
|
| 53 |
+
else:
|
| 54 |
+
r = text.tag_prevrange("console", index)
|
| 55 |
+
if r:
|
| 56 |
+
startatindex = r[1]
|
| 57 |
+
else:
|
| 58 |
+
startatindex = "1.0"
|
| 59 |
+
stopatindex = "%d.end" % lno
|
| 60 |
+
# We add the newline because PyParse requires it. We add a
|
| 61 |
+
# space so that index won't be at end of line, so that its
|
| 62 |
+
# status will be the same as the char before it, if should.
|
| 63 |
+
parser.set_code(text.get(startatindex, stopatindex)+' \n')
|
| 64 |
+
parser.set_lo(0)
|
| 65 |
+
|
| 66 |
+
# We want what the parser has, minus the last newline and space.
|
| 67 |
+
self.rawtext = parser.code[:-2]
|
| 68 |
+
# Parser.code apparently preserves the statement we are in, so
|
| 69 |
+
# that stopatindex can be used to synchronize the string with
|
| 70 |
+
# the text box indices.
|
| 71 |
+
self.stopatindex = stopatindex
|
| 72 |
+
self.bracketing = parser.get_last_stmt_bracketing()
|
| 73 |
+
# find which pairs of bracketing are openers. These always
|
| 74 |
+
# correspond to a character of rawtext.
|
| 75 |
+
self.isopener = [i>0 and self.bracketing[i][1] >
|
| 76 |
+
self.bracketing[i-1][1]
|
| 77 |
+
for i in range(len(self.bracketing))]
|
| 78 |
+
|
| 79 |
+
self.set_index(index)
|
| 80 |
+
|
| 81 |
+
def set_index(self, index):
|
| 82 |
+
"""Set the index to which the functions relate.
|
| 83 |
+
|
| 84 |
+
The index must be in the same statement.
|
| 85 |
+
"""
|
| 86 |
+
indexinrawtext = (len(self.rawtext) -
|
| 87 |
+
len(self.text.get(index, self.stopatindex)))
|
| 88 |
+
if indexinrawtext < 0:
|
| 89 |
+
raise ValueError("Index %s precedes the analyzed statement"
|
| 90 |
+
% index)
|
| 91 |
+
self.indexinrawtext = indexinrawtext
|
| 92 |
+
# find the rightmost bracket to which index belongs
|
| 93 |
+
self.indexbracket = 0
|
| 94 |
+
while (self.indexbracket < len(self.bracketing)-1 and
|
| 95 |
+
self.bracketing[self.indexbracket+1][0] < self.indexinrawtext):
|
| 96 |
+
self.indexbracket += 1
|
| 97 |
+
if (self.indexbracket < len(self.bracketing)-1 and
|
| 98 |
+
self.bracketing[self.indexbracket+1][0] == self.indexinrawtext and
|
| 99 |
+
not self.isopener[self.indexbracket+1]):
|
| 100 |
+
self.indexbracket += 1
|
| 101 |
+
|
| 102 |
+
def is_in_string(self):
|
| 103 |
+
"""Is the index given to the HyperParser in a string?"""
|
| 104 |
+
# The bracket to which we belong should be an opener.
|
| 105 |
+
# If it's an opener, it has to have a character.
|
| 106 |
+
return (self.isopener[self.indexbracket] and
|
| 107 |
+
self.rawtext[self.bracketing[self.indexbracket][0]]
|
| 108 |
+
in ('"', "'"))
|
| 109 |
+
|
| 110 |
+
def is_in_code(self):
|
| 111 |
+
"""Is the index given to the HyperParser in normal code?"""
|
| 112 |
+
return (not self.isopener[self.indexbracket] or
|
| 113 |
+
self.rawtext[self.bracketing[self.indexbracket][0]]
|
| 114 |
+
not in ('#', '"', "'"))
|
| 115 |
+
|
| 116 |
+
def get_surrounding_brackets(self, openers='([{', mustclose=False):
|
| 117 |
+
"""Return bracket indexes or None.
|
| 118 |
+
|
| 119 |
+
If the index given to the HyperParser is surrounded by a
|
| 120 |
+
bracket defined in openers (or at least has one before it),
|
| 121 |
+
return the indices of the opening bracket and the closing
|
| 122 |
+
bracket (or the end of line, whichever comes first).
|
| 123 |
+
|
| 124 |
+
If it is not surrounded by brackets, or the end of line comes
|
| 125 |
+
before the closing bracket and mustclose is True, returns None.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
bracketinglevel = self.bracketing[self.indexbracket][1]
|
| 129 |
+
before = self.indexbracket
|
| 130 |
+
while (not self.isopener[before] or
|
| 131 |
+
self.rawtext[self.bracketing[before][0]] not in openers or
|
| 132 |
+
self.bracketing[before][1] > bracketinglevel):
|
| 133 |
+
before -= 1
|
| 134 |
+
if before < 0:
|
| 135 |
+
return None
|
| 136 |
+
bracketinglevel = min(bracketinglevel, self.bracketing[before][1])
|
| 137 |
+
after = self.indexbracket + 1
|
| 138 |
+
while (after < len(self.bracketing) and
|
| 139 |
+
self.bracketing[after][1] >= bracketinglevel):
|
| 140 |
+
after += 1
|
| 141 |
+
|
| 142 |
+
beforeindex = self.text.index("%s-%dc" %
|
| 143 |
+
(self.stopatindex, len(self.rawtext)-self.bracketing[before][0]))
|
| 144 |
+
if (after >= len(self.bracketing) or
|
| 145 |
+
self.bracketing[after][0] > len(self.rawtext)):
|
| 146 |
+
if mustclose:
|
| 147 |
+
return None
|
| 148 |
+
afterindex = self.stopatindex
|
| 149 |
+
else:
|
| 150 |
+
# We are after a real char, so it is a ')' and we give the
|
| 151 |
+
# index before it.
|
| 152 |
+
afterindex = self.text.index(
|
| 153 |
+
"%s-%dc" % (self.stopatindex,
|
| 154 |
+
len(self.rawtext)-(self.bracketing[after][0]-1)))
|
| 155 |
+
|
| 156 |
+
return beforeindex, afterindex
|
| 157 |
+
|
| 158 |
+
# the set of built-in identifiers which are also keywords,
|
| 159 |
+
# i.e. keyword.iskeyword() returns True for them
|
| 160 |
+
_ID_KEYWORDS = frozenset({"True", "False", "None"})
|
| 161 |
+
|
| 162 |
+
@classmethod
|
| 163 |
+
def _eat_identifier(cls, str, limit, pos):
|
| 164 |
+
"""Given a string and pos, return the number of chars in the
|
| 165 |
+
identifier which ends at pos, or 0 if there is no such one.
|
| 166 |
+
|
| 167 |
+
This ignores non-identifier eywords are not identifiers.
|
| 168 |
+
"""
|
| 169 |
+
is_ascii_id_char = _IS_ASCII_ID_CHAR
|
| 170 |
+
|
| 171 |
+
# Start at the end (pos) and work backwards.
|
| 172 |
+
i = pos
|
| 173 |
+
|
| 174 |
+
# Go backwards as long as the characters are valid ASCII
|
| 175 |
+
# identifier characters. This is an optimization, since it
|
| 176 |
+
# is faster in the common case where most of the characters
|
| 177 |
+
# are ASCII.
|
| 178 |
+
while i > limit and (
|
| 179 |
+
ord(str[i - 1]) < 128 and
|
| 180 |
+
is_ascii_id_char[ord(str[i - 1])]
|
| 181 |
+
):
|
| 182 |
+
i -= 1
|
| 183 |
+
|
| 184 |
+
# If the above loop ended due to reaching a non-ASCII
|
| 185 |
+
# character, continue going backwards using the most generic
|
| 186 |
+
# test for whether a string contains only valid identifier
|
| 187 |
+
# characters.
|
| 188 |
+
if i > limit and ord(str[i - 1]) >= 128:
|
| 189 |
+
while i - 4 >= limit and ('a' + str[i - 4:pos]).isidentifier():
|
| 190 |
+
i -= 4
|
| 191 |
+
if i - 2 >= limit and ('a' + str[i - 2:pos]).isidentifier():
|
| 192 |
+
i -= 2
|
| 193 |
+
if i - 1 >= limit and ('a' + str[i - 1:pos]).isidentifier():
|
| 194 |
+
i -= 1
|
| 195 |
+
|
| 196 |
+
# The identifier candidate starts here. If it isn't a valid
|
| 197 |
+
# identifier, don't eat anything. At this point that is only
|
| 198 |
+
# possible if the first character isn't a valid first
|
| 199 |
+
# character for an identifier.
|
| 200 |
+
if not str[i:pos].isidentifier():
|
| 201 |
+
return 0
|
| 202 |
+
elif i < pos:
|
| 203 |
+
# All characters in str[i:pos] are valid ASCII identifier
|
| 204 |
+
# characters, so it is enough to check that the first is
|
| 205 |
+
# valid as the first character of an identifier.
|
| 206 |
+
if not _IS_ASCII_ID_FIRST_CHAR[ord(str[i])]:
|
| 207 |
+
return 0
|
| 208 |
+
|
| 209 |
+
# All keywords are valid identifiers, but should not be
|
| 210 |
+
# considered identifiers here, except for True, False and None.
|
| 211 |
+
if i < pos and (
|
| 212 |
+
iskeyword(str[i:pos]) and
|
| 213 |
+
str[i:pos] not in cls._ID_KEYWORDS
|
| 214 |
+
):
|
| 215 |
+
return 0
|
| 216 |
+
|
| 217 |
+
return pos - i
|
| 218 |
+
|
| 219 |
+
# This string includes all chars that may be in a white space
|
| 220 |
+
_whitespace_chars = " \t\n\\"
|
| 221 |
+
|
| 222 |
+
def get_expression(self):
|
| 223 |
+
"""Return a string with the Python expression which ends at the
|
| 224 |
+
given index, which is empty if there is no real one.
|
| 225 |
+
"""
|
| 226 |
+
if not self.is_in_code():
|
| 227 |
+
raise ValueError("get_expression should only be called "
|
| 228 |
+
"if index is inside a code.")
|
| 229 |
+
|
| 230 |
+
rawtext = self.rawtext
|
| 231 |
+
bracketing = self.bracketing
|
| 232 |
+
|
| 233 |
+
brck_index = self.indexbracket
|
| 234 |
+
brck_limit = bracketing[brck_index][0]
|
| 235 |
+
pos = self.indexinrawtext
|
| 236 |
+
|
| 237 |
+
last_identifier_pos = pos
|
| 238 |
+
postdot_phase = True
|
| 239 |
+
|
| 240 |
+
while True:
|
| 241 |
+
# Eat whitespaces, comments, and if postdot_phase is False - a dot
|
| 242 |
+
while True:
|
| 243 |
+
if pos>brck_limit and rawtext[pos-1] in self._whitespace_chars:
|
| 244 |
+
# Eat a whitespace
|
| 245 |
+
pos -= 1
|
| 246 |
+
elif (not postdot_phase and
|
| 247 |
+
pos > brck_limit and rawtext[pos-1] == '.'):
|
| 248 |
+
# Eat a dot
|
| 249 |
+
pos -= 1
|
| 250 |
+
postdot_phase = True
|
| 251 |
+
# The next line will fail if we are *inside* a comment,
|
| 252 |
+
# but we shouldn't be.
|
| 253 |
+
elif (pos == brck_limit and brck_index > 0 and
|
| 254 |
+
rawtext[bracketing[brck_index-1][0]] == '#'):
|
| 255 |
+
# Eat a comment
|
| 256 |
+
brck_index -= 2
|
| 257 |
+
brck_limit = bracketing[brck_index][0]
|
| 258 |
+
pos = bracketing[brck_index+1][0]
|
| 259 |
+
else:
|
| 260 |
+
# If we didn't eat anything, quit.
|
| 261 |
+
break
|
| 262 |
+
|
| 263 |
+
if not postdot_phase:
|
| 264 |
+
# We didn't find a dot, so the expression end at the
|
| 265 |
+
# last identifier pos.
|
| 266 |
+
break
|
| 267 |
+
|
| 268 |
+
ret = self._eat_identifier(rawtext, brck_limit, pos)
|
| 269 |
+
if ret:
|
| 270 |
+
# There is an identifier to eat
|
| 271 |
+
pos = pos - ret
|
| 272 |
+
last_identifier_pos = pos
|
| 273 |
+
# Now, to continue the search, we must find a dot.
|
| 274 |
+
postdot_phase = False
|
| 275 |
+
# (the loop continues now)
|
| 276 |
+
|
| 277 |
+
elif pos == brck_limit:
|
| 278 |
+
# We are at a bracketing limit. If it is a closing
|
| 279 |
+
# bracket, eat the bracket, otherwise, stop the search.
|
| 280 |
+
level = bracketing[brck_index][1]
|
| 281 |
+
while brck_index > 0 and bracketing[brck_index-1][1] > level:
|
| 282 |
+
brck_index -= 1
|
| 283 |
+
if bracketing[brck_index][0] == brck_limit:
|
| 284 |
+
# We were not at the end of a closing bracket
|
| 285 |
+
break
|
| 286 |
+
pos = bracketing[brck_index][0]
|
| 287 |
+
brck_index -= 1
|
| 288 |
+
brck_limit = bracketing[brck_index][0]
|
| 289 |
+
last_identifier_pos = pos
|
| 290 |
+
if rawtext[pos] in "([":
|
| 291 |
+
# [] and () may be used after an identifier, so we
|
| 292 |
+
# continue. postdot_phase is True, so we don't allow a dot.
|
| 293 |
+
pass
|
| 294 |
+
else:
|
| 295 |
+
# We can't continue after other types of brackets
|
| 296 |
+
if rawtext[pos] in "'\"":
|
| 297 |
+
# Scan a string prefix
|
| 298 |
+
while pos > 0 and rawtext[pos - 1] in "rRbBuU":
|
| 299 |
+
pos -= 1
|
| 300 |
+
last_identifier_pos = pos
|
| 301 |
+
break
|
| 302 |
+
|
| 303 |
+
else:
|
| 304 |
+
# We've found an operator or something.
|
| 305 |
+
break
|
| 306 |
+
|
| 307 |
+
return rawtext[last_identifier_pos:self.indexinrawtext]
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
if __name__ == '__main__':
|
| 311 |
+
from unittest import main
|
| 312 |
+
main('idlelib.idle_test.test_hyperparser', verbosity=2)
|
parrot/lib/python3.10/idlelib/idle.bat
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@echo off
|
| 2 |
+
rem Start IDLE using the appropriate Python interpreter
|
| 3 |
+
set CURRDIR=%~dp0
|
| 4 |
+
start "IDLE" "%CURRDIR%..\..\pythonw.exe" "%CURRDIR%idle.pyw" %1 %2 %3 %4 %5 %6 %7 %8 %9
|
parrot/lib/python3.10/idlelib/idle_test/README.txt
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
README FOR IDLE TESTS IN IDLELIB.IDLE_TEST
|
| 2 |
+
|
| 3 |
+
0. Quick Start
|
| 4 |
+
|
| 5 |
+
Automated unit tests were added in 3.3 for Python 3.x.
|
| 6 |
+
To run the tests from a command line:
|
| 7 |
+
|
| 8 |
+
python -m test.test_idle
|
| 9 |
+
|
| 10 |
+
Human-mediated tests were added later in 3.4.
|
| 11 |
+
|
| 12 |
+
python -m idlelib.idle_test.htest
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
1. Test Files
|
| 16 |
+
|
| 17 |
+
The idle directory, idlelib, has over 60 xyz.py files. The idle_test
|
| 18 |
+
subdirectory contains test_xyz.py for each implementation file xyz.py.
|
| 19 |
+
To add a test for abc.py, open idle_test/template.py and immediately
|
| 20 |
+
Save As test_abc.py. Insert 'abc' on the first line, and replace
|
| 21 |
+
'zzdummy' with 'abc.
|
| 22 |
+
|
| 23 |
+
Remove the imports of requires and tkinter if not needed. Otherwise,
|
| 24 |
+
add to the tkinter imports as needed.
|
| 25 |
+
|
| 26 |
+
Add a prefix to 'Test' for the initial test class. The template class
|
| 27 |
+
contains code needed or possibly needed for gui tests. See the next
|
| 28 |
+
section if doing gui tests. If not, and not needed for further classes,
|
| 29 |
+
this code can be removed.
|
| 30 |
+
|
| 31 |
+
Add the following at the end of abc.py. If an htest was added first,
|
| 32 |
+
insert the import and main lines before the htest lines.
|
| 33 |
+
|
| 34 |
+
if __name__ == "__main__":
|
| 35 |
+
from unittest import main
|
| 36 |
+
main('idlelib.idle_test.test_abc', verbosity=2, exit=False)
|
| 37 |
+
|
| 38 |
+
The ', exit=False' is only needed if an htest follows.
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
2. GUI Tests
|
| 43 |
+
|
| 44 |
+
When run as part of the Python test suite, Idle GUI tests need to run
|
| 45 |
+
test.support.requires('gui'). A test is a GUI test if it creates a
|
| 46 |
+
tkinter.Tk root or master object either directly or indirectly by
|
| 47 |
+
instantiating a tkinter or idle class. GUI tests cannot run in test
|
| 48 |
+
processes that either have no graphical environment available or are not
|
| 49 |
+
allowed to use it.
|
| 50 |
+
|
| 51 |
+
To guard a module consisting entirely of GUI tests, start with
|
| 52 |
+
|
| 53 |
+
from test.support import requires
|
| 54 |
+
requires('gui')
|
| 55 |
+
|
| 56 |
+
To guard a test class, put "requires('gui')" in its setUpClass function.
|
| 57 |
+
The template.py file does this.
|
| 58 |
+
|
| 59 |
+
To avoid interfering with other GUI tests, all GUI objects must be
|
| 60 |
+
destroyed and deleted by the end of the test. The Tk root created in a
|
| 61 |
+
setUpX function should be destroyed in the corresponding tearDownX and
|
| 62 |
+
the module or class attribute deleted. Others widgets should descend
|
| 63 |
+
from the single root and the attributes deleted BEFORE root is
|
| 64 |
+
destroyed. See https://bugs.python.org/issue20567.
|
| 65 |
+
|
| 66 |
+
@classmethod
|
| 67 |
+
def setUpClass(cls):
|
| 68 |
+
requires('gui')
|
| 69 |
+
cls.root = tk.Tk()
|
| 70 |
+
cls.text = tk.Text(root)
|
| 71 |
+
|
| 72 |
+
@classmethod
|
| 73 |
+
def tearDownClass(cls):
|
| 74 |
+
del cls.text
|
| 75 |
+
cls.root.update_idletasks()
|
| 76 |
+
cls.root.destroy()
|
| 77 |
+
del cls.root
|
| 78 |
+
|
| 79 |
+
The update_idletasks call is sometimes needed to prevent the following
|
| 80 |
+
warning either when running a test alone or as part of the test suite
|
| 81 |
+
(#27196). It should not hurt if not needed.
|
| 82 |
+
|
| 83 |
+
can't invoke "event" command: application has been destroyed
|
| 84 |
+
...
|
| 85 |
+
"ttk::ThemeChanged"
|
| 86 |
+
|
| 87 |
+
If a test creates instance 'e' of EditorWindow, call 'e._close()' before
|
| 88 |
+
or as the first part of teardown. The effect of omitting this depends
|
| 89 |
+
on the later shutdown. Then enable the after_cancel loop in the
|
| 90 |
+
template. This prevents messages like the following.
|
| 91 |
+
|
| 92 |
+
bgerror failed to handle background error.
|
| 93 |
+
Original error: invalid command name "106096696timer_event"
|
| 94 |
+
Error in bgerror: can't invoke "tk" command: application has been destroyed
|
| 95 |
+
|
| 96 |
+
Requires('gui') causes the test(s) it guards to be skipped if any of
|
| 97 |
+
these conditions are met:
|
| 98 |
+
|
| 99 |
+
- The tests are being run by regrtest.py, and it was started without
|
| 100 |
+
enabling the "gui" resource with the "-u" command line option.
|
| 101 |
+
|
| 102 |
+
- The tests are being run on Windows by a service that is not allowed
|
| 103 |
+
to interact with the graphical environment.
|
| 104 |
+
|
| 105 |
+
- The tests are being run on Linux and X Windows is not available.
|
| 106 |
+
|
| 107 |
+
- The tests are being run on Mac OSX in a process that cannot make a
|
| 108 |
+
window manager connection.
|
| 109 |
+
|
| 110 |
+
- tkinter.Tk cannot be successfully instantiated for some reason.
|
| 111 |
+
|
| 112 |
+
- test.support.use_resources has been set by something other than
|
| 113 |
+
regrtest.py and does not contain "gui".
|
| 114 |
+
|
| 115 |
+
Tests of non-GUI operations should avoid creating tk widgets. Incidental
|
| 116 |
+
uses of tk variables and messageboxes can be replaced by the mock
|
| 117 |
+
classes in idle_test/mock_tk.py. The mock text handles some uses of the
|
| 118 |
+
tk Text widget.
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
3. Running Unit Tests
|
| 122 |
+
|
| 123 |
+
Assume that xyz.py and test_xyz.py both end with a unittest.main() call.
|
| 124 |
+
Running either from an Idle editor runs all tests in the test_xyz file
|
| 125 |
+
with the version of Python running Idle. Test output appears in the
|
| 126 |
+
Shell window. The 'verbosity=2' option lists all test methods in the
|
| 127 |
+
file, which is appropriate when developing tests. The 'exit=False'
|
| 128 |
+
option is needed in xyx.py files when an htest follows.
|
| 129 |
+
|
| 130 |
+
The following command lines also run all test methods, including
|
| 131 |
+
GUI tests, in test_xyz.py. (Both '-m idlelib' and '-m idlelib.idle'
|
| 132 |
+
start Idle and so cannot run tests.)
|
| 133 |
+
|
| 134 |
+
python -m idlelib.xyz
|
| 135 |
+
python -m idlelib.idle_test.test_xyz
|
| 136 |
+
|
| 137 |
+
The following runs all idle_test/test_*.py tests interactively.
|
| 138 |
+
|
| 139 |
+
>>> import unittest
|
| 140 |
+
>>> unittest.main('idlelib.idle_test', verbosity=2)
|
| 141 |
+
|
| 142 |
+
The following run all Idle tests at a command line. Option '-v' is the
|
| 143 |
+
same as 'verbosity=2'.
|
| 144 |
+
|
| 145 |
+
python -m unittest -v idlelib.idle_test
|
| 146 |
+
python -m test -v -ugui test_idle
|
| 147 |
+
python -m test.test_idle
|
| 148 |
+
|
| 149 |
+
The idle tests are 'discovered' by
|
| 150 |
+
idlelib.idle_test.__init__.load_tests, which is also imported into
|
| 151 |
+
test.test_idle. Normally, neither file should be changed when working on
|
| 152 |
+
individual test modules. The third command runs unittest indirectly
|
| 153 |
+
through regrtest. The same happens when the entire test suite is run
|
| 154 |
+
with 'python -m test'. So that command must work for buildbots to stay
|
| 155 |
+
green. Idle tests must not disturb the environment in a way that makes
|
| 156 |
+
other tests fail (issue 18081).
|
| 157 |
+
|
| 158 |
+
To run an individual Testcase or test method, extend the dotted name
|
| 159 |
+
given to unittest on the command line or use the test -m option. The
|
| 160 |
+
latter allows use of other regrtest options. When using the latter,
|
| 161 |
+
all components of the pattern must be present, but any can be replaced
|
| 162 |
+
by '*'.
|
| 163 |
+
|
| 164 |
+
python -m unittest -v idlelib.idle_test.test_xyz.Test_case.test_meth
|
| 165 |
+
python -m test -m idlelib.idle_test.text_xyz.Test_case.test_meth test_idle
|
| 166 |
+
|
| 167 |
+
The test suite can be run in an IDLE user process from Shell.
|
| 168 |
+
>>> import test.autotest # Issue 25588, 2017/10/13, 3.6.4, 3.7.0a2.
|
| 169 |
+
There are currently failures not usually present, and this does not
|
| 170 |
+
work when run from the editor.
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
4. Human-mediated Tests
|
| 174 |
+
|
| 175 |
+
Human-mediated tests are widget tests that cannot be automated but need
|
| 176 |
+
human verification. They are contained in idlelib/idle_test/htest.py,
|
| 177 |
+
which has instructions. (Some modules need an auxiliary function,
|
| 178 |
+
identified with "# htest # on the header line.) The set is about
|
| 179 |
+
complete, though some tests need improvement. To run all htests, run the
|
| 180 |
+
htest file from an editor or from the command line with:
|
| 181 |
+
|
| 182 |
+
python -m idlelib.idle_test.htest
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
5. Test Coverage
|
| 186 |
+
|
| 187 |
+
Install the coverage package into your Python 3.6 site-packages
|
| 188 |
+
directory. (Its exact location depends on the OS).
|
| 189 |
+
> python3 -m pip install coverage
|
| 190 |
+
(On Windows, replace 'python3 with 'py -3.6' or perhaps just 'python'.)
|
| 191 |
+
|
| 192 |
+
The problem with running coverage with repository python is that
|
| 193 |
+
coverage uses absolute imports for its submodules, hence it needs to be
|
| 194 |
+
in a directory in sys.path. One solution: copy the package to the
|
| 195 |
+
directory containing the cpython repository. Call it 'dev'. Then run
|
| 196 |
+
coverage either directly or from a script in that directory so that
|
| 197 |
+
'dev' is prepended to sys.path.
|
| 198 |
+
|
| 199 |
+
Either edit or add dev/.coveragerc so it looks something like this.
|
| 200 |
+
---
|
| 201 |
+
# .coveragerc sets coverage options.
|
| 202 |
+
[run]
|
| 203 |
+
branch = True
|
| 204 |
+
|
| 205 |
+
[report]
|
| 206 |
+
# Regexes for lines to exclude from consideration
|
| 207 |
+
exclude_lines =
|
| 208 |
+
# Don't complain if non-runnable code isn't run:
|
| 209 |
+
if 0:
|
| 210 |
+
if __name__ == .__main__.:
|
| 211 |
+
|
| 212 |
+
.*# htest #
|
| 213 |
+
if not _utest:
|
| 214 |
+
if _htest:
|
| 215 |
+
---
|
| 216 |
+
The additions for IDLE are 'branch = True', to test coverage both ways,
|
| 217 |
+
and the last three exclude lines, to exclude things peculiar to IDLE
|
| 218 |
+
that are not executed during tests.
|
| 219 |
+
|
| 220 |
+
A script like the following cover.bat (for Windows) is very handy.
|
| 221 |
+
---
|
| 222 |
+
@echo off
|
| 223 |
+
rem Usage: cover filename [test_ suffix] # proper case required by coverage
|
| 224 |
+
rem filename without .py, 2nd parameter if test is not test_filename
|
| 225 |
+
setlocal
|
| 226 |
+
set py=f:\dev\3x\pcbuild\win32\python_d.exe
|
| 227 |
+
set src=idlelib.%1
|
| 228 |
+
if "%2" EQU "" set tst=f:/dev/3x/Lib/idlelib/idle_test/test_%1.py
|
| 229 |
+
if "%2" NEQ "" set tst=f:/dev/ex/Lib/idlelib/idle_test/test_%2.py
|
| 230 |
+
|
| 231 |
+
%py% -m coverage run --pylib --source=%src% %tst%
|
| 232 |
+
%py% -m coverage report --show-missing
|
| 233 |
+
%py% -m coverage html
|
| 234 |
+
start htmlcov\3x_Lib_idlelib_%1_py.html
|
| 235 |
+
rem Above opens new report; htmlcov\index.html displays report index
|
| 236 |
+
---
|
| 237 |
+
The second parameter was added for tests of module x not named test_x.
|
| 238 |
+
(There were several before modules were renamed, now only one is left.)
|
parrot/lib/python3.10/idlelib/idle_test/__pycache__/test_debugobj_r.cpython-310.pyc
ADDED
|
Binary file (1.35 kB). View file
|
|
|
parrot/lib/python3.10/idlelib/idle_test/__pycache__/test_iomenu.cpython-310.pyc
ADDED
|
Binary file (3.31 kB). View file
|
|
|
parrot/lib/python3.10/idlelib/idle_test/__pycache__/test_scrolledlist.cpython-310.pyc
ADDED
|
Binary file (1.1 kB). View file
|
|
|
parrot/lib/python3.10/idlelib/idle_test/__pycache__/test_squeezer.cpython-310.pyc
ADDED
|
Binary file (16.2 kB). View file
|
|
|
parrot/lib/python3.10/idlelib/idle_test/__pycache__/tkinter_testing_utils.cpython-310.pyc
ADDED
|
Binary file (2.18 kB). View file
|
|
|
parrot/lib/python3.10/idlelib/idle_test/test_autocomplete_w.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test autocomplete_w, coverage 11%."
|
| 2 |
+
|
| 3 |
+
import unittest
|
| 4 |
+
from test.support import requires
|
| 5 |
+
from tkinter import Tk, Text
|
| 6 |
+
|
| 7 |
+
import idlelib.autocomplete_w as acw
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class AutoCompleteWindowTest(unittest.TestCase):
|
| 11 |
+
|
| 12 |
+
@classmethod
|
| 13 |
+
def setUpClass(cls):
|
| 14 |
+
requires('gui')
|
| 15 |
+
cls.root = Tk()
|
| 16 |
+
cls.root.withdraw()
|
| 17 |
+
cls.text = Text(cls.root)
|
| 18 |
+
cls.acw = acw.AutoCompleteWindow(cls.text, tags=None)
|
| 19 |
+
|
| 20 |
+
@classmethod
|
| 21 |
+
def tearDownClass(cls):
|
| 22 |
+
del cls.text, cls.acw
|
| 23 |
+
cls.root.update_idletasks()
|
| 24 |
+
cls.root.destroy()
|
| 25 |
+
del cls.root
|
| 26 |
+
|
| 27 |
+
def test_init(self):
|
| 28 |
+
self.assertEqual(self.acw.widget, self.text)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if __name__ == '__main__':
|
| 32 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test browser, coverage 90%."
|
| 2 |
+
|
| 3 |
+
from idlelib import browser
|
| 4 |
+
from test.support import requires
|
| 5 |
+
import unittest
|
| 6 |
+
from unittest import mock
|
| 7 |
+
from idlelib.idle_test.mock_idle import Func
|
| 8 |
+
from idlelib.util import py_extensions
|
| 9 |
+
|
| 10 |
+
from collections import deque
|
| 11 |
+
import os.path
|
| 12 |
+
import pyclbr
|
| 13 |
+
from tkinter import Tk
|
| 14 |
+
|
| 15 |
+
from idlelib.tree import TreeNode
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ModuleBrowserTest(unittest.TestCase):
|
| 19 |
+
|
| 20 |
+
@classmethod
|
| 21 |
+
def setUpClass(cls):
|
| 22 |
+
requires('gui')
|
| 23 |
+
cls.root = Tk()
|
| 24 |
+
cls.root.withdraw()
|
| 25 |
+
cls.mb = browser.ModuleBrowser(cls.root, __file__, _utest=True)
|
| 26 |
+
|
| 27 |
+
@classmethod
|
| 28 |
+
def tearDownClass(cls):
|
| 29 |
+
cls.mb.close()
|
| 30 |
+
cls.root.update_idletasks()
|
| 31 |
+
cls.root.destroy()
|
| 32 |
+
del cls.root, cls.mb
|
| 33 |
+
|
| 34 |
+
def test_init(self):
|
| 35 |
+
mb = self.mb
|
| 36 |
+
eq = self.assertEqual
|
| 37 |
+
eq(mb.path, __file__)
|
| 38 |
+
eq(pyclbr._modules, {})
|
| 39 |
+
self.assertIsInstance(mb.node, TreeNode)
|
| 40 |
+
self.assertIsNotNone(browser.file_open)
|
| 41 |
+
|
| 42 |
+
def test_settitle(self):
|
| 43 |
+
mb = self.mb
|
| 44 |
+
self.assertIn(os.path.basename(__file__), mb.top.title())
|
| 45 |
+
self.assertEqual(mb.top.iconname(), 'Module Browser')
|
| 46 |
+
|
| 47 |
+
def test_rootnode(self):
|
| 48 |
+
mb = self.mb
|
| 49 |
+
rn = mb.rootnode()
|
| 50 |
+
self.assertIsInstance(rn, browser.ModuleBrowserTreeItem)
|
| 51 |
+
|
| 52 |
+
def test_close(self):
|
| 53 |
+
mb = self.mb
|
| 54 |
+
mb.top.destroy = Func()
|
| 55 |
+
mb.node.destroy = Func()
|
| 56 |
+
mb.close()
|
| 57 |
+
self.assertTrue(mb.top.destroy.called)
|
| 58 |
+
self.assertTrue(mb.node.destroy.called)
|
| 59 |
+
del mb.top.destroy, mb.node.destroy
|
| 60 |
+
|
| 61 |
+
def test_is_browseable_extension(self):
|
| 62 |
+
path = "/path/to/file"
|
| 63 |
+
for ext in py_extensions:
|
| 64 |
+
with self.subTest(ext=ext):
|
| 65 |
+
filename = f'{path}{ext}'
|
| 66 |
+
actual = browser.is_browseable_extension(filename)
|
| 67 |
+
expected = ext not in browser.browseable_extension_blocklist
|
| 68 |
+
self.assertEqual(actual, expected)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# Nested tree same as in test_pyclbr.py except for supers on C0. C1.
|
| 72 |
+
mb = pyclbr
|
| 73 |
+
module, fname = 'test', 'test.py'
|
| 74 |
+
C0 = mb.Class(module, 'C0', ['base'], fname, 1, end_lineno=9)
|
| 75 |
+
F1 = mb._nest_function(C0, 'F1', 3, 5)
|
| 76 |
+
C1 = mb._nest_class(C0, 'C1', 6, 9, [''])
|
| 77 |
+
C2 = mb._nest_class(C1, 'C2', 7, 9)
|
| 78 |
+
F3 = mb._nest_function(C2, 'F3', 9, 9)
|
| 79 |
+
f0 = mb.Function(module, 'f0', fname, 11, end_lineno=15)
|
| 80 |
+
f1 = mb._nest_function(f0, 'f1', 12, 14)
|
| 81 |
+
f2 = mb._nest_function(f1, 'f2', 13, 13)
|
| 82 |
+
c1 = mb._nest_class(f0, 'c1', 15, 15)
|
| 83 |
+
mock_pyclbr_tree = {'C0': C0, 'f0': f0}
|
| 84 |
+
|
| 85 |
+
# Adjust C0.name, C1.name so tests do not depend on order.
|
| 86 |
+
browser.transform_children(mock_pyclbr_tree, 'test') # C0(base)
|
| 87 |
+
browser.transform_children(C0.children) # C1()
|
| 88 |
+
|
| 89 |
+
# The class below checks that the calls above are correct
|
| 90 |
+
# and that duplicate calls have no effect.
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class TransformChildrenTest(unittest.TestCase):
|
| 94 |
+
|
| 95 |
+
def test_transform_module_children(self):
|
| 96 |
+
eq = self.assertEqual
|
| 97 |
+
transform = browser.transform_children
|
| 98 |
+
# Parameter matches tree module.
|
| 99 |
+
tcl = list(transform(mock_pyclbr_tree, 'test'))
|
| 100 |
+
eq(tcl, [C0, f0])
|
| 101 |
+
eq(tcl[0].name, 'C0(base)')
|
| 102 |
+
eq(tcl[1].name, 'f0')
|
| 103 |
+
# Check that second call does not change suffix.
|
| 104 |
+
tcl = list(transform(mock_pyclbr_tree, 'test'))
|
| 105 |
+
eq(tcl[0].name, 'C0(base)')
|
| 106 |
+
# Nothing to traverse if parameter name isn't same as tree module.
|
| 107 |
+
tcl = list(transform(mock_pyclbr_tree, 'different name'))
|
| 108 |
+
eq(tcl, [])
|
| 109 |
+
|
| 110 |
+
def test_transform_node_children(self):
|
| 111 |
+
eq = self.assertEqual
|
| 112 |
+
transform = browser.transform_children
|
| 113 |
+
# Class with two children, one name altered.
|
| 114 |
+
tcl = list(transform(C0.children))
|
| 115 |
+
eq(tcl, [F1, C1])
|
| 116 |
+
eq(tcl[0].name, 'F1')
|
| 117 |
+
eq(tcl[1].name, 'C1()')
|
| 118 |
+
tcl = list(transform(C0.children))
|
| 119 |
+
eq(tcl[1].name, 'C1()')
|
| 120 |
+
# Function with two children.
|
| 121 |
+
eq(list(transform(f0.children)), [f1, c1])
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class ModuleBrowserTreeItemTest(unittest.TestCase):
|
| 125 |
+
|
| 126 |
+
@classmethod
|
| 127 |
+
def setUpClass(cls):
|
| 128 |
+
cls.mbt = browser.ModuleBrowserTreeItem(fname)
|
| 129 |
+
|
| 130 |
+
def test_init(self):
|
| 131 |
+
self.assertEqual(self.mbt.file, fname)
|
| 132 |
+
|
| 133 |
+
def test_gettext(self):
|
| 134 |
+
self.assertEqual(self.mbt.GetText(), fname)
|
| 135 |
+
|
| 136 |
+
def test_geticonname(self):
|
| 137 |
+
self.assertEqual(self.mbt.GetIconName(), 'python')
|
| 138 |
+
|
| 139 |
+
def test_isexpandable(self):
|
| 140 |
+
self.assertTrue(self.mbt.IsExpandable())
|
| 141 |
+
|
| 142 |
+
def test_listchildren(self):
|
| 143 |
+
save_rex = browser.pyclbr.readmodule_ex
|
| 144 |
+
save_tc = browser.transform_children
|
| 145 |
+
browser.pyclbr.readmodule_ex = Func(result=mock_pyclbr_tree)
|
| 146 |
+
browser.transform_children = Func(result=[f0, C0])
|
| 147 |
+
try:
|
| 148 |
+
self.assertEqual(self.mbt.listchildren(), [f0, C0])
|
| 149 |
+
finally:
|
| 150 |
+
browser.pyclbr.readmodule_ex = save_rex
|
| 151 |
+
browser.transform_children = save_tc
|
| 152 |
+
|
| 153 |
+
def test_getsublist(self):
|
| 154 |
+
mbt = self.mbt
|
| 155 |
+
mbt.listchildren = Func(result=[f0, C0])
|
| 156 |
+
sub0, sub1 = mbt.GetSubList()
|
| 157 |
+
del mbt.listchildren
|
| 158 |
+
self.assertIsInstance(sub0, browser.ChildBrowserTreeItem)
|
| 159 |
+
self.assertIsInstance(sub1, browser.ChildBrowserTreeItem)
|
| 160 |
+
self.assertEqual(sub0.name, 'f0')
|
| 161 |
+
self.assertEqual(sub1.name, 'C0(base)')
|
| 162 |
+
|
| 163 |
+
@mock.patch('idlelib.browser.file_open')
|
| 164 |
+
def test_ondoubleclick(self, fopen):
|
| 165 |
+
mbt = self.mbt
|
| 166 |
+
|
| 167 |
+
with mock.patch('os.path.exists', return_value=False):
|
| 168 |
+
mbt.OnDoubleClick()
|
| 169 |
+
fopen.assert_not_called()
|
| 170 |
+
|
| 171 |
+
with mock.patch('os.path.exists', return_value=True):
|
| 172 |
+
mbt.OnDoubleClick()
|
| 173 |
+
fopen.assert_called_once_with(fname)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class ChildBrowserTreeItemTest(unittest.TestCase):
|
| 177 |
+
|
| 178 |
+
@classmethod
|
| 179 |
+
def setUpClass(cls):
|
| 180 |
+
CBT = browser.ChildBrowserTreeItem
|
| 181 |
+
cls.cbt_f1 = CBT(f1)
|
| 182 |
+
cls.cbt_C1 = CBT(C1)
|
| 183 |
+
cls.cbt_F1 = CBT(F1)
|
| 184 |
+
|
| 185 |
+
@classmethod
|
| 186 |
+
def tearDownClass(cls):
|
| 187 |
+
del cls.cbt_C1, cls.cbt_f1, cls.cbt_F1
|
| 188 |
+
|
| 189 |
+
def test_init(self):
|
| 190 |
+
eq = self.assertEqual
|
| 191 |
+
eq(self.cbt_C1.name, 'C1()')
|
| 192 |
+
self.assertFalse(self.cbt_C1.isfunction)
|
| 193 |
+
eq(self.cbt_f1.name, 'f1')
|
| 194 |
+
self.assertTrue(self.cbt_f1.isfunction)
|
| 195 |
+
|
| 196 |
+
def test_gettext(self):
|
| 197 |
+
self.assertEqual(self.cbt_C1.GetText(), 'class C1()')
|
| 198 |
+
self.assertEqual(self.cbt_f1.GetText(), 'def f1(...)')
|
| 199 |
+
|
| 200 |
+
def test_geticonname(self):
|
| 201 |
+
self.assertEqual(self.cbt_C1.GetIconName(), 'folder')
|
| 202 |
+
self.assertEqual(self.cbt_f1.GetIconName(), 'python')
|
| 203 |
+
|
| 204 |
+
def test_isexpandable(self):
|
| 205 |
+
self.assertTrue(self.cbt_C1.IsExpandable())
|
| 206 |
+
self.assertTrue(self.cbt_f1.IsExpandable())
|
| 207 |
+
self.assertFalse(self.cbt_F1.IsExpandable())
|
| 208 |
+
|
| 209 |
+
def test_getsublist(self):
|
| 210 |
+
eq = self.assertEqual
|
| 211 |
+
CBT = browser.ChildBrowserTreeItem
|
| 212 |
+
|
| 213 |
+
f1sublist = self.cbt_f1.GetSubList()
|
| 214 |
+
self.assertIsInstance(f1sublist[0], CBT)
|
| 215 |
+
eq(len(f1sublist), 1)
|
| 216 |
+
eq(f1sublist[0].name, 'f2')
|
| 217 |
+
|
| 218 |
+
eq(self.cbt_F1.GetSubList(), [])
|
| 219 |
+
|
| 220 |
+
@mock.patch('idlelib.browser.file_open')
|
| 221 |
+
def test_ondoubleclick(self, fopen):
|
| 222 |
+
goto = fopen.return_value.gotoline = mock.Mock()
|
| 223 |
+
self.cbt_F1.OnDoubleClick()
|
| 224 |
+
fopen.assert_called()
|
| 225 |
+
goto.assert_called()
|
| 226 |
+
goto.assert_called_with(self.cbt_F1.obj.lineno)
|
| 227 |
+
# Failure test would have to raise OSError or AttributeError.
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class NestedChildrenTest(unittest.TestCase):
|
| 231 |
+
"Test that all the nodes in a nested tree are added to the BrowserTree."
|
| 232 |
+
|
| 233 |
+
def test_nested(self):
|
| 234 |
+
queue = deque()
|
| 235 |
+
actual_names = []
|
| 236 |
+
# The tree items are processed in breadth first order.
|
| 237 |
+
# Verify that processing each sublist hits every node and
|
| 238 |
+
# in the right order.
|
| 239 |
+
expected_names = ['f0', 'C0(base)',
|
| 240 |
+
'f1', 'c1', 'F1', 'C1()',
|
| 241 |
+
'f2', 'C2',
|
| 242 |
+
'F3']
|
| 243 |
+
CBT = browser.ChildBrowserTreeItem
|
| 244 |
+
queue.extend((CBT(f0), CBT(C0)))
|
| 245 |
+
while queue:
|
| 246 |
+
cb = queue.popleft()
|
| 247 |
+
sublist = cb.GetSubList()
|
| 248 |
+
queue.extend(sublist)
|
| 249 |
+
self.assertIn(cb.name, cb.GetText())
|
| 250 |
+
self.assertIn(cb.GetIconName(), ('python', 'folder'))
|
| 251 |
+
self.assertIs(cb.IsExpandable(), sublist != [])
|
| 252 |
+
actual_names.append(cb.name)
|
| 253 |
+
self.assertEqual(actual_names, expected_names)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
if __name__ == '__main__':
|
| 257 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_calltip.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test calltip, coverage 76%"
|
| 2 |
+
|
| 3 |
+
from idlelib import calltip
|
| 4 |
+
import unittest
|
| 5 |
+
from unittest.mock import Mock
|
| 6 |
+
import textwrap
|
| 7 |
+
import types
|
| 8 |
+
import re
|
| 9 |
+
from idlelib.idle_test.mock_tk import Text
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Test Class TC is used in multiple get_argspec test methods
|
| 13 |
+
class TC:
|
| 14 |
+
'doc'
|
| 15 |
+
tip = "(ai=None, *b)"
|
| 16 |
+
def __init__(self, ai=None, *b): 'doc'
|
| 17 |
+
__init__.tip = "(self, ai=None, *b)"
|
| 18 |
+
def t1(self): 'doc'
|
| 19 |
+
t1.tip = "(self)"
|
| 20 |
+
def t2(self, ai, b=None): 'doc'
|
| 21 |
+
t2.tip = "(self, ai, b=None)"
|
| 22 |
+
def t3(self, ai, *args): 'doc'
|
| 23 |
+
t3.tip = "(self, ai, *args)"
|
| 24 |
+
def t4(self, *args): 'doc'
|
| 25 |
+
t4.tip = "(self, *args)"
|
| 26 |
+
def t5(self, ai, b=None, *args, **kw): 'doc'
|
| 27 |
+
t5.tip = "(self, ai, b=None, *args, **kw)"
|
| 28 |
+
def t6(no, self): 'doc'
|
| 29 |
+
t6.tip = "(no, self)"
|
| 30 |
+
def __call__(self, ci): 'doc'
|
| 31 |
+
__call__.tip = "(self, ci)"
|
| 32 |
+
def nd(self): pass # No doc.
|
| 33 |
+
# attaching .tip to wrapped methods does not work
|
| 34 |
+
@classmethod
|
| 35 |
+
def cm(cls, a): 'doc'
|
| 36 |
+
@staticmethod
|
| 37 |
+
def sm(b): 'doc'
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
tc = TC()
|
| 41 |
+
default_tip = calltip._default_callable_argspec
|
| 42 |
+
get_spec = calltip.get_argspec
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class Get_argspecTest(unittest.TestCase):
|
| 46 |
+
# The get_spec function must return a string, even if blank.
|
| 47 |
+
# Test a variety of objects to be sure that none cause it to raise
|
| 48 |
+
# (quite aside from getting as correct an answer as possible).
|
| 49 |
+
# The tests of builtins may break if inspect or the docstrings change,
|
| 50 |
+
# but a red buildbot is better than a user crash (as has happened).
|
| 51 |
+
# For a simple mismatch, change the expected output to the actual.
|
| 52 |
+
|
| 53 |
+
def test_builtins(self):
|
| 54 |
+
|
| 55 |
+
def tiptest(obj, out):
|
| 56 |
+
self.assertEqual(get_spec(obj), out)
|
| 57 |
+
|
| 58 |
+
# Python class that inherits builtin methods
|
| 59 |
+
class List(list): "List() doc"
|
| 60 |
+
|
| 61 |
+
# Simulate builtin with no docstring for default tip test
|
| 62 |
+
class SB: __call__ = None
|
| 63 |
+
|
| 64 |
+
if List.__doc__ is not None:
|
| 65 |
+
tiptest(List,
|
| 66 |
+
f'(iterable=(), /)'
|
| 67 |
+
f'\n{List.__doc__}')
|
| 68 |
+
tiptest(list.__new__,
|
| 69 |
+
'(*args, **kwargs)\n'
|
| 70 |
+
'Create and return a new object. '
|
| 71 |
+
'See help(type) for accurate signature.')
|
| 72 |
+
tiptest(list.__init__,
|
| 73 |
+
'(self, /, *args, **kwargs)\n'
|
| 74 |
+
'Initialize self. See help(type(self)) for accurate signature.')
|
| 75 |
+
append_doc = "\nAppend object to the end of the list."
|
| 76 |
+
tiptest(list.append, '(self, object, /)' + append_doc)
|
| 77 |
+
tiptest(List.append, '(self, object, /)' + append_doc)
|
| 78 |
+
tiptest([].append, '(object, /)' + append_doc)
|
| 79 |
+
|
| 80 |
+
tiptest(types.MethodType, "method(function, instance)")
|
| 81 |
+
tiptest(SB(), default_tip)
|
| 82 |
+
|
| 83 |
+
p = re.compile('')
|
| 84 |
+
tiptest(re.sub, '''\
|
| 85 |
+
(pattern, repl, string, count=0, flags=0)
|
| 86 |
+
Return the string obtained by replacing the leftmost
|
| 87 |
+
non-overlapping occurrences of the pattern in string by the
|
| 88 |
+
replacement repl. repl can be either a string or a callable;
|
| 89 |
+
if a string, backslash escapes in it are processed. If it is
|
| 90 |
+
a callable, it's passed the Match object and must return''')
|
| 91 |
+
tiptest(p.sub, '''\
|
| 92 |
+
(repl, string, count=0)
|
| 93 |
+
Return the string obtained by replacing the leftmost \
|
| 94 |
+
non-overlapping occurrences o...''')
|
| 95 |
+
|
| 96 |
+
def test_signature_wrap(self):
|
| 97 |
+
if textwrap.TextWrapper.__doc__ is not None:
|
| 98 |
+
self.assertEqual(get_spec(textwrap.TextWrapper), '''\
|
| 99 |
+
(width=70, initial_indent='', subsequent_indent='', expand_tabs=True,
|
| 100 |
+
replace_whitespace=True, fix_sentence_endings=False, break_long_words=True,
|
| 101 |
+
drop_whitespace=True, break_on_hyphens=True, tabsize=8, *, max_lines=None,
|
| 102 |
+
placeholder=' [...]')
|
| 103 |
+
Object for wrapping/filling text. The public interface consists of
|
| 104 |
+
the wrap() and fill() methods; the other methods are just there for
|
| 105 |
+
subclasses to override in order to tweak the default behaviour.
|
| 106 |
+
If you want to completely replace the main wrapping algorithm,
|
| 107 |
+
you\'ll probably have to override _wrap_chunks().''')
|
| 108 |
+
|
| 109 |
+
def test_properly_formatted(self):
|
| 110 |
+
|
| 111 |
+
def foo(s='a'*100):
|
| 112 |
+
pass
|
| 113 |
+
|
| 114 |
+
def bar(s='a'*100):
|
| 115 |
+
"""Hello Guido"""
|
| 116 |
+
pass
|
| 117 |
+
|
| 118 |
+
def baz(s='a'*100, z='b'*100):
|
| 119 |
+
pass
|
| 120 |
+
|
| 121 |
+
indent = calltip._INDENT
|
| 122 |
+
|
| 123 |
+
sfoo = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\
|
| 124 |
+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\
|
| 125 |
+
"aaaaaaaaaa')"
|
| 126 |
+
sbar = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\
|
| 127 |
+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\
|
| 128 |
+
"aaaaaaaaaa')\nHello Guido"
|
| 129 |
+
sbaz = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\
|
| 130 |
+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\
|
| 131 |
+
"aaaaaaaaaa', z='bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"\
|
| 132 |
+
"bbbbbbbbbbbbbbbbb\n" + indent + "bbbbbbbbbbbbbbbbbbbbbb"\
|
| 133 |
+
"bbbbbbbbbbbbbbbbbbbbbb')"
|
| 134 |
+
|
| 135 |
+
for func,doc in [(foo, sfoo), (bar, sbar), (baz, sbaz)]:
|
| 136 |
+
with self.subTest(func=func, doc=doc):
|
| 137 |
+
self.assertEqual(get_spec(func), doc)
|
| 138 |
+
|
| 139 |
+
def test_docline_truncation(self):
|
| 140 |
+
def f(): pass
|
| 141 |
+
f.__doc__ = 'a'*300
|
| 142 |
+
self.assertEqual(get_spec(f), f"()\n{'a'*(calltip._MAX_COLS-3) + '...'}")
|
| 143 |
+
|
| 144 |
+
def test_multiline_docstring(self):
|
| 145 |
+
# Test fewer lines than max.
|
| 146 |
+
self.assertEqual(get_spec(range),
|
| 147 |
+
"range(stop) -> range object\n"
|
| 148 |
+
"range(start, stop[, step]) -> range object")
|
| 149 |
+
|
| 150 |
+
# Test max lines
|
| 151 |
+
self.assertEqual(get_spec(bytes), '''\
|
| 152 |
+
bytes(iterable_of_ints) -> bytes
|
| 153 |
+
bytes(string, encoding[, errors]) -> bytes
|
| 154 |
+
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
|
| 155 |
+
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
|
| 156 |
+
bytes() -> empty bytes object''')
|
| 157 |
+
|
| 158 |
+
# Test more than max lines
|
| 159 |
+
def f(): pass
|
| 160 |
+
f.__doc__ = 'a\n' * 15
|
| 161 |
+
self.assertEqual(get_spec(f), '()' + '\na' * calltip._MAX_LINES)
|
| 162 |
+
|
| 163 |
+
def test_functions(self):
|
| 164 |
+
def t1(): 'doc'
|
| 165 |
+
t1.tip = "()"
|
| 166 |
+
def t2(a, b=None): 'doc'
|
| 167 |
+
t2.tip = "(a, b=None)"
|
| 168 |
+
def t3(a, *args): 'doc'
|
| 169 |
+
t3.tip = "(a, *args)"
|
| 170 |
+
def t4(*args): 'doc'
|
| 171 |
+
t4.tip = "(*args)"
|
| 172 |
+
def t5(a, b=None, *args, **kw): 'doc'
|
| 173 |
+
t5.tip = "(a, b=None, *args, **kw)"
|
| 174 |
+
|
| 175 |
+
doc = '\ndoc' if t1.__doc__ is not None else ''
|
| 176 |
+
for func in (t1, t2, t3, t4, t5, TC):
|
| 177 |
+
with self.subTest(func=func):
|
| 178 |
+
self.assertEqual(get_spec(func), func.tip + doc)
|
| 179 |
+
|
| 180 |
+
def test_methods(self):
|
| 181 |
+
doc = '\ndoc' if TC.__doc__ is not None else ''
|
| 182 |
+
for meth in (TC.t1, TC.t2, TC.t3, TC.t4, TC.t5, TC.t6, TC.__call__):
|
| 183 |
+
with self.subTest(meth=meth):
|
| 184 |
+
self.assertEqual(get_spec(meth), meth.tip + doc)
|
| 185 |
+
self.assertEqual(get_spec(TC.cm), "(a)" + doc)
|
| 186 |
+
self.assertEqual(get_spec(TC.sm), "(b)" + doc)
|
| 187 |
+
|
| 188 |
+
def test_bound_methods(self):
|
| 189 |
+
# test that first parameter is correctly removed from argspec
|
| 190 |
+
doc = '\ndoc' if TC.__doc__ is not None else ''
|
| 191 |
+
for meth, mtip in ((tc.t1, "()"), (tc.t4, "(*args)"),
|
| 192 |
+
(tc.t6, "(self)"), (tc.__call__, '(ci)'),
|
| 193 |
+
(tc, '(ci)'), (TC.cm, "(a)"),):
|
| 194 |
+
with self.subTest(meth=meth, mtip=mtip):
|
| 195 |
+
self.assertEqual(get_spec(meth), mtip + doc)
|
| 196 |
+
|
| 197 |
+
def test_starred_parameter(self):
|
| 198 |
+
# test that starred first parameter is *not* removed from argspec
|
| 199 |
+
class C:
|
| 200 |
+
def m1(*args): pass
|
| 201 |
+
c = C()
|
| 202 |
+
for meth, mtip in ((C.m1, '(*args)'), (c.m1, "(*args)"),):
|
| 203 |
+
with self.subTest(meth=meth, mtip=mtip):
|
| 204 |
+
self.assertEqual(get_spec(meth), mtip)
|
| 205 |
+
|
| 206 |
+
def test_invalid_method_get_spec(self):
|
| 207 |
+
class C:
|
| 208 |
+
def m2(**kwargs): pass
|
| 209 |
+
class Test:
|
| 210 |
+
def __call__(*, a): pass
|
| 211 |
+
|
| 212 |
+
mtip = calltip._invalid_method
|
| 213 |
+
self.assertEqual(get_spec(C().m2), mtip)
|
| 214 |
+
self.assertEqual(get_spec(Test()), mtip)
|
| 215 |
+
|
| 216 |
+
def test_non_ascii_name(self):
|
| 217 |
+
# test that re works to delete a first parameter name that
|
| 218 |
+
# includes non-ascii chars, such as various forms of A.
|
| 219 |
+
uni = "(A\u0391\u0410\u05d0\u0627\u0905\u1e00\u3042, a)"
|
| 220 |
+
assert calltip._first_param.sub('', uni) == '(a)'
|
| 221 |
+
|
| 222 |
+
def test_no_docstring(self):
|
| 223 |
+
for meth, mtip in ((TC.nd, "(self)"), (tc.nd, "()")):
|
| 224 |
+
with self.subTest(meth=meth, mtip=mtip):
|
| 225 |
+
self.assertEqual(get_spec(meth), mtip)
|
| 226 |
+
|
| 227 |
+
def test_buggy_getattr_class(self):
|
| 228 |
+
class NoCall:
|
| 229 |
+
def __getattr__(self, name): # Not invoked for class attribute.
|
| 230 |
+
raise IndexError # Bug.
|
| 231 |
+
class CallA(NoCall):
|
| 232 |
+
def __call__(self, ci): # Bug does not matter.
|
| 233 |
+
pass
|
| 234 |
+
class CallB(NoCall):
|
| 235 |
+
def __call__(oui, a, b, c): # Non-standard 'self'.
|
| 236 |
+
pass
|
| 237 |
+
|
| 238 |
+
for meth, mtip in ((NoCall, default_tip), (CallA, default_tip),
|
| 239 |
+
(NoCall(), ''), (CallA(), '(ci)'),
|
| 240 |
+
(CallB(), '(a, b, c)')):
|
| 241 |
+
with self.subTest(meth=meth, mtip=mtip):
|
| 242 |
+
self.assertEqual(get_spec(meth), mtip)
|
| 243 |
+
|
| 244 |
+
def test_metaclass_class(self): # Failure case for issue 38689.
|
| 245 |
+
class Type(type): # Type() requires 3 type args, returns class.
|
| 246 |
+
__class__ = property({}.__getitem__, {}.__setitem__)
|
| 247 |
+
class Object(metaclass=Type):
|
| 248 |
+
__slots__ = '__class__'
|
| 249 |
+
for meth, mtip in ((Type, get_spec(type)), (Object, default_tip),
|
| 250 |
+
(Object(), '')):
|
| 251 |
+
with self.subTest(meth=meth, mtip=mtip):
|
| 252 |
+
self.assertEqual(get_spec(meth), mtip)
|
| 253 |
+
|
| 254 |
+
def test_non_callables(self):
|
| 255 |
+
for obj in (0, 0.0, '0', b'0', [], {}):
|
| 256 |
+
with self.subTest(obj=obj):
|
| 257 |
+
self.assertEqual(get_spec(obj), '')
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class Get_entityTest(unittest.TestCase):
|
| 261 |
+
def test_bad_entity(self):
|
| 262 |
+
self.assertIsNone(calltip.get_entity('1/0'))
|
| 263 |
+
def test_good_entity(self):
|
| 264 |
+
self.assertIs(calltip.get_entity('int'), int)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# Test the 9 Calltip methods.
|
| 268 |
+
# open_calltip is about half the code; the others are fairly trivial.
|
| 269 |
+
# The default mocks are what are needed for open_calltip.
|
| 270 |
+
|
| 271 |
+
class mock_Shell:
|
| 272 |
+
"Return mock sufficient to pass to hyperparser."
|
| 273 |
+
def __init__(self, text):
|
| 274 |
+
text.tag_prevrange = Mock(return_value=None)
|
| 275 |
+
self.text = text
|
| 276 |
+
self.prompt_last_line = ">>> "
|
| 277 |
+
self.indentwidth = 4
|
| 278 |
+
self.tabwidth = 8
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class mock_TipWindow:
|
| 282 |
+
def __init__(self):
|
| 283 |
+
pass
|
| 284 |
+
|
| 285 |
+
def showtip(self, text, parenleft, parenright):
|
| 286 |
+
self.args = parenleft, parenright
|
| 287 |
+
self.parenline, self.parencol = map(int, parenleft.split('.'))
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class WrappedCalltip(calltip.Calltip):
|
| 291 |
+
def _make_tk_calltip_window(self):
|
| 292 |
+
return mock_TipWindow()
|
| 293 |
+
|
| 294 |
+
def remove_calltip_window(self, event=None):
|
| 295 |
+
if self.active_calltip: # Setup to None.
|
| 296 |
+
self.active_calltip = None
|
| 297 |
+
self.tips_removed += 1 # Setup to 0.
|
| 298 |
+
|
| 299 |
+
def fetch_tip(self, expression):
|
| 300 |
+
return 'tip'
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class CalltipTest(unittest.TestCase):
|
| 304 |
+
|
| 305 |
+
@classmethod
|
| 306 |
+
def setUpClass(cls):
|
| 307 |
+
cls.text = Text()
|
| 308 |
+
cls.ct = WrappedCalltip(mock_Shell(cls.text))
|
| 309 |
+
|
| 310 |
+
def setUp(self):
|
| 311 |
+
self.text.delete('1.0', 'end') # Insert and call
|
| 312 |
+
self.ct.active_calltip = None
|
| 313 |
+
# Test .active_calltip, +args
|
| 314 |
+
self.ct.tips_removed = 0
|
| 315 |
+
|
| 316 |
+
def open_close(self, testfunc):
|
| 317 |
+
# Open-close template with testfunc called in between.
|
| 318 |
+
opentip = self.ct.open_calltip
|
| 319 |
+
self.text.insert(1.0, 'f(')
|
| 320 |
+
opentip(False)
|
| 321 |
+
self.tip = self.ct.active_calltip
|
| 322 |
+
testfunc(self) ###
|
| 323 |
+
self.text.insert('insert', ')')
|
| 324 |
+
opentip(False)
|
| 325 |
+
self.assertIsNone(self.ct.active_calltip, None)
|
| 326 |
+
|
| 327 |
+
def test_open_close(self):
|
| 328 |
+
def args(self):
|
| 329 |
+
self.assertEqual(self.tip.args, ('1.1', '1.end'))
|
| 330 |
+
self.open_close(args)
|
| 331 |
+
|
| 332 |
+
def test_repeated_force(self):
|
| 333 |
+
def force(self):
|
| 334 |
+
for char in 'abc':
|
| 335 |
+
self.text.insert('insert', 'a')
|
| 336 |
+
self.ct.open_calltip(True)
|
| 337 |
+
self.ct.open_calltip(True)
|
| 338 |
+
self.assertIs(self.ct.active_calltip, self.tip)
|
| 339 |
+
self.open_close(force)
|
| 340 |
+
|
| 341 |
+
def test_repeated_parens(self):
|
| 342 |
+
def parens(self):
|
| 343 |
+
for context in "a", "'":
|
| 344 |
+
with self.subTest(context=context):
|
| 345 |
+
self.text.insert('insert', context)
|
| 346 |
+
for char in '(()())':
|
| 347 |
+
self.text.insert('insert', char)
|
| 348 |
+
self.assertIs(self.ct.active_calltip, self.tip)
|
| 349 |
+
self.text.insert('insert', "'")
|
| 350 |
+
self.open_close(parens)
|
| 351 |
+
|
| 352 |
+
def test_comment_parens(self):
|
| 353 |
+
def comment(self):
|
| 354 |
+
self.text.insert('insert', "# ")
|
| 355 |
+
for char in '(()())':
|
| 356 |
+
self.text.insert('insert', char)
|
| 357 |
+
self.assertIs(self.ct.active_calltip, self.tip)
|
| 358 |
+
self.text.insert('insert', "\n")
|
| 359 |
+
self.open_close(comment)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
if __name__ == '__main__':
|
| 363 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_config_key.py
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test config_key, coverage 98%.
|
| 2 |
+
|
| 3 |
+
Coverage is effectively 100%. Tkinter dialog is mocked, Mac-only line
|
| 4 |
+
may be skipped, and dummy function in bind test should not be called.
|
| 5 |
+
Not tested: exit with 'self.advanced or self.keys_ok(keys) ...' False.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from idlelib import config_key
|
| 9 |
+
from test.support import requires
|
| 10 |
+
import unittest
|
| 11 |
+
from unittest import mock
|
| 12 |
+
from tkinter import Tk, TclError
|
| 13 |
+
from idlelib.idle_test.mock_idle import Func
|
| 14 |
+
from idlelib.idle_test.mock_tk import Mbox_func
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class ValidationTest(unittest.TestCase):
|
| 18 |
+
"Test validation methods: ok, keys_ok, bind_ok."
|
| 19 |
+
|
| 20 |
+
class Validator(config_key.GetKeysFrame):
|
| 21 |
+
def __init__(self, *args, **kwargs):
|
| 22 |
+
super().__init__(*args, **kwargs)
|
| 23 |
+
class list_keys_final:
|
| 24 |
+
get = Func()
|
| 25 |
+
self.list_keys_final = list_keys_final
|
| 26 |
+
get_modifiers = Func()
|
| 27 |
+
showerror = Mbox_func()
|
| 28 |
+
|
| 29 |
+
@classmethod
|
| 30 |
+
def setUpClass(cls):
|
| 31 |
+
requires('gui')
|
| 32 |
+
cls.root = Tk()
|
| 33 |
+
cls.root.withdraw()
|
| 34 |
+
keylist = [['<Key-F12>'], ['<Control-Key-x>', '<Control-Key-X>']]
|
| 35 |
+
cls.dialog = cls.Validator(cls.root, '<<Test>>', keylist)
|
| 36 |
+
|
| 37 |
+
@classmethod
|
| 38 |
+
def tearDownClass(cls):
|
| 39 |
+
del cls.dialog
|
| 40 |
+
cls.root.update_idletasks()
|
| 41 |
+
cls.root.destroy()
|
| 42 |
+
del cls.root
|
| 43 |
+
|
| 44 |
+
def setUp(self):
|
| 45 |
+
self.dialog.showerror.message = ''
|
| 46 |
+
# A test that needs a particular final key value should set it.
|
| 47 |
+
# A test that sets a non-blank modifier list should reset it to [].
|
| 48 |
+
|
| 49 |
+
def test_ok_empty(self):
|
| 50 |
+
self.dialog.key_string.set(' ')
|
| 51 |
+
self.dialog.ok()
|
| 52 |
+
self.assertEqual(self.dialog.result, '')
|
| 53 |
+
self.assertEqual(self.dialog.showerror.message, 'No key specified.')
|
| 54 |
+
|
| 55 |
+
def test_ok_good(self):
|
| 56 |
+
self.dialog.key_string.set('<Key-F11>')
|
| 57 |
+
self.dialog.list_keys_final.get.result = 'F11'
|
| 58 |
+
self.dialog.ok()
|
| 59 |
+
self.assertEqual(self.dialog.result, '<Key-F11>')
|
| 60 |
+
self.assertEqual(self.dialog.showerror.message, '')
|
| 61 |
+
|
| 62 |
+
def test_keys_no_ending(self):
|
| 63 |
+
self.assertFalse(self.dialog.keys_ok('<Control-Shift'))
|
| 64 |
+
self.assertIn('Missing the final', self.dialog.showerror.message)
|
| 65 |
+
|
| 66 |
+
def test_keys_no_modifier_bad(self):
|
| 67 |
+
self.dialog.list_keys_final.get.result = 'A'
|
| 68 |
+
self.assertFalse(self.dialog.keys_ok('<Key-A>'))
|
| 69 |
+
self.assertIn('No modifier', self.dialog.showerror.message)
|
| 70 |
+
|
| 71 |
+
def test_keys_no_modifier_ok(self):
|
| 72 |
+
self.dialog.list_keys_final.get.result = 'F11'
|
| 73 |
+
self.assertTrue(self.dialog.keys_ok('<Key-F11>'))
|
| 74 |
+
self.assertEqual(self.dialog.showerror.message, '')
|
| 75 |
+
|
| 76 |
+
def test_keys_shift_bad(self):
|
| 77 |
+
self.dialog.list_keys_final.get.result = 'a'
|
| 78 |
+
self.dialog.get_modifiers.result = ['Shift']
|
| 79 |
+
self.assertFalse(self.dialog.keys_ok('<a>'))
|
| 80 |
+
self.assertIn('shift modifier', self.dialog.showerror.message)
|
| 81 |
+
self.dialog.get_modifiers.result = []
|
| 82 |
+
|
| 83 |
+
def test_keys_dup(self):
|
| 84 |
+
for mods, final, seq in (([], 'F12', '<Key-F12>'),
|
| 85 |
+
(['Control'], 'x', '<Control-Key-x>'),
|
| 86 |
+
(['Control'], 'X', '<Control-Key-X>')):
|
| 87 |
+
with self.subTest(m=mods, f=final, s=seq):
|
| 88 |
+
self.dialog.list_keys_final.get.result = final
|
| 89 |
+
self.dialog.get_modifiers.result = mods
|
| 90 |
+
self.assertFalse(self.dialog.keys_ok(seq))
|
| 91 |
+
self.assertIn('already in use', self.dialog.showerror.message)
|
| 92 |
+
self.dialog.get_modifiers.result = []
|
| 93 |
+
|
| 94 |
+
def test_bind_ok(self):
|
| 95 |
+
self.assertTrue(self.dialog.bind_ok('<Control-Shift-Key-a>'))
|
| 96 |
+
self.assertEqual(self.dialog.showerror.message, '')
|
| 97 |
+
|
| 98 |
+
def test_bind_not_ok(self):
|
| 99 |
+
self.assertFalse(self.dialog.bind_ok('<Control-Shift>'))
|
| 100 |
+
self.assertIn('not accepted', self.dialog.showerror.message)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class ToggleLevelTest(unittest.TestCase):
|
| 104 |
+
"Test toggle between Basic and Advanced frames."
|
| 105 |
+
|
| 106 |
+
@classmethod
|
| 107 |
+
def setUpClass(cls):
|
| 108 |
+
requires('gui')
|
| 109 |
+
cls.root = Tk()
|
| 110 |
+
cls.root.withdraw()
|
| 111 |
+
cls.dialog = config_key.GetKeysFrame(cls.root, '<<Test>>', [])
|
| 112 |
+
|
| 113 |
+
@classmethod
|
| 114 |
+
def tearDownClass(cls):
|
| 115 |
+
del cls.dialog
|
| 116 |
+
cls.root.update_idletasks()
|
| 117 |
+
cls.root.destroy()
|
| 118 |
+
del cls.root
|
| 119 |
+
|
| 120 |
+
def test_toggle_level(self):
|
| 121 |
+
dialog = self.dialog
|
| 122 |
+
|
| 123 |
+
def stackorder():
|
| 124 |
+
"""Get the stack order of the children of the frame.
|
| 125 |
+
|
| 126 |
+
winfo_children() stores the children in stack order, so
|
| 127 |
+
this can be used to check whether a frame is above or
|
| 128 |
+
below another one.
|
| 129 |
+
"""
|
| 130 |
+
for index, child in enumerate(dialog.winfo_children()):
|
| 131 |
+
if child._name == 'keyseq_basic':
|
| 132 |
+
basic = index
|
| 133 |
+
if child._name == 'keyseq_advanced':
|
| 134 |
+
advanced = index
|
| 135 |
+
return basic, advanced
|
| 136 |
+
|
| 137 |
+
# New window starts at basic level.
|
| 138 |
+
self.assertFalse(dialog.advanced)
|
| 139 |
+
self.assertIn('Advanced', dialog.button_level['text'])
|
| 140 |
+
basic, advanced = stackorder()
|
| 141 |
+
self.assertGreater(basic, advanced)
|
| 142 |
+
|
| 143 |
+
# Toggle to advanced.
|
| 144 |
+
dialog.toggle_level()
|
| 145 |
+
self.assertTrue(dialog.advanced)
|
| 146 |
+
self.assertIn('Basic', dialog.button_level['text'])
|
| 147 |
+
basic, advanced = stackorder()
|
| 148 |
+
self.assertGreater(advanced, basic)
|
| 149 |
+
|
| 150 |
+
# Toggle to basic.
|
| 151 |
+
dialog.button_level.invoke()
|
| 152 |
+
self.assertFalse(dialog.advanced)
|
| 153 |
+
self.assertIn('Advanced', dialog.button_level['text'])
|
| 154 |
+
basic, advanced = stackorder()
|
| 155 |
+
self.assertGreater(basic, advanced)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class KeySelectionTest(unittest.TestCase):
|
| 159 |
+
"Test selecting key on Basic frames."
|
| 160 |
+
|
| 161 |
+
class Basic(config_key.GetKeysFrame):
|
| 162 |
+
def __init__(self, *args, **kwargs):
|
| 163 |
+
super().__init__(*args, **kwargs)
|
| 164 |
+
class list_keys_final:
|
| 165 |
+
get = Func()
|
| 166 |
+
select_clear = Func()
|
| 167 |
+
yview = Func()
|
| 168 |
+
self.list_keys_final = list_keys_final
|
| 169 |
+
def set_modifiers_for_platform(self):
|
| 170 |
+
self.modifiers = ['foo', 'bar', 'BAZ']
|
| 171 |
+
self.modifier_label = {'BAZ': 'ZZZ'}
|
| 172 |
+
showerror = Mbox_func()
|
| 173 |
+
|
| 174 |
+
@classmethod
|
| 175 |
+
def setUpClass(cls):
|
| 176 |
+
requires('gui')
|
| 177 |
+
cls.root = Tk()
|
| 178 |
+
cls.root.withdraw()
|
| 179 |
+
cls.dialog = cls.Basic(cls.root, '<<Test>>', [])
|
| 180 |
+
|
| 181 |
+
@classmethod
|
| 182 |
+
def tearDownClass(cls):
|
| 183 |
+
del cls.dialog
|
| 184 |
+
cls.root.update_idletasks()
|
| 185 |
+
cls.root.destroy()
|
| 186 |
+
del cls.root
|
| 187 |
+
|
| 188 |
+
def setUp(self):
|
| 189 |
+
self.dialog.clear_key_seq()
|
| 190 |
+
|
| 191 |
+
def test_get_modifiers(self):
|
| 192 |
+
dialog = self.dialog
|
| 193 |
+
gm = dialog.get_modifiers
|
| 194 |
+
eq = self.assertEqual
|
| 195 |
+
|
| 196 |
+
# Modifiers are set on/off by invoking the checkbutton.
|
| 197 |
+
dialog.modifier_checkbuttons['foo'].invoke()
|
| 198 |
+
eq(gm(), ['foo'])
|
| 199 |
+
|
| 200 |
+
dialog.modifier_checkbuttons['BAZ'].invoke()
|
| 201 |
+
eq(gm(), ['foo', 'BAZ'])
|
| 202 |
+
|
| 203 |
+
dialog.modifier_checkbuttons['foo'].invoke()
|
| 204 |
+
eq(gm(), ['BAZ'])
|
| 205 |
+
|
| 206 |
+
@mock.patch.object(config_key.GetKeysFrame, 'get_modifiers')
|
| 207 |
+
def test_build_key_string(self, mock_modifiers):
|
| 208 |
+
dialog = self.dialog
|
| 209 |
+
key = dialog.list_keys_final
|
| 210 |
+
string = dialog.key_string.get
|
| 211 |
+
eq = self.assertEqual
|
| 212 |
+
|
| 213 |
+
key.get.result = 'a'
|
| 214 |
+
mock_modifiers.return_value = []
|
| 215 |
+
dialog.build_key_string()
|
| 216 |
+
eq(string(), '<Key-a>')
|
| 217 |
+
|
| 218 |
+
mock_modifiers.return_value = ['mymod']
|
| 219 |
+
dialog.build_key_string()
|
| 220 |
+
eq(string(), '<mymod-Key-a>')
|
| 221 |
+
|
| 222 |
+
key.get.result = ''
|
| 223 |
+
mock_modifiers.return_value = ['mymod', 'test']
|
| 224 |
+
dialog.build_key_string()
|
| 225 |
+
eq(string(), '<mymod-test>')
|
| 226 |
+
|
| 227 |
+
@mock.patch.object(config_key.GetKeysFrame, 'get_modifiers')
|
| 228 |
+
def test_final_key_selected(self, mock_modifiers):
|
| 229 |
+
dialog = self.dialog
|
| 230 |
+
key = dialog.list_keys_final
|
| 231 |
+
string = dialog.key_string.get
|
| 232 |
+
eq = self.assertEqual
|
| 233 |
+
|
| 234 |
+
mock_modifiers.return_value = ['Shift']
|
| 235 |
+
key.get.result = '{'
|
| 236 |
+
dialog.final_key_selected()
|
| 237 |
+
eq(string(), '<Shift-Key-braceleft>')
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
class CancelWindowTest(unittest.TestCase):
|
| 241 |
+
"Simulate user clicking [Cancel] button."
|
| 242 |
+
|
| 243 |
+
@classmethod
|
| 244 |
+
def setUpClass(cls):
|
| 245 |
+
requires('gui')
|
| 246 |
+
cls.root = Tk()
|
| 247 |
+
cls.root.withdraw()
|
| 248 |
+
cls.dialog = config_key.GetKeysWindow(
|
| 249 |
+
cls.root, 'Title', '<<Test>>', [], _utest=True)
|
| 250 |
+
|
| 251 |
+
@classmethod
|
| 252 |
+
def tearDownClass(cls):
|
| 253 |
+
cls.dialog.cancel()
|
| 254 |
+
del cls.dialog
|
| 255 |
+
cls.root.update_idletasks()
|
| 256 |
+
cls.root.destroy()
|
| 257 |
+
del cls.root
|
| 258 |
+
|
| 259 |
+
@mock.patch.object(config_key.GetKeysFrame, 'ok')
|
| 260 |
+
def test_cancel(self, mock_frame_ok):
|
| 261 |
+
self.assertEqual(self.dialog.winfo_class(), 'Toplevel')
|
| 262 |
+
self.dialog.button_cancel.invoke()
|
| 263 |
+
with self.assertRaises(TclError):
|
| 264 |
+
self.dialog.winfo_class()
|
| 265 |
+
self.assertEqual(self.dialog.result, '')
|
| 266 |
+
mock_frame_ok.assert_not_called()
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class OKWindowTest(unittest.TestCase):
|
| 270 |
+
"Simulate user clicking [OK] button."
|
| 271 |
+
|
| 272 |
+
@classmethod
|
| 273 |
+
def setUpClass(cls):
|
| 274 |
+
requires('gui')
|
| 275 |
+
cls.root = Tk()
|
| 276 |
+
cls.root.withdraw()
|
| 277 |
+
cls.dialog = config_key.GetKeysWindow(
|
| 278 |
+
cls.root, 'Title', '<<Test>>', [], _utest=True)
|
| 279 |
+
|
| 280 |
+
@classmethod
|
| 281 |
+
def tearDownClass(cls):
|
| 282 |
+
cls.dialog.cancel()
|
| 283 |
+
del cls.dialog
|
| 284 |
+
cls.root.update_idletasks()
|
| 285 |
+
cls.root.destroy()
|
| 286 |
+
del cls.root
|
| 287 |
+
|
| 288 |
+
@mock.patch.object(config_key.GetKeysFrame, 'ok')
|
| 289 |
+
def test_ok(self, mock_frame_ok):
|
| 290 |
+
self.assertEqual(self.dialog.winfo_class(), 'Toplevel')
|
| 291 |
+
self.dialog.button_ok.invoke()
|
| 292 |
+
with self.assertRaises(TclError):
|
| 293 |
+
self.dialog.winfo_class()
|
| 294 |
+
mock_frame_ok.assert_called()
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class WindowResultTest(unittest.TestCase):
|
| 298 |
+
"Test window result get and set."
|
| 299 |
+
|
| 300 |
+
@classmethod
|
| 301 |
+
def setUpClass(cls):
|
| 302 |
+
requires('gui')
|
| 303 |
+
cls.root = Tk()
|
| 304 |
+
cls.root.withdraw()
|
| 305 |
+
cls.dialog = config_key.GetKeysWindow(
|
| 306 |
+
cls.root, 'Title', '<<Test>>', [], _utest=True)
|
| 307 |
+
|
| 308 |
+
@classmethod
|
| 309 |
+
def tearDownClass(cls):
|
| 310 |
+
cls.dialog.cancel()
|
| 311 |
+
del cls.dialog
|
| 312 |
+
cls.root.update_idletasks()
|
| 313 |
+
cls.root.destroy()
|
| 314 |
+
del cls.root
|
| 315 |
+
|
| 316 |
+
def test_result(self):
|
| 317 |
+
dialog = self.dialog
|
| 318 |
+
eq = self.assertEqual
|
| 319 |
+
|
| 320 |
+
dialog.result = ''
|
| 321 |
+
eq(dialog.result, '')
|
| 322 |
+
eq(dialog.frame.result,'')
|
| 323 |
+
|
| 324 |
+
dialog.result = 'bar'
|
| 325 |
+
eq(dialog.result,'bar')
|
| 326 |
+
eq(dialog.frame.result,'bar')
|
| 327 |
+
|
| 328 |
+
dialog.frame.result = 'foo'
|
| 329 |
+
eq(dialog.result, 'foo')
|
| 330 |
+
eq(dialog.frame.result,'foo')
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class HelperTest(unittest.TestCase):
|
| 334 |
+
"Test module level helper functions."
|
| 335 |
+
|
| 336 |
+
def test_translate_key(self):
|
| 337 |
+
tr = config_key.translate_key
|
| 338 |
+
eq = self.assertEqual
|
| 339 |
+
|
| 340 |
+
# Letters return unchanged with no 'Shift'.
|
| 341 |
+
eq(tr('q', []), 'Key-q')
|
| 342 |
+
eq(tr('q', ['Control', 'Alt']), 'Key-q')
|
| 343 |
+
|
| 344 |
+
# 'Shift' uppercases single lowercase letters.
|
| 345 |
+
eq(tr('q', ['Shift']), 'Key-Q')
|
| 346 |
+
eq(tr('q', ['Control', 'Shift']), 'Key-Q')
|
| 347 |
+
eq(tr('q', ['Control', 'Alt', 'Shift']), 'Key-Q')
|
| 348 |
+
|
| 349 |
+
# Convert key name to keysym.
|
| 350 |
+
eq(tr('Page Up', []), 'Key-Prior')
|
| 351 |
+
# 'Shift' doesn't change case when it's not a single char.
|
| 352 |
+
eq(tr('*', ['Shift']), 'Key-asterisk')
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
if __name__ == '__main__':
|
| 356 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_delegator.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test delegator, coverage 100%."
|
| 2 |
+
|
| 3 |
+
from idlelib.delegator import Delegator
|
| 4 |
+
import unittest
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class DelegatorTest(unittest.TestCase):
|
| 8 |
+
|
| 9 |
+
def test_mydel(self):
|
| 10 |
+
# Test a simple use scenario.
|
| 11 |
+
|
| 12 |
+
# Initialize an int delegator.
|
| 13 |
+
mydel = Delegator(int)
|
| 14 |
+
self.assertIs(mydel.delegate, int)
|
| 15 |
+
self.assertEqual(mydel._Delegator__cache, set())
|
| 16 |
+
# Trying to access a non-attribute of int fails.
|
| 17 |
+
self.assertRaises(AttributeError, mydel.__getattr__, 'xyz')
|
| 18 |
+
|
| 19 |
+
# Add real int attribute 'bit_length' by accessing it.
|
| 20 |
+
bl = mydel.bit_length
|
| 21 |
+
self.assertIs(bl, int.bit_length)
|
| 22 |
+
self.assertIs(mydel.__dict__['bit_length'], int.bit_length)
|
| 23 |
+
self.assertEqual(mydel._Delegator__cache, {'bit_length'})
|
| 24 |
+
|
| 25 |
+
# Add attribute 'numerator'.
|
| 26 |
+
mydel.numerator
|
| 27 |
+
self.assertEqual(mydel._Delegator__cache, {'bit_length', 'numerator'})
|
| 28 |
+
|
| 29 |
+
# Delete 'numerator'.
|
| 30 |
+
del mydel.numerator
|
| 31 |
+
self.assertNotIn('numerator', mydel.__dict__)
|
| 32 |
+
# The current implementation leaves it in the name cache.
|
| 33 |
+
# self.assertIn('numerator', mydel._Delegator__cache)
|
| 34 |
+
# However, this is not required and not part of the specification
|
| 35 |
+
|
| 36 |
+
# Change delegate to float, first resetting the attributes.
|
| 37 |
+
mydel.setdelegate(float) # calls resetcache
|
| 38 |
+
self.assertNotIn('bit_length', mydel.__dict__)
|
| 39 |
+
self.assertEqual(mydel._Delegator__cache, set())
|
| 40 |
+
self.assertIs(mydel.delegate, float)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if __name__ == '__main__':
|
| 44 |
+
unittest.main(verbosity=2, exit=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_help.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test help, coverage 87%."
|
| 2 |
+
|
| 3 |
+
from idlelib import help
|
| 4 |
+
import unittest
|
| 5 |
+
from test.support import requires
|
| 6 |
+
requires('gui')
|
| 7 |
+
from os.path import abspath, dirname, join
|
| 8 |
+
from tkinter import Tk
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class HelpFrameTest(unittest.TestCase):
|
| 12 |
+
|
| 13 |
+
@classmethod
|
| 14 |
+
def setUpClass(cls):
|
| 15 |
+
"By itself, this tests that file parsed without exception."
|
| 16 |
+
cls.root = root = Tk()
|
| 17 |
+
root.withdraw()
|
| 18 |
+
helpfile = join(dirname(dirname(abspath(__file__))), 'help.html')
|
| 19 |
+
cls.frame = help.HelpFrame(root, helpfile)
|
| 20 |
+
|
| 21 |
+
@classmethod
|
| 22 |
+
def tearDownClass(cls):
|
| 23 |
+
del cls.frame
|
| 24 |
+
cls.root.update_idletasks()
|
| 25 |
+
cls.root.destroy()
|
| 26 |
+
del cls.root
|
| 27 |
+
|
| 28 |
+
def test_line1(self):
|
| 29 |
+
text = self.frame.text
|
| 30 |
+
self.assertEqual(text.get('1.0', '1.end'), ' IDLE ')
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if __name__ == '__main__':
|
| 34 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_help_about.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test help_about, coverage 100%.
|
| 2 |
+
help_about.build_bits branches on sys.platform='darwin'.
|
| 3 |
+
'100% combines coverage on Mac and others.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from idlelib import help_about
|
| 7 |
+
import unittest
|
| 8 |
+
from test.support import requires, findfile
|
| 9 |
+
from tkinter import Tk, TclError
|
| 10 |
+
from idlelib.idle_test.mock_idle import Func
|
| 11 |
+
from idlelib.idle_test.mock_tk import Mbox_func
|
| 12 |
+
from idlelib import textview
|
| 13 |
+
import os.path
|
| 14 |
+
from platform import python_version
|
| 15 |
+
|
| 16 |
+
About = help_about.AboutDialog
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class LiveDialogTest(unittest.TestCase):
|
| 20 |
+
"""Simulate user clicking buttons other than [Close].
|
| 21 |
+
|
| 22 |
+
Test that invoked textview has text from source.
|
| 23 |
+
"""
|
| 24 |
+
@classmethod
|
| 25 |
+
def setUpClass(cls):
|
| 26 |
+
requires('gui')
|
| 27 |
+
cls.root = Tk()
|
| 28 |
+
cls.root.withdraw()
|
| 29 |
+
cls.dialog = About(cls.root, 'About IDLE', _utest=True)
|
| 30 |
+
|
| 31 |
+
@classmethod
|
| 32 |
+
def tearDownClass(cls):
|
| 33 |
+
del cls.dialog
|
| 34 |
+
cls.root.update_idletasks()
|
| 35 |
+
cls.root.destroy()
|
| 36 |
+
del cls.root
|
| 37 |
+
|
| 38 |
+
def test_build_bits(self):
|
| 39 |
+
self.assertIn(help_about.build_bits(), ('32', '64'))
|
| 40 |
+
|
| 41 |
+
def test_dialog_title(self):
|
| 42 |
+
"""Test about dialog title"""
|
| 43 |
+
self.assertEqual(self.dialog.title(), 'About IDLE')
|
| 44 |
+
|
| 45 |
+
def test_dialog_logo(self):
|
| 46 |
+
"""Test about dialog logo."""
|
| 47 |
+
path, file = os.path.split(self.dialog.icon_image['file'])
|
| 48 |
+
fn, ext = os.path.splitext(file)
|
| 49 |
+
self.assertEqual(fn, 'idle_48')
|
| 50 |
+
|
| 51 |
+
def test_printer_buttons(self):
|
| 52 |
+
"""Test buttons whose commands use printer function."""
|
| 53 |
+
dialog = self.dialog
|
| 54 |
+
button_sources = [(dialog.py_license, license, 'license'),
|
| 55 |
+
(dialog.py_copyright, copyright, 'copyright'),
|
| 56 |
+
(dialog.py_credits, credits, 'credits')]
|
| 57 |
+
|
| 58 |
+
for button, printer, name in button_sources:
|
| 59 |
+
with self.subTest(name=name):
|
| 60 |
+
printer._Printer__setup()
|
| 61 |
+
button.invoke()
|
| 62 |
+
get = dialog._current_textview.viewframe.textframe.text.get
|
| 63 |
+
lines = printer._Printer__lines
|
| 64 |
+
if len(lines) < 2:
|
| 65 |
+
self.fail(name + ' full text was not found')
|
| 66 |
+
self.assertEqual(lines[0], get('1.0', '1.end'))
|
| 67 |
+
self.assertEqual(lines[1], get('2.0', '2.end'))
|
| 68 |
+
dialog._current_textview.destroy()
|
| 69 |
+
|
| 70 |
+
def test_file_buttons(self):
|
| 71 |
+
"""Test buttons that display files."""
|
| 72 |
+
dialog = self.dialog
|
| 73 |
+
button_sources = [(self.dialog.readme, 'README.txt', 'readme'),
|
| 74 |
+
(self.dialog.idle_news, 'NEWS.txt', 'news'),
|
| 75 |
+
(self.dialog.idle_credits, 'CREDITS.txt', 'credits')]
|
| 76 |
+
|
| 77 |
+
for button, filename, name in button_sources:
|
| 78 |
+
with self.subTest(name=name):
|
| 79 |
+
button.invoke()
|
| 80 |
+
fn = findfile(filename, subdir='idlelib')
|
| 81 |
+
get = dialog._current_textview.viewframe.textframe.text.get
|
| 82 |
+
with open(fn, encoding='utf-8') as f:
|
| 83 |
+
self.assertEqual(f.readline().strip(), get('1.0', '1.end'))
|
| 84 |
+
f.readline()
|
| 85 |
+
self.assertEqual(f.readline().strip(), get('3.0', '3.end'))
|
| 86 |
+
dialog._current_textview.destroy()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class DefaultTitleTest(unittest.TestCase):
|
| 90 |
+
"Test default title."
|
| 91 |
+
|
| 92 |
+
@classmethod
|
| 93 |
+
def setUpClass(cls):
|
| 94 |
+
requires('gui')
|
| 95 |
+
cls.root = Tk()
|
| 96 |
+
cls.root.withdraw()
|
| 97 |
+
cls.dialog = About(cls.root, _utest=True)
|
| 98 |
+
|
| 99 |
+
@classmethod
|
| 100 |
+
def tearDownClass(cls):
|
| 101 |
+
del cls.dialog
|
| 102 |
+
cls.root.update_idletasks()
|
| 103 |
+
cls.root.destroy()
|
| 104 |
+
del cls.root
|
| 105 |
+
|
| 106 |
+
def test_dialog_title(self):
|
| 107 |
+
"""Test about dialog title"""
|
| 108 |
+
self.assertEqual(self.dialog.title(),
|
| 109 |
+
f'About IDLE {python_version()}'
|
| 110 |
+
f' ({help_about.build_bits()} bit)')
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class CloseTest(unittest.TestCase):
|
| 114 |
+
"""Simulate user clicking [Close] button"""
|
| 115 |
+
|
| 116 |
+
@classmethod
|
| 117 |
+
def setUpClass(cls):
|
| 118 |
+
requires('gui')
|
| 119 |
+
cls.root = Tk()
|
| 120 |
+
cls.root.withdraw()
|
| 121 |
+
cls.dialog = About(cls.root, 'About IDLE', _utest=True)
|
| 122 |
+
|
| 123 |
+
@classmethod
|
| 124 |
+
def tearDownClass(cls):
|
| 125 |
+
del cls.dialog
|
| 126 |
+
cls.root.update_idletasks()
|
| 127 |
+
cls.root.destroy()
|
| 128 |
+
del cls.root
|
| 129 |
+
|
| 130 |
+
def test_close(self):
|
| 131 |
+
self.assertEqual(self.dialog.winfo_class(), 'Toplevel')
|
| 132 |
+
self.dialog.button_ok.invoke()
|
| 133 |
+
with self.assertRaises(TclError):
|
| 134 |
+
self.dialog.winfo_class()
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class Dummy_about_dialog:
|
| 138 |
+
# Dummy class for testing file display functions.
|
| 139 |
+
idle_credits = About.show_idle_credits
|
| 140 |
+
idle_readme = About.show_readme
|
| 141 |
+
idle_news = About.show_idle_news
|
| 142 |
+
# Called by the above
|
| 143 |
+
display_file_text = About.display_file_text
|
| 144 |
+
_utest = True
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class DisplayFileTest(unittest.TestCase):
|
| 148 |
+
"""Test functions that display files.
|
| 149 |
+
|
| 150 |
+
While somewhat redundant with gui-based test_file_dialog,
|
| 151 |
+
these unit tests run on all buildbots, not just a few.
|
| 152 |
+
"""
|
| 153 |
+
dialog = Dummy_about_dialog()
|
| 154 |
+
|
| 155 |
+
@classmethod
|
| 156 |
+
def setUpClass(cls):
|
| 157 |
+
cls.orig_error = textview.showerror
|
| 158 |
+
cls.orig_view = textview.view_text
|
| 159 |
+
cls.error = Mbox_func()
|
| 160 |
+
cls.view = Func()
|
| 161 |
+
textview.showerror = cls.error
|
| 162 |
+
textview.view_text = cls.view
|
| 163 |
+
|
| 164 |
+
@classmethod
|
| 165 |
+
def tearDownClass(cls):
|
| 166 |
+
textview.showerror = cls.orig_error
|
| 167 |
+
textview.view_text = cls.orig_view
|
| 168 |
+
|
| 169 |
+
def test_file_display(self):
|
| 170 |
+
for handler in (self.dialog.idle_credits,
|
| 171 |
+
self.dialog.idle_readme,
|
| 172 |
+
self.dialog.idle_news):
|
| 173 |
+
self.error.message = ''
|
| 174 |
+
self.view.called = False
|
| 175 |
+
with self.subTest(handler=handler):
|
| 176 |
+
handler()
|
| 177 |
+
self.assertEqual(self.error.message, '')
|
| 178 |
+
self.assertEqual(self.view.called, True)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
if __name__ == '__main__':
|
| 182 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_multicall.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test multicall, coverage 33%."
|
| 2 |
+
|
| 3 |
+
from idlelib import multicall
|
| 4 |
+
import unittest
|
| 5 |
+
from test.support import requires
|
| 6 |
+
from tkinter import Tk, Text
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class MultiCallTest(unittest.TestCase):
|
| 10 |
+
|
| 11 |
+
@classmethod
|
| 12 |
+
def setUpClass(cls):
|
| 13 |
+
requires('gui')
|
| 14 |
+
cls.root = Tk()
|
| 15 |
+
cls.root.withdraw()
|
| 16 |
+
cls.mc = multicall.MultiCallCreator(Text)
|
| 17 |
+
|
| 18 |
+
@classmethod
|
| 19 |
+
def tearDownClass(cls):
|
| 20 |
+
del cls.mc
|
| 21 |
+
cls.root.update_idletasks()
|
| 22 |
+
## for id in cls.root.tk.call('after', 'info'):
|
| 23 |
+
## cls.root.after_cancel(id) # Need for EditorWindow.
|
| 24 |
+
cls.root.destroy()
|
| 25 |
+
del cls.root
|
| 26 |
+
|
| 27 |
+
def test_creator(self):
|
| 28 |
+
mc = self.mc
|
| 29 |
+
self.assertIs(multicall._multicall_dict[Text], mc)
|
| 30 |
+
self.assertTrue(issubclass(mc, Text))
|
| 31 |
+
mc2 = multicall.MultiCallCreator(Text)
|
| 32 |
+
self.assertIs(mc, mc2)
|
| 33 |
+
|
| 34 |
+
def test_init(self):
|
| 35 |
+
mctext = self.mc(self.root)
|
| 36 |
+
self.assertIsInstance(mctext._MultiCall__binders, list)
|
| 37 |
+
|
| 38 |
+
def test_yview(self):
|
| 39 |
+
# Added for tree.wheel_event
|
| 40 |
+
# (it depends on yview to not be overridden)
|
| 41 |
+
mc = self.mc
|
| 42 |
+
self.assertIs(mc.yview, Text.yview)
|
| 43 |
+
mctext = self.mc(self.root)
|
| 44 |
+
self.assertIs(mctext.yview.__func__, Text.yview)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if __name__ == '__main__':
|
| 48 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_parenmatch.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test parenmatch, coverage 91%.
|
| 2 |
+
|
| 3 |
+
This must currently be a gui test because ParenMatch methods use
|
| 4 |
+
several text methods not defined on idlelib.idle_test.mock_tk.Text.
|
| 5 |
+
"""
|
| 6 |
+
from idlelib.parenmatch import ParenMatch
|
| 7 |
+
from test.support import requires
|
| 8 |
+
requires('gui')
|
| 9 |
+
|
| 10 |
+
import unittest
|
| 11 |
+
from unittest.mock import Mock
|
| 12 |
+
from tkinter import Tk, Text
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class DummyEditwin:
|
| 16 |
+
def __init__(self, text):
|
| 17 |
+
self.text = text
|
| 18 |
+
self.indentwidth = 8
|
| 19 |
+
self.tabwidth = 8
|
| 20 |
+
self.prompt_last_line = '>>>' # Currently not used by parenmatch.
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class ParenMatchTest(unittest.TestCase):
|
| 24 |
+
|
| 25 |
+
@classmethod
|
| 26 |
+
def setUpClass(cls):
|
| 27 |
+
cls.root = Tk()
|
| 28 |
+
cls.root.withdraw()
|
| 29 |
+
cls.text = Text(cls.root)
|
| 30 |
+
cls.editwin = DummyEditwin(cls.text)
|
| 31 |
+
cls.editwin.text_frame = Mock()
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def tearDownClass(cls):
|
| 35 |
+
del cls.text, cls.editwin
|
| 36 |
+
cls.root.update_idletasks()
|
| 37 |
+
cls.root.destroy()
|
| 38 |
+
del cls.root
|
| 39 |
+
|
| 40 |
+
def tearDown(self):
|
| 41 |
+
self.text.delete('1.0', 'end')
|
| 42 |
+
|
| 43 |
+
def get_parenmatch(self):
|
| 44 |
+
pm = ParenMatch(self.editwin)
|
| 45 |
+
pm.bell = lambda: None
|
| 46 |
+
return pm
|
| 47 |
+
|
| 48 |
+
def test_paren_styles(self):
|
| 49 |
+
"""
|
| 50 |
+
Test ParenMatch with each style.
|
| 51 |
+
"""
|
| 52 |
+
text = self.text
|
| 53 |
+
pm = self.get_parenmatch()
|
| 54 |
+
for style, range1, range2 in (
|
| 55 |
+
('opener', ('1.10', '1.11'), ('1.10', '1.11')),
|
| 56 |
+
('default',('1.10', '1.11'),('1.10', '1.11')),
|
| 57 |
+
('parens', ('1.14', '1.15'), ('1.15', '1.16')),
|
| 58 |
+
('expression', ('1.10', '1.15'), ('1.10', '1.16'))):
|
| 59 |
+
with self.subTest(style=style):
|
| 60 |
+
text.delete('1.0', 'end')
|
| 61 |
+
pm.STYLE = style
|
| 62 |
+
text.insert('insert', 'def foobar(a, b')
|
| 63 |
+
|
| 64 |
+
pm.flash_paren_event('event')
|
| 65 |
+
self.assertIn('<<parenmatch-check-restore>>', text.event_info())
|
| 66 |
+
if style == 'parens':
|
| 67 |
+
self.assertTupleEqual(text.tag_nextrange('paren', '1.0'),
|
| 68 |
+
('1.10', '1.11'))
|
| 69 |
+
self.assertTupleEqual(
|
| 70 |
+
text.tag_prevrange('paren', 'end'), range1)
|
| 71 |
+
|
| 72 |
+
text.insert('insert', ')')
|
| 73 |
+
pm.restore_event()
|
| 74 |
+
self.assertNotIn('<<parenmatch-check-restore>>',
|
| 75 |
+
text.event_info())
|
| 76 |
+
self.assertEqual(text.tag_prevrange('paren', 'end'), ())
|
| 77 |
+
|
| 78 |
+
pm.paren_closed_event('event')
|
| 79 |
+
self.assertTupleEqual(
|
| 80 |
+
text.tag_prevrange('paren', 'end'), range2)
|
| 81 |
+
|
| 82 |
+
def test_paren_corner(self):
|
| 83 |
+
"""
|
| 84 |
+
Test corner cases in flash_paren_event and paren_closed_event.
|
| 85 |
+
|
| 86 |
+
Force execution of conditional expressions and alternate paths.
|
| 87 |
+
"""
|
| 88 |
+
text = self.text
|
| 89 |
+
pm = self.get_parenmatch()
|
| 90 |
+
|
| 91 |
+
text.insert('insert', '# Comment.)')
|
| 92 |
+
pm.paren_closed_event('event')
|
| 93 |
+
|
| 94 |
+
text.insert('insert', '\ndef')
|
| 95 |
+
pm.flash_paren_event('event')
|
| 96 |
+
pm.paren_closed_event('event')
|
| 97 |
+
|
| 98 |
+
text.insert('insert', ' a, *arg)')
|
| 99 |
+
pm.paren_closed_event('event')
|
| 100 |
+
|
| 101 |
+
def test_handle_restore_timer(self):
|
| 102 |
+
pm = self.get_parenmatch()
|
| 103 |
+
pm.restore_event = Mock()
|
| 104 |
+
pm.handle_restore_timer(0)
|
| 105 |
+
self.assertTrue(pm.restore_event.called)
|
| 106 |
+
pm.restore_event.reset_mock()
|
| 107 |
+
pm.handle_restore_timer(1)
|
| 108 |
+
self.assertFalse(pm.restore_event.called)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if __name__ == '__main__':
|
| 112 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_pathbrowser.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test pathbrowser, coverage 95%."
|
| 2 |
+
|
| 3 |
+
from idlelib import pathbrowser
|
| 4 |
+
import unittest
|
| 5 |
+
from test.support import requires
|
| 6 |
+
from tkinter import Tk
|
| 7 |
+
|
| 8 |
+
import os.path
|
| 9 |
+
import pyclbr # for _modules
|
| 10 |
+
import sys # for sys.path
|
| 11 |
+
|
| 12 |
+
from idlelib.idle_test.mock_idle import Func
|
| 13 |
+
import idlelib # for __file__
|
| 14 |
+
from idlelib import browser
|
| 15 |
+
from idlelib.tree import TreeNode
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class PathBrowserTest(unittest.TestCase):
|
| 19 |
+
|
| 20 |
+
@classmethod
|
| 21 |
+
def setUpClass(cls):
|
| 22 |
+
requires('gui')
|
| 23 |
+
cls.root = Tk()
|
| 24 |
+
cls.root.withdraw()
|
| 25 |
+
cls.pb = pathbrowser.PathBrowser(cls.root, _utest=True)
|
| 26 |
+
|
| 27 |
+
@classmethod
|
| 28 |
+
def tearDownClass(cls):
|
| 29 |
+
cls.pb.close()
|
| 30 |
+
cls.root.update_idletasks()
|
| 31 |
+
cls.root.destroy()
|
| 32 |
+
del cls.root, cls.pb
|
| 33 |
+
|
| 34 |
+
def test_init(self):
|
| 35 |
+
pb = self.pb
|
| 36 |
+
eq = self.assertEqual
|
| 37 |
+
eq(pb.master, self.root)
|
| 38 |
+
eq(pyclbr._modules, {})
|
| 39 |
+
self.assertIsInstance(pb.node, TreeNode)
|
| 40 |
+
self.assertIsNotNone(browser.file_open)
|
| 41 |
+
|
| 42 |
+
def test_settitle(self):
|
| 43 |
+
pb = self.pb
|
| 44 |
+
self.assertEqual(pb.top.title(), 'Path Browser')
|
| 45 |
+
self.assertEqual(pb.top.iconname(), 'Path Browser')
|
| 46 |
+
|
| 47 |
+
def test_rootnode(self):
|
| 48 |
+
pb = self.pb
|
| 49 |
+
rn = pb.rootnode()
|
| 50 |
+
self.assertIsInstance(rn, pathbrowser.PathBrowserTreeItem)
|
| 51 |
+
|
| 52 |
+
def test_close(self):
|
| 53 |
+
pb = self.pb
|
| 54 |
+
pb.top.destroy = Func()
|
| 55 |
+
pb.node.destroy = Func()
|
| 56 |
+
pb.close()
|
| 57 |
+
self.assertTrue(pb.top.destroy.called)
|
| 58 |
+
self.assertTrue(pb.node.destroy.called)
|
| 59 |
+
del pb.top.destroy, pb.node.destroy
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class DirBrowserTreeItemTest(unittest.TestCase):
|
| 63 |
+
|
| 64 |
+
def test_DirBrowserTreeItem(self):
|
| 65 |
+
# Issue16226 - make sure that getting a sublist works
|
| 66 |
+
d = pathbrowser.DirBrowserTreeItem('')
|
| 67 |
+
d.GetSubList()
|
| 68 |
+
self.assertEqual('', d.GetText())
|
| 69 |
+
|
| 70 |
+
dir = os.path.split(os.path.abspath(idlelib.__file__))[0]
|
| 71 |
+
self.assertEqual(d.ispackagedir(dir), True)
|
| 72 |
+
self.assertEqual(d.ispackagedir(dir + '/Icons'), False)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class PathBrowserTreeItemTest(unittest.TestCase):
|
| 76 |
+
|
| 77 |
+
def test_PathBrowserTreeItem(self):
|
| 78 |
+
p = pathbrowser.PathBrowserTreeItem()
|
| 79 |
+
self.assertEqual(p.GetText(), 'sys.path')
|
| 80 |
+
sub = p.GetSubList()
|
| 81 |
+
self.assertEqual(len(sub), len(sys.path))
|
| 82 |
+
self.assertEqual(type(sub[0]), pathbrowser.DirBrowserTreeItem)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if __name__ == '__main__':
|
| 86 |
+
unittest.main(verbosity=2, exit=False)
|
parrot/lib/python3.10/idlelib/idle_test/test_replace.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test replace, coverage 78%."
|
| 2 |
+
|
| 3 |
+
from idlelib.replace import ReplaceDialog
|
| 4 |
+
import unittest
|
| 5 |
+
from test.support import requires
|
| 6 |
+
requires('gui')
|
| 7 |
+
from tkinter import Tk, Text
|
| 8 |
+
|
| 9 |
+
from unittest.mock import Mock
|
| 10 |
+
from idlelib.idle_test.mock_tk import Mbox
|
| 11 |
+
import idlelib.searchengine as se
|
| 12 |
+
|
| 13 |
+
orig_mbox = se.messagebox
|
| 14 |
+
showerror = Mbox.showerror
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class ReplaceDialogTest(unittest.TestCase):
|
| 18 |
+
|
| 19 |
+
@classmethod
|
| 20 |
+
def setUpClass(cls):
|
| 21 |
+
cls.root = Tk()
|
| 22 |
+
cls.root.withdraw()
|
| 23 |
+
se.messagebox = Mbox
|
| 24 |
+
cls.engine = se.SearchEngine(cls.root)
|
| 25 |
+
cls.dialog = ReplaceDialog(cls.root, cls.engine)
|
| 26 |
+
cls.dialog.bell = lambda: None
|
| 27 |
+
cls.dialog.ok = Mock()
|
| 28 |
+
cls.text = Text(cls.root)
|
| 29 |
+
cls.text.undo_block_start = Mock()
|
| 30 |
+
cls.text.undo_block_stop = Mock()
|
| 31 |
+
cls.dialog.text = cls.text
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def tearDownClass(cls):
|
| 35 |
+
se.messagebox = orig_mbox
|
| 36 |
+
del cls.text, cls.dialog, cls.engine
|
| 37 |
+
cls.root.destroy()
|
| 38 |
+
del cls.root
|
| 39 |
+
|
| 40 |
+
def setUp(self):
|
| 41 |
+
self.text.insert('insert', 'This is a sample sTring')
|
| 42 |
+
|
| 43 |
+
def tearDown(self):
|
| 44 |
+
self.engine.patvar.set('')
|
| 45 |
+
self.dialog.replvar.set('')
|
| 46 |
+
self.engine.wordvar.set(False)
|
| 47 |
+
self.engine.casevar.set(False)
|
| 48 |
+
self.engine.revar.set(False)
|
| 49 |
+
self.engine.wrapvar.set(True)
|
| 50 |
+
self.engine.backvar.set(False)
|
| 51 |
+
showerror.title = ''
|
| 52 |
+
showerror.message = ''
|
| 53 |
+
self.text.delete('1.0', 'end')
|
| 54 |
+
|
| 55 |
+
def test_replace_simple(self):
|
| 56 |
+
# Test replace function with all options at default setting.
|
| 57 |
+
# Wrap around - True
|
| 58 |
+
# Regular Expression - False
|
| 59 |
+
# Match case - False
|
| 60 |
+
# Match word - False
|
| 61 |
+
# Direction - Forwards
|
| 62 |
+
text = self.text
|
| 63 |
+
equal = self.assertEqual
|
| 64 |
+
pv = self.engine.patvar
|
| 65 |
+
rv = self.dialog.replvar
|
| 66 |
+
replace = self.dialog.replace_it
|
| 67 |
+
|
| 68 |
+
# test accessor method
|
| 69 |
+
self.engine.setpat('asdf')
|
| 70 |
+
equal(self.engine.getpat(), pv.get())
|
| 71 |
+
|
| 72 |
+
# text found and replaced
|
| 73 |
+
pv.set('a')
|
| 74 |
+
rv.set('asdf')
|
| 75 |
+
replace()
|
| 76 |
+
equal(text.get('1.8', '1.12'), 'asdf')
|
| 77 |
+
|
| 78 |
+
# don't "match word" case
|
| 79 |
+
text.mark_set('insert', '1.0')
|
| 80 |
+
pv.set('is')
|
| 81 |
+
rv.set('hello')
|
| 82 |
+
replace()
|
| 83 |
+
equal(text.get('1.2', '1.7'), 'hello')
|
| 84 |
+
|
| 85 |
+
# don't "match case" case
|
| 86 |
+
pv.set('string')
|
| 87 |
+
rv.set('world')
|
| 88 |
+
replace()
|
| 89 |
+
equal(text.get('1.23', '1.28'), 'world')
|
| 90 |
+
|
| 91 |
+
# without "regular expression" case
|
| 92 |
+
text.mark_set('insert', 'end')
|
| 93 |
+
text.insert('insert', '\nline42:')
|
| 94 |
+
before_text = text.get('1.0', 'end')
|
| 95 |
+
pv.set(r'[a-z][\d]+')
|
| 96 |
+
replace()
|
| 97 |
+
after_text = text.get('1.0', 'end')
|
| 98 |
+
equal(before_text, after_text)
|
| 99 |
+
|
| 100 |
+
# test with wrap around selected and complete a cycle
|
| 101 |
+
text.mark_set('insert', '1.9')
|
| 102 |
+
pv.set('i')
|
| 103 |
+
rv.set('j')
|
| 104 |
+
replace()
|
| 105 |
+
equal(text.get('1.8'), 'i')
|
| 106 |
+
equal(text.get('2.1'), 'j')
|
| 107 |
+
replace()
|
| 108 |
+
equal(text.get('2.1'), 'j')
|
| 109 |
+
equal(text.get('1.8'), 'j')
|
| 110 |
+
before_text = text.get('1.0', 'end')
|
| 111 |
+
replace()
|
| 112 |
+
after_text = text.get('1.0', 'end')
|
| 113 |
+
equal(before_text, after_text)
|
| 114 |
+
|
| 115 |
+
# text not found
|
| 116 |
+
before_text = text.get('1.0', 'end')
|
| 117 |
+
pv.set('foobar')
|
| 118 |
+
replace()
|
| 119 |
+
after_text = text.get('1.0', 'end')
|
| 120 |
+
equal(before_text, after_text)
|
| 121 |
+
|
| 122 |
+
# test access method
|
| 123 |
+
self.dialog.find_it(0)
|
| 124 |
+
|
| 125 |
+
def test_replace_wrap_around(self):
|
| 126 |
+
text = self.text
|
| 127 |
+
equal = self.assertEqual
|
| 128 |
+
pv = self.engine.patvar
|
| 129 |
+
rv = self.dialog.replvar
|
| 130 |
+
replace = self.dialog.replace_it
|
| 131 |
+
self.engine.wrapvar.set(False)
|
| 132 |
+
|
| 133 |
+
# replace candidate found both after and before 'insert'
|
| 134 |
+
text.mark_set('insert', '1.4')
|
| 135 |
+
pv.set('i')
|
| 136 |
+
rv.set('j')
|
| 137 |
+
replace()
|
| 138 |
+
equal(text.get('1.2'), 'i')
|
| 139 |
+
equal(text.get('1.5'), 'j')
|
| 140 |
+
replace()
|
| 141 |
+
equal(text.get('1.2'), 'i')
|
| 142 |
+
equal(text.get('1.20'), 'j')
|
| 143 |
+
replace()
|
| 144 |
+
equal(text.get('1.2'), 'i')
|
| 145 |
+
|
| 146 |
+
# replace candidate found only before 'insert'
|
| 147 |
+
text.mark_set('insert', '1.8')
|
| 148 |
+
pv.set('is')
|
| 149 |
+
before_text = text.get('1.0', 'end')
|
| 150 |
+
replace()
|
| 151 |
+
after_text = text.get('1.0', 'end')
|
| 152 |
+
equal(before_text, after_text)
|
| 153 |
+
|
| 154 |
+
def test_replace_whole_word(self):
|
| 155 |
+
text = self.text
|
| 156 |
+
equal = self.assertEqual
|
| 157 |
+
pv = self.engine.patvar
|
| 158 |
+
rv = self.dialog.replvar
|
| 159 |
+
replace = self.dialog.replace_it
|
| 160 |
+
self.engine.wordvar.set(True)
|
| 161 |
+
|
| 162 |
+
pv.set('is')
|
| 163 |
+
rv.set('hello')
|
| 164 |
+
replace()
|
| 165 |
+
equal(text.get('1.0', '1.4'), 'This')
|
| 166 |
+
equal(text.get('1.5', '1.10'), 'hello')
|
| 167 |
+
|
| 168 |
+
def test_replace_match_case(self):
|
| 169 |
+
equal = self.assertEqual
|
| 170 |
+
text = self.text
|
| 171 |
+
pv = self.engine.patvar
|
| 172 |
+
rv = self.dialog.replvar
|
| 173 |
+
replace = self.dialog.replace_it
|
| 174 |
+
self.engine.casevar.set(True)
|
| 175 |
+
|
| 176 |
+
before_text = self.text.get('1.0', 'end')
|
| 177 |
+
pv.set('this')
|
| 178 |
+
rv.set('that')
|
| 179 |
+
replace()
|
| 180 |
+
after_text = self.text.get('1.0', 'end')
|
| 181 |
+
equal(before_text, after_text)
|
| 182 |
+
|
| 183 |
+
pv.set('This')
|
| 184 |
+
replace()
|
| 185 |
+
equal(text.get('1.0', '1.4'), 'that')
|
| 186 |
+
|
| 187 |
+
def test_replace_regex(self):
|
| 188 |
+
equal = self.assertEqual
|
| 189 |
+
text = self.text
|
| 190 |
+
pv = self.engine.patvar
|
| 191 |
+
rv = self.dialog.replvar
|
| 192 |
+
replace = self.dialog.replace_it
|
| 193 |
+
self.engine.revar.set(True)
|
| 194 |
+
|
| 195 |
+
before_text = text.get('1.0', 'end')
|
| 196 |
+
pv.set(r'[a-z][\d]+')
|
| 197 |
+
rv.set('hello')
|
| 198 |
+
replace()
|
| 199 |
+
after_text = text.get('1.0', 'end')
|
| 200 |
+
equal(before_text, after_text)
|
| 201 |
+
|
| 202 |
+
text.insert('insert', '\nline42')
|
| 203 |
+
replace()
|
| 204 |
+
equal(text.get('2.0', '2.8'), 'linhello')
|
| 205 |
+
|
| 206 |
+
pv.set('')
|
| 207 |
+
replace()
|
| 208 |
+
self.assertIn('error', showerror.title)
|
| 209 |
+
self.assertIn('Empty', showerror.message)
|
| 210 |
+
|
| 211 |
+
pv.set(r'[\d')
|
| 212 |
+
replace()
|
| 213 |
+
self.assertIn('error', showerror.title)
|
| 214 |
+
self.assertIn('Pattern', showerror.message)
|
| 215 |
+
|
| 216 |
+
showerror.title = ''
|
| 217 |
+
showerror.message = ''
|
| 218 |
+
pv.set('[a]')
|
| 219 |
+
rv.set('test\\')
|
| 220 |
+
replace()
|
| 221 |
+
self.assertIn('error', showerror.title)
|
| 222 |
+
self.assertIn('Invalid Replace Expression', showerror.message)
|
| 223 |
+
|
| 224 |
+
# test access method
|
| 225 |
+
self.engine.setcookedpat("?")
|
| 226 |
+
equal(pv.get(), "\\?")
|
| 227 |
+
|
| 228 |
+
def test_replace_backwards(self):
|
| 229 |
+
equal = self.assertEqual
|
| 230 |
+
text = self.text
|
| 231 |
+
pv = self.engine.patvar
|
| 232 |
+
rv = self.dialog.replvar
|
| 233 |
+
replace = self.dialog.replace_it
|
| 234 |
+
self.engine.backvar.set(True)
|
| 235 |
+
|
| 236 |
+
text.insert('insert', '\nis as ')
|
| 237 |
+
|
| 238 |
+
pv.set('is')
|
| 239 |
+
rv.set('was')
|
| 240 |
+
replace()
|
| 241 |
+
equal(text.get('1.2', '1.4'), 'is')
|
| 242 |
+
equal(text.get('2.0', '2.3'), 'was')
|
| 243 |
+
replace()
|
| 244 |
+
equal(text.get('1.5', '1.8'), 'was')
|
| 245 |
+
replace()
|
| 246 |
+
equal(text.get('1.2', '1.5'), 'was')
|
| 247 |
+
|
| 248 |
+
def test_replace_all(self):
|
| 249 |
+
text = self.text
|
| 250 |
+
pv = self.engine.patvar
|
| 251 |
+
rv = self.dialog.replvar
|
| 252 |
+
replace_all = self.dialog.replace_all
|
| 253 |
+
|
| 254 |
+
text.insert('insert', '\n')
|
| 255 |
+
text.insert('insert', text.get('1.0', 'end')*100)
|
| 256 |
+
pv.set('is')
|
| 257 |
+
rv.set('was')
|
| 258 |
+
replace_all()
|
| 259 |
+
self.assertNotIn('is', text.get('1.0', 'end'))
|
| 260 |
+
|
| 261 |
+
self.engine.revar.set(True)
|
| 262 |
+
pv.set('')
|
| 263 |
+
replace_all()
|
| 264 |
+
self.assertIn('error', showerror.title)
|
| 265 |
+
self.assertIn('Empty', showerror.message)
|
| 266 |
+
|
| 267 |
+
pv.set('[s][T]')
|
| 268 |
+
rv.set('\\')
|
| 269 |
+
replace_all()
|
| 270 |
+
|
| 271 |
+
self.engine.revar.set(False)
|
| 272 |
+
pv.set('text which is not present')
|
| 273 |
+
rv.set('foobar')
|
| 274 |
+
replace_all()
|
| 275 |
+
|
| 276 |
+
def test_default_command(self):
|
| 277 |
+
text = self.text
|
| 278 |
+
pv = self.engine.patvar
|
| 279 |
+
rv = self.dialog.replvar
|
| 280 |
+
replace_find = self.dialog.default_command
|
| 281 |
+
equal = self.assertEqual
|
| 282 |
+
|
| 283 |
+
pv.set('This')
|
| 284 |
+
rv.set('was')
|
| 285 |
+
replace_find()
|
| 286 |
+
equal(text.get('sel.first', 'sel.last'), 'was')
|
| 287 |
+
|
| 288 |
+
self.engine.revar.set(True)
|
| 289 |
+
pv.set('')
|
| 290 |
+
replace_find()
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
if __name__ == '__main__':
|
| 294 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_run.py
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test run, coverage 54%."
|
| 2 |
+
|
| 3 |
+
from idlelib import run
|
| 4 |
+
import io
|
| 5 |
+
import sys
|
| 6 |
+
from test.support import captured_output, captured_stderr
|
| 7 |
+
import unittest
|
| 8 |
+
from unittest import mock
|
| 9 |
+
import idlelib
|
| 10 |
+
from idlelib.idle_test.mock_idle import Func
|
| 11 |
+
|
| 12 |
+
idlelib.testing = True # Use {} for executing test user code.
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ExceptionTest(unittest.TestCase):
|
| 16 |
+
|
| 17 |
+
def test_print_exception_unhashable(self):
|
| 18 |
+
class UnhashableException(Exception):
|
| 19 |
+
def __eq__(self, other):
|
| 20 |
+
return True
|
| 21 |
+
|
| 22 |
+
ex1 = UnhashableException('ex1')
|
| 23 |
+
ex2 = UnhashableException('ex2')
|
| 24 |
+
try:
|
| 25 |
+
raise ex2 from ex1
|
| 26 |
+
except UnhashableException:
|
| 27 |
+
try:
|
| 28 |
+
raise ex1
|
| 29 |
+
except UnhashableException:
|
| 30 |
+
with captured_stderr() as output:
|
| 31 |
+
with mock.patch.object(run, 'cleanup_traceback') as ct:
|
| 32 |
+
ct.side_effect = lambda t, e: t
|
| 33 |
+
run.print_exception()
|
| 34 |
+
|
| 35 |
+
tb = output.getvalue().strip().splitlines()
|
| 36 |
+
self.assertEqual(11, len(tb))
|
| 37 |
+
self.assertIn('UnhashableException: ex2', tb[3])
|
| 38 |
+
self.assertIn('UnhashableException: ex1', tb[10])
|
| 39 |
+
|
| 40 |
+
data = (('1/0', ZeroDivisionError, "division by zero\n"),
|
| 41 |
+
('abc', NameError, "name 'abc' is not defined. "
|
| 42 |
+
"Did you mean: 'abs'?\n"),
|
| 43 |
+
('int.reel', AttributeError,
|
| 44 |
+
"type object 'int' has no attribute 'reel'. "
|
| 45 |
+
"Did you mean: 'real'?\n"),
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
def test_get_message(self):
|
| 49 |
+
for code, exc, msg in self.data:
|
| 50 |
+
with self.subTest(code=code):
|
| 51 |
+
try:
|
| 52 |
+
eval(compile(code, '', 'eval'))
|
| 53 |
+
except exc:
|
| 54 |
+
typ, val, tb = sys.exc_info()
|
| 55 |
+
actual = run.get_message_lines(typ, val, tb)[0]
|
| 56 |
+
expect = f'{exc.__name__}: {msg}'
|
| 57 |
+
self.assertEqual(actual, expect)
|
| 58 |
+
|
| 59 |
+
@mock.patch.object(run, 'cleanup_traceback',
|
| 60 |
+
new_callable=lambda: (lambda t, e: None))
|
| 61 |
+
def test_get_multiple_message(self, mock):
|
| 62 |
+
d = self.data
|
| 63 |
+
data2 = ((d[0], d[1]), (d[1], d[2]), (d[2], d[0]))
|
| 64 |
+
subtests = 0
|
| 65 |
+
for (code1, exc1, msg1), (code2, exc2, msg2) in data2:
|
| 66 |
+
with self.subTest(codes=(code1,code2)):
|
| 67 |
+
try:
|
| 68 |
+
eval(compile(code1, '', 'eval'))
|
| 69 |
+
except exc1:
|
| 70 |
+
try:
|
| 71 |
+
eval(compile(code2, '', 'eval'))
|
| 72 |
+
except exc2:
|
| 73 |
+
with captured_stderr() as output:
|
| 74 |
+
run.print_exception()
|
| 75 |
+
actual = output.getvalue()
|
| 76 |
+
self.assertIn(msg1, actual)
|
| 77 |
+
self.assertIn(msg2, actual)
|
| 78 |
+
subtests += 1
|
| 79 |
+
self.assertEqual(subtests, len(data2)) # All subtests ran?
|
| 80 |
+
|
| 81 |
+
# StdioFile tests.
|
| 82 |
+
|
| 83 |
+
class S(str):
|
| 84 |
+
def __str__(self):
|
| 85 |
+
return '%s:str' % type(self).__name__
|
| 86 |
+
def __unicode__(self):
|
| 87 |
+
return '%s:unicode' % type(self).__name__
|
| 88 |
+
def __len__(self):
|
| 89 |
+
return 3
|
| 90 |
+
def __iter__(self):
|
| 91 |
+
return iter('abc')
|
| 92 |
+
def __getitem__(self, *args):
|
| 93 |
+
return '%s:item' % type(self).__name__
|
| 94 |
+
def __getslice__(self, *args):
|
| 95 |
+
return '%s:slice' % type(self).__name__
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class MockShell:
|
| 99 |
+
def __init__(self):
|
| 100 |
+
self.reset()
|
| 101 |
+
def write(self, *args):
|
| 102 |
+
self.written.append(args)
|
| 103 |
+
def readline(self):
|
| 104 |
+
return self.lines.pop()
|
| 105 |
+
def close(self):
|
| 106 |
+
pass
|
| 107 |
+
def reset(self):
|
| 108 |
+
self.written = []
|
| 109 |
+
def push(self, lines):
|
| 110 |
+
self.lines = list(lines)[::-1]
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class StdInputFilesTest(unittest.TestCase):
|
| 114 |
+
|
| 115 |
+
def test_misc(self):
|
| 116 |
+
shell = MockShell()
|
| 117 |
+
f = run.StdInputFile(shell, 'stdin')
|
| 118 |
+
self.assertIsInstance(f, io.TextIOBase)
|
| 119 |
+
self.assertEqual(f.encoding, 'utf-8')
|
| 120 |
+
self.assertEqual(f.errors, 'strict')
|
| 121 |
+
self.assertIsNone(f.newlines)
|
| 122 |
+
self.assertEqual(f.name, '<stdin>')
|
| 123 |
+
self.assertFalse(f.closed)
|
| 124 |
+
self.assertTrue(f.isatty())
|
| 125 |
+
self.assertTrue(f.readable())
|
| 126 |
+
self.assertFalse(f.writable())
|
| 127 |
+
self.assertFalse(f.seekable())
|
| 128 |
+
|
| 129 |
+
def test_unsupported(self):
|
| 130 |
+
shell = MockShell()
|
| 131 |
+
f = run.StdInputFile(shell, 'stdin')
|
| 132 |
+
self.assertRaises(OSError, f.fileno)
|
| 133 |
+
self.assertRaises(OSError, f.tell)
|
| 134 |
+
self.assertRaises(OSError, f.seek, 0)
|
| 135 |
+
self.assertRaises(OSError, f.write, 'x')
|
| 136 |
+
self.assertRaises(OSError, f.writelines, ['x'])
|
| 137 |
+
|
| 138 |
+
def test_read(self):
|
| 139 |
+
shell = MockShell()
|
| 140 |
+
f = run.StdInputFile(shell, 'stdin')
|
| 141 |
+
shell.push(['one\n', 'two\n', ''])
|
| 142 |
+
self.assertEqual(f.read(), 'one\ntwo\n')
|
| 143 |
+
shell.push(['one\n', 'two\n', ''])
|
| 144 |
+
self.assertEqual(f.read(-1), 'one\ntwo\n')
|
| 145 |
+
shell.push(['one\n', 'two\n', ''])
|
| 146 |
+
self.assertEqual(f.read(None), 'one\ntwo\n')
|
| 147 |
+
shell.push(['one\n', 'two\n', 'three\n', ''])
|
| 148 |
+
self.assertEqual(f.read(2), 'on')
|
| 149 |
+
self.assertEqual(f.read(3), 'e\nt')
|
| 150 |
+
self.assertEqual(f.read(10), 'wo\nthree\n')
|
| 151 |
+
|
| 152 |
+
shell.push(['one\n', 'two\n'])
|
| 153 |
+
self.assertEqual(f.read(0), '')
|
| 154 |
+
self.assertRaises(TypeError, f.read, 1.5)
|
| 155 |
+
self.assertRaises(TypeError, f.read, '1')
|
| 156 |
+
self.assertRaises(TypeError, f.read, 1, 1)
|
| 157 |
+
|
| 158 |
+
def test_readline(self):
|
| 159 |
+
shell = MockShell()
|
| 160 |
+
f = run.StdInputFile(shell, 'stdin')
|
| 161 |
+
shell.push(['one\n', 'two\n', 'three\n', 'four\n'])
|
| 162 |
+
self.assertEqual(f.readline(), 'one\n')
|
| 163 |
+
self.assertEqual(f.readline(-1), 'two\n')
|
| 164 |
+
self.assertEqual(f.readline(None), 'three\n')
|
| 165 |
+
shell.push(['one\ntwo\n'])
|
| 166 |
+
self.assertEqual(f.readline(), 'one\n')
|
| 167 |
+
self.assertEqual(f.readline(), 'two\n')
|
| 168 |
+
shell.push(['one', 'two', 'three'])
|
| 169 |
+
self.assertEqual(f.readline(), 'one')
|
| 170 |
+
self.assertEqual(f.readline(), 'two')
|
| 171 |
+
shell.push(['one\n', 'two\n', 'three\n'])
|
| 172 |
+
self.assertEqual(f.readline(2), 'on')
|
| 173 |
+
self.assertEqual(f.readline(1), 'e')
|
| 174 |
+
self.assertEqual(f.readline(1), '\n')
|
| 175 |
+
self.assertEqual(f.readline(10), 'two\n')
|
| 176 |
+
|
| 177 |
+
shell.push(['one\n', 'two\n'])
|
| 178 |
+
self.assertEqual(f.readline(0), '')
|
| 179 |
+
self.assertRaises(TypeError, f.readlines, 1.5)
|
| 180 |
+
self.assertRaises(TypeError, f.readlines, '1')
|
| 181 |
+
self.assertRaises(TypeError, f.readlines, 1, 1)
|
| 182 |
+
|
| 183 |
+
def test_readlines(self):
|
| 184 |
+
shell = MockShell()
|
| 185 |
+
f = run.StdInputFile(shell, 'stdin')
|
| 186 |
+
shell.push(['one\n', 'two\n', ''])
|
| 187 |
+
self.assertEqual(f.readlines(), ['one\n', 'two\n'])
|
| 188 |
+
shell.push(['one\n', 'two\n', ''])
|
| 189 |
+
self.assertEqual(f.readlines(-1), ['one\n', 'two\n'])
|
| 190 |
+
shell.push(['one\n', 'two\n', ''])
|
| 191 |
+
self.assertEqual(f.readlines(None), ['one\n', 'two\n'])
|
| 192 |
+
shell.push(['one\n', 'two\n', ''])
|
| 193 |
+
self.assertEqual(f.readlines(0), ['one\n', 'two\n'])
|
| 194 |
+
shell.push(['one\n', 'two\n', ''])
|
| 195 |
+
self.assertEqual(f.readlines(3), ['one\n'])
|
| 196 |
+
shell.push(['one\n', 'two\n', ''])
|
| 197 |
+
self.assertEqual(f.readlines(4), ['one\n', 'two\n'])
|
| 198 |
+
|
| 199 |
+
shell.push(['one\n', 'two\n', ''])
|
| 200 |
+
self.assertRaises(TypeError, f.readlines, 1.5)
|
| 201 |
+
self.assertRaises(TypeError, f.readlines, '1')
|
| 202 |
+
self.assertRaises(TypeError, f.readlines, 1, 1)
|
| 203 |
+
|
| 204 |
+
def test_close(self):
|
| 205 |
+
shell = MockShell()
|
| 206 |
+
f = run.StdInputFile(shell, 'stdin')
|
| 207 |
+
shell.push(['one\n', 'two\n', ''])
|
| 208 |
+
self.assertFalse(f.closed)
|
| 209 |
+
self.assertEqual(f.readline(), 'one\n')
|
| 210 |
+
f.close()
|
| 211 |
+
self.assertFalse(f.closed)
|
| 212 |
+
self.assertEqual(f.readline(), 'two\n')
|
| 213 |
+
self.assertRaises(TypeError, f.close, 1)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class StdOutputFilesTest(unittest.TestCase):
|
| 217 |
+
|
| 218 |
+
def test_misc(self):
|
| 219 |
+
shell = MockShell()
|
| 220 |
+
f = run.StdOutputFile(shell, 'stdout')
|
| 221 |
+
self.assertIsInstance(f, io.TextIOBase)
|
| 222 |
+
self.assertEqual(f.encoding, 'utf-8')
|
| 223 |
+
self.assertEqual(f.errors, 'strict')
|
| 224 |
+
self.assertIsNone(f.newlines)
|
| 225 |
+
self.assertEqual(f.name, '<stdout>')
|
| 226 |
+
self.assertFalse(f.closed)
|
| 227 |
+
self.assertTrue(f.isatty())
|
| 228 |
+
self.assertFalse(f.readable())
|
| 229 |
+
self.assertTrue(f.writable())
|
| 230 |
+
self.assertFalse(f.seekable())
|
| 231 |
+
|
| 232 |
+
def test_unsupported(self):
|
| 233 |
+
shell = MockShell()
|
| 234 |
+
f = run.StdOutputFile(shell, 'stdout')
|
| 235 |
+
self.assertRaises(OSError, f.fileno)
|
| 236 |
+
self.assertRaises(OSError, f.tell)
|
| 237 |
+
self.assertRaises(OSError, f.seek, 0)
|
| 238 |
+
self.assertRaises(OSError, f.read, 0)
|
| 239 |
+
self.assertRaises(OSError, f.readline, 0)
|
| 240 |
+
|
| 241 |
+
def test_write(self):
|
| 242 |
+
shell = MockShell()
|
| 243 |
+
f = run.StdOutputFile(shell, 'stdout')
|
| 244 |
+
f.write('test')
|
| 245 |
+
self.assertEqual(shell.written, [('test', 'stdout')])
|
| 246 |
+
shell.reset()
|
| 247 |
+
f.write('t\xe8\u015b\U0001d599')
|
| 248 |
+
self.assertEqual(shell.written, [('t\xe8\u015b\U0001d599', 'stdout')])
|
| 249 |
+
shell.reset()
|
| 250 |
+
|
| 251 |
+
f.write(S('t\xe8\u015b\U0001d599'))
|
| 252 |
+
self.assertEqual(shell.written, [('t\xe8\u015b\U0001d599', 'stdout')])
|
| 253 |
+
self.assertEqual(type(shell.written[0][0]), str)
|
| 254 |
+
shell.reset()
|
| 255 |
+
|
| 256 |
+
self.assertRaises(TypeError, f.write)
|
| 257 |
+
self.assertEqual(shell.written, [])
|
| 258 |
+
self.assertRaises(TypeError, f.write, b'test')
|
| 259 |
+
self.assertRaises(TypeError, f.write, 123)
|
| 260 |
+
self.assertEqual(shell.written, [])
|
| 261 |
+
self.assertRaises(TypeError, f.write, 'test', 'spam')
|
| 262 |
+
self.assertEqual(shell.written, [])
|
| 263 |
+
|
| 264 |
+
def test_write_stderr_nonencodable(self):
|
| 265 |
+
shell = MockShell()
|
| 266 |
+
f = run.StdOutputFile(shell, 'stderr', 'iso-8859-15', 'backslashreplace')
|
| 267 |
+
f.write('t\xe8\u015b\U0001d599\xa4')
|
| 268 |
+
self.assertEqual(shell.written, [('t\xe8\\u015b\\U0001d599\\xa4', 'stderr')])
|
| 269 |
+
shell.reset()
|
| 270 |
+
|
| 271 |
+
f.write(S('t\xe8\u015b\U0001d599\xa4'))
|
| 272 |
+
self.assertEqual(shell.written, [('t\xe8\\u015b\\U0001d599\\xa4', 'stderr')])
|
| 273 |
+
self.assertEqual(type(shell.written[0][0]), str)
|
| 274 |
+
shell.reset()
|
| 275 |
+
|
| 276 |
+
self.assertRaises(TypeError, f.write)
|
| 277 |
+
self.assertEqual(shell.written, [])
|
| 278 |
+
self.assertRaises(TypeError, f.write, b'test')
|
| 279 |
+
self.assertRaises(TypeError, f.write, 123)
|
| 280 |
+
self.assertEqual(shell.written, [])
|
| 281 |
+
self.assertRaises(TypeError, f.write, 'test', 'spam')
|
| 282 |
+
self.assertEqual(shell.written, [])
|
| 283 |
+
|
| 284 |
+
def test_writelines(self):
|
| 285 |
+
shell = MockShell()
|
| 286 |
+
f = run.StdOutputFile(shell, 'stdout')
|
| 287 |
+
f.writelines([])
|
| 288 |
+
self.assertEqual(shell.written, [])
|
| 289 |
+
shell.reset()
|
| 290 |
+
f.writelines(['one\n', 'two'])
|
| 291 |
+
self.assertEqual(shell.written,
|
| 292 |
+
[('one\n', 'stdout'), ('two', 'stdout')])
|
| 293 |
+
shell.reset()
|
| 294 |
+
f.writelines(['on\xe8\n', 'tw\xf2'])
|
| 295 |
+
self.assertEqual(shell.written,
|
| 296 |
+
[('on\xe8\n', 'stdout'), ('tw\xf2', 'stdout')])
|
| 297 |
+
shell.reset()
|
| 298 |
+
|
| 299 |
+
f.writelines([S('t\xe8st')])
|
| 300 |
+
self.assertEqual(shell.written, [('t\xe8st', 'stdout')])
|
| 301 |
+
self.assertEqual(type(shell.written[0][0]), str)
|
| 302 |
+
shell.reset()
|
| 303 |
+
|
| 304 |
+
self.assertRaises(TypeError, f.writelines)
|
| 305 |
+
self.assertEqual(shell.written, [])
|
| 306 |
+
self.assertRaises(TypeError, f.writelines, 123)
|
| 307 |
+
self.assertEqual(shell.written, [])
|
| 308 |
+
self.assertRaises(TypeError, f.writelines, [b'test'])
|
| 309 |
+
self.assertRaises(TypeError, f.writelines, [123])
|
| 310 |
+
self.assertEqual(shell.written, [])
|
| 311 |
+
self.assertRaises(TypeError, f.writelines, [], [])
|
| 312 |
+
self.assertEqual(shell.written, [])
|
| 313 |
+
|
| 314 |
+
def test_close(self):
|
| 315 |
+
shell = MockShell()
|
| 316 |
+
f = run.StdOutputFile(shell, 'stdout')
|
| 317 |
+
self.assertFalse(f.closed)
|
| 318 |
+
f.write('test')
|
| 319 |
+
f.close()
|
| 320 |
+
self.assertTrue(f.closed)
|
| 321 |
+
self.assertRaises(ValueError, f.write, 'x')
|
| 322 |
+
self.assertEqual(shell.written, [('test', 'stdout')])
|
| 323 |
+
f.close()
|
| 324 |
+
self.assertRaises(TypeError, f.close, 1)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class RecursionLimitTest(unittest.TestCase):
|
| 328 |
+
# Test (un)install_recursionlimit_wrappers and fixdoc.
|
| 329 |
+
|
| 330 |
+
def test_bad_setrecursionlimit_calls(self):
|
| 331 |
+
run.install_recursionlimit_wrappers()
|
| 332 |
+
self.addCleanup(run.uninstall_recursionlimit_wrappers)
|
| 333 |
+
f = sys.setrecursionlimit
|
| 334 |
+
self.assertRaises(TypeError, f, limit=100)
|
| 335 |
+
self.assertRaises(TypeError, f, 100, 1000)
|
| 336 |
+
self.assertRaises(ValueError, f, 0)
|
| 337 |
+
|
| 338 |
+
def test_roundtrip(self):
|
| 339 |
+
run.install_recursionlimit_wrappers()
|
| 340 |
+
self.addCleanup(run.uninstall_recursionlimit_wrappers)
|
| 341 |
+
|
| 342 |
+
# Check that setting the recursion limit works.
|
| 343 |
+
orig_reclimit = sys.getrecursionlimit()
|
| 344 |
+
self.addCleanup(sys.setrecursionlimit, orig_reclimit)
|
| 345 |
+
sys.setrecursionlimit(orig_reclimit + 3)
|
| 346 |
+
|
| 347 |
+
# Check that the new limit is returned by sys.getrecursionlimit().
|
| 348 |
+
new_reclimit = sys.getrecursionlimit()
|
| 349 |
+
self.assertEqual(new_reclimit, orig_reclimit + 3)
|
| 350 |
+
|
| 351 |
+
def test_default_recursion_limit_preserved(self):
|
| 352 |
+
orig_reclimit = sys.getrecursionlimit()
|
| 353 |
+
run.install_recursionlimit_wrappers()
|
| 354 |
+
self.addCleanup(run.uninstall_recursionlimit_wrappers)
|
| 355 |
+
new_reclimit = sys.getrecursionlimit()
|
| 356 |
+
self.assertEqual(new_reclimit, orig_reclimit)
|
| 357 |
+
|
| 358 |
+
def test_fixdoc(self):
|
| 359 |
+
# Put here until better place for miscellaneous test.
|
| 360 |
+
def func(): "docstring"
|
| 361 |
+
run.fixdoc(func, "more")
|
| 362 |
+
self.assertEqual(func.__doc__, "docstring\n\nmore")
|
| 363 |
+
func.__doc__ = None
|
| 364 |
+
run.fixdoc(func, "more")
|
| 365 |
+
self.assertEqual(func.__doc__, "more")
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
class HandleErrorTest(unittest.TestCase):
|
| 369 |
+
# Method of MyRPCServer
|
| 370 |
+
def test_fatal_error(self):
|
| 371 |
+
eq = self.assertEqual
|
| 372 |
+
with captured_output('__stderr__') as err,\
|
| 373 |
+
mock.patch('idlelib.run.thread.interrupt_main',
|
| 374 |
+
new_callable=Func) as func:
|
| 375 |
+
try:
|
| 376 |
+
raise EOFError
|
| 377 |
+
except EOFError:
|
| 378 |
+
run.MyRPCServer.handle_error(None, 'abc', '123')
|
| 379 |
+
eq(run.exit_now, True)
|
| 380 |
+
run.exit_now = False
|
| 381 |
+
eq(err.getvalue(), '')
|
| 382 |
+
|
| 383 |
+
try:
|
| 384 |
+
raise IndexError
|
| 385 |
+
except IndexError:
|
| 386 |
+
run.MyRPCServer.handle_error(None, 'abc', '123')
|
| 387 |
+
eq(run.quitting, True)
|
| 388 |
+
run.quitting = False
|
| 389 |
+
msg = err.getvalue()
|
| 390 |
+
self.assertIn('abc', msg)
|
| 391 |
+
self.assertIn('123', msg)
|
| 392 |
+
self.assertIn('IndexError', msg)
|
| 393 |
+
eq(func.called, 2)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
class ExecRuncodeTest(unittest.TestCase):
|
| 397 |
+
|
| 398 |
+
@classmethod
|
| 399 |
+
def setUpClass(cls):
|
| 400 |
+
cls.addClassCleanup(setattr,run,'print_exception',run.print_exception)
|
| 401 |
+
cls.prt = Func() # Need reference.
|
| 402 |
+
run.print_exception = cls.prt
|
| 403 |
+
mockrpc = mock.Mock()
|
| 404 |
+
mockrpc.console.getvar = Func(result=False)
|
| 405 |
+
cls.ex = run.Executive(mockrpc)
|
| 406 |
+
|
| 407 |
+
@classmethod
|
| 408 |
+
def tearDownClass(cls):
|
| 409 |
+
assert sys.excepthook == sys.__excepthook__
|
| 410 |
+
|
| 411 |
+
def test_exceptions(self):
|
| 412 |
+
ex = self.ex
|
| 413 |
+
ex.runcode('1/0')
|
| 414 |
+
self.assertIs(ex.user_exc_info[0], ZeroDivisionError)
|
| 415 |
+
|
| 416 |
+
self.addCleanup(setattr, sys, 'excepthook', sys.__excepthook__)
|
| 417 |
+
sys.excepthook = lambda t, e, tb: run.print_exception(t)
|
| 418 |
+
ex.runcode('1/0')
|
| 419 |
+
self.assertIs(self.prt.args[0], ZeroDivisionError)
|
| 420 |
+
|
| 421 |
+
sys.excepthook = lambda: None
|
| 422 |
+
ex.runcode('1/0')
|
| 423 |
+
t, e, tb = ex.user_exc_info
|
| 424 |
+
self.assertIs(t, TypeError)
|
| 425 |
+
self.assertTrue(isinstance(e.__context__, ZeroDivisionError))
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
if __name__ == '__main__':
|
| 429 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_search.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test search, coverage 69%."
|
| 2 |
+
|
| 3 |
+
from idlelib import search
|
| 4 |
+
import unittest
|
| 5 |
+
from test.support import requires
|
| 6 |
+
requires('gui')
|
| 7 |
+
from tkinter import Tk, Text, BooleanVar
|
| 8 |
+
from idlelib import searchengine
|
| 9 |
+
|
| 10 |
+
# Does not currently test the event handler wrappers.
|
| 11 |
+
# A usage test should simulate clicks and check highlighting.
|
| 12 |
+
# Tests need to be coordinated with SearchDialogBase tests
|
| 13 |
+
# to avoid duplication.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class SearchDialogTest(unittest.TestCase):
|
| 17 |
+
|
| 18 |
+
@classmethod
|
| 19 |
+
def setUpClass(cls):
|
| 20 |
+
cls.root = Tk()
|
| 21 |
+
|
| 22 |
+
@classmethod
|
| 23 |
+
def tearDownClass(cls):
|
| 24 |
+
cls.root.destroy()
|
| 25 |
+
del cls.root
|
| 26 |
+
|
| 27 |
+
def setUp(self):
|
| 28 |
+
self.engine = searchengine.SearchEngine(self.root)
|
| 29 |
+
self.dialog = search.SearchDialog(self.root, self.engine)
|
| 30 |
+
self.dialog.bell = lambda: None
|
| 31 |
+
self.text = Text(self.root)
|
| 32 |
+
self.text.insert('1.0', 'Hello World!')
|
| 33 |
+
|
| 34 |
+
def test_find_again(self):
|
| 35 |
+
# Search for various expressions
|
| 36 |
+
text = self.text
|
| 37 |
+
|
| 38 |
+
self.engine.setpat('')
|
| 39 |
+
self.assertFalse(self.dialog.find_again(text))
|
| 40 |
+
self.dialog.bell = lambda: None
|
| 41 |
+
|
| 42 |
+
self.engine.setpat('Hello')
|
| 43 |
+
self.assertTrue(self.dialog.find_again(text))
|
| 44 |
+
|
| 45 |
+
self.engine.setpat('Goodbye')
|
| 46 |
+
self.assertFalse(self.dialog.find_again(text))
|
| 47 |
+
|
| 48 |
+
self.engine.setpat('World!')
|
| 49 |
+
self.assertTrue(self.dialog.find_again(text))
|
| 50 |
+
|
| 51 |
+
self.engine.setpat('Hello World!')
|
| 52 |
+
self.assertTrue(self.dialog.find_again(text))
|
| 53 |
+
|
| 54 |
+
# Regular expression
|
| 55 |
+
self.engine.revar = BooleanVar(self.root, True)
|
| 56 |
+
self.engine.setpat('W[aeiouy]r')
|
| 57 |
+
self.assertTrue(self.dialog.find_again(text))
|
| 58 |
+
|
| 59 |
+
def test_find_selection(self):
|
| 60 |
+
# Select some text and make sure it's found
|
| 61 |
+
text = self.text
|
| 62 |
+
# Add additional line to find
|
| 63 |
+
self.text.insert('2.0', 'Hello World!')
|
| 64 |
+
|
| 65 |
+
text.tag_add('sel', '1.0', '1.4') # Select 'Hello'
|
| 66 |
+
self.assertTrue(self.dialog.find_selection(text))
|
| 67 |
+
|
| 68 |
+
text.tag_remove('sel', '1.0', 'end')
|
| 69 |
+
text.tag_add('sel', '1.6', '1.11') # Select 'World!'
|
| 70 |
+
self.assertTrue(self.dialog.find_selection(text))
|
| 71 |
+
|
| 72 |
+
text.tag_remove('sel', '1.0', 'end')
|
| 73 |
+
text.tag_add('sel', '1.0', '1.11') # Select 'Hello World!'
|
| 74 |
+
self.assertTrue(self.dialog.find_selection(text))
|
| 75 |
+
|
| 76 |
+
# Remove additional line
|
| 77 |
+
text.delete('2.0', 'end')
|
| 78 |
+
|
| 79 |
+
if __name__ == '__main__':
|
| 80 |
+
unittest.main(verbosity=2, exit=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_searchbase.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 4 |
+
|
| 5 |
+
import unittest
|
| 6 |
+
from test.support import requires
|
| 7 |
+
from tkinter import Text, Tk, Toplevel
|
| 8 |
+
from tkinter.ttk import Frame
|
| 9 |
+
from idlelib import searchengine as se
|
| 10 |
+
from idlelib import searchbase as sdb
|
| 11 |
+
from idlelib.idle_test.mock_idle import Func
|
| 12 |
+
## from idlelib.idle_test.mock_tk import Var
|
| 13 |
+
|
| 14 |
+
# The ## imports above & following could help make some tests gui-free.
|
| 15 |
+
# However, they currently make radiobutton tests fail.
|
| 16 |
+
##def setUpModule():
|
| 17 |
+
## # Replace tk objects used to initialize se.SearchEngine.
|
| 18 |
+
## se.BooleanVar = Var
|
| 19 |
+
## se.StringVar = Var
|
| 20 |
+
##
|
| 21 |
+
##def tearDownModule():
|
| 22 |
+
## se.BooleanVar = BooleanVar
|
| 23 |
+
## se.StringVar = StringVar
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class SearchDialogBaseTest(unittest.TestCase):
|
| 27 |
+
|
| 28 |
+
@classmethod
|
| 29 |
+
def setUpClass(cls):
|
| 30 |
+
requires('gui')
|
| 31 |
+
cls.root = Tk()
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def tearDownClass(cls):
|
| 35 |
+
cls.root.update_idletasks()
|
| 36 |
+
cls.root.destroy()
|
| 37 |
+
del cls.root
|
| 38 |
+
|
| 39 |
+
def setUp(self):
|
| 40 |
+
self.engine = se.SearchEngine(self.root) # None also seems to work
|
| 41 |
+
self.dialog = sdb.SearchDialogBase(root=self.root, engine=self.engine)
|
| 42 |
+
|
| 43 |
+
def tearDown(self):
|
| 44 |
+
self.dialog.close()
|
| 45 |
+
|
| 46 |
+
def test_open_and_close(self):
|
| 47 |
+
# open calls create_widgets, which needs default_command
|
| 48 |
+
self.dialog.default_command = None
|
| 49 |
+
|
| 50 |
+
toplevel = Toplevel(self.root)
|
| 51 |
+
text = Text(toplevel)
|
| 52 |
+
self.dialog.open(text)
|
| 53 |
+
self.assertEqual(self.dialog.top.state(), 'normal')
|
| 54 |
+
self.dialog.close()
|
| 55 |
+
self.assertEqual(self.dialog.top.state(), 'withdrawn')
|
| 56 |
+
|
| 57 |
+
self.dialog.open(text, searchphrase="hello")
|
| 58 |
+
self.assertEqual(self.dialog.ent.get(), 'hello')
|
| 59 |
+
toplevel.update_idletasks()
|
| 60 |
+
toplevel.destroy()
|
| 61 |
+
|
| 62 |
+
def test_create_widgets(self):
|
| 63 |
+
self.dialog.create_entries = Func()
|
| 64 |
+
self.dialog.create_option_buttons = Func()
|
| 65 |
+
self.dialog.create_other_buttons = Func()
|
| 66 |
+
self.dialog.create_command_buttons = Func()
|
| 67 |
+
|
| 68 |
+
self.dialog.default_command = None
|
| 69 |
+
self.dialog.create_widgets()
|
| 70 |
+
|
| 71 |
+
self.assertTrue(self.dialog.create_entries.called)
|
| 72 |
+
self.assertTrue(self.dialog.create_option_buttons.called)
|
| 73 |
+
self.assertTrue(self.dialog.create_other_buttons.called)
|
| 74 |
+
self.assertTrue(self.dialog.create_command_buttons.called)
|
| 75 |
+
|
| 76 |
+
def test_make_entry(self):
|
| 77 |
+
equal = self.assertEqual
|
| 78 |
+
self.dialog.row = 0
|
| 79 |
+
self.dialog.frame = Frame(self.root)
|
| 80 |
+
entry, label = self.dialog.make_entry("Test:", 'hello')
|
| 81 |
+
equal(label['text'], 'Test:')
|
| 82 |
+
|
| 83 |
+
self.assertIn(entry.get(), 'hello')
|
| 84 |
+
egi = entry.grid_info()
|
| 85 |
+
equal(int(egi['row']), 0)
|
| 86 |
+
equal(int(egi['column']), 1)
|
| 87 |
+
equal(int(egi['rowspan']), 1)
|
| 88 |
+
equal(int(egi['columnspan']), 1)
|
| 89 |
+
equal(self.dialog.row, 1)
|
| 90 |
+
|
| 91 |
+
def test_create_entries(self):
|
| 92 |
+
self.dialog.frame = Frame(self.root)
|
| 93 |
+
self.dialog.row = 0
|
| 94 |
+
self.engine.setpat('hello')
|
| 95 |
+
self.dialog.create_entries()
|
| 96 |
+
self.assertIn(self.dialog.ent.get(), 'hello')
|
| 97 |
+
|
| 98 |
+
def test_make_frame(self):
|
| 99 |
+
self.dialog.row = 0
|
| 100 |
+
self.dialog.frame = Frame(self.root)
|
| 101 |
+
frame, label = self.dialog.make_frame()
|
| 102 |
+
self.assertEqual(label, '')
|
| 103 |
+
self.assertEqual(str(type(frame)), "<class 'tkinter.ttk.Frame'>")
|
| 104 |
+
# self.assertIsInstance(frame, Frame) fails when test is run by
|
| 105 |
+
# test_idle not run from IDLE editor. See issue 33987 PR.
|
| 106 |
+
|
| 107 |
+
frame, label = self.dialog.make_frame('testlabel')
|
| 108 |
+
self.assertEqual(label['text'], 'testlabel')
|
| 109 |
+
|
| 110 |
+
def btn_test_setup(self, meth):
|
| 111 |
+
self.dialog.frame = Frame(self.root)
|
| 112 |
+
self.dialog.row = 0
|
| 113 |
+
return meth()
|
| 114 |
+
|
| 115 |
+
def test_create_option_buttons(self):
|
| 116 |
+
e = self.engine
|
| 117 |
+
for state in (0, 1):
|
| 118 |
+
for var in (e.revar, e.casevar, e.wordvar, e.wrapvar):
|
| 119 |
+
var.set(state)
|
| 120 |
+
frame, options = self.btn_test_setup(
|
| 121 |
+
self.dialog.create_option_buttons)
|
| 122 |
+
for spec, button in zip (options, frame.pack_slaves()):
|
| 123 |
+
var, label = spec
|
| 124 |
+
self.assertEqual(button['text'], label)
|
| 125 |
+
self.assertEqual(var.get(), state)
|
| 126 |
+
|
| 127 |
+
def test_create_other_buttons(self):
|
| 128 |
+
for state in (False, True):
|
| 129 |
+
var = self.engine.backvar
|
| 130 |
+
var.set(state)
|
| 131 |
+
frame, others = self.btn_test_setup(
|
| 132 |
+
self.dialog.create_other_buttons)
|
| 133 |
+
buttons = frame.pack_slaves()
|
| 134 |
+
for spec, button in zip(others, buttons):
|
| 135 |
+
val, label = spec
|
| 136 |
+
self.assertEqual(button['text'], label)
|
| 137 |
+
if val == state:
|
| 138 |
+
# hit other button, then this one
|
| 139 |
+
# indexes depend on button order
|
| 140 |
+
self.assertEqual(var.get(), state)
|
| 141 |
+
|
| 142 |
+
def test_make_button(self):
|
| 143 |
+
self.dialog.frame = Frame(self.root)
|
| 144 |
+
self.dialog.buttonframe = Frame(self.dialog.frame)
|
| 145 |
+
btn = self.dialog.make_button('Test', self.dialog.close)
|
| 146 |
+
self.assertEqual(btn['text'], 'Test')
|
| 147 |
+
|
| 148 |
+
def test_create_command_buttons(self):
|
| 149 |
+
self.dialog.frame = Frame(self.root)
|
| 150 |
+
self.dialog.create_command_buttons()
|
| 151 |
+
# Look for close button command in buttonframe
|
| 152 |
+
closebuttoncommand = ''
|
| 153 |
+
for child in self.dialog.buttonframe.winfo_children():
|
| 154 |
+
if child['text'] == 'Close':
|
| 155 |
+
closebuttoncommand = child['command']
|
| 156 |
+
self.assertIn('close', closebuttoncommand)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
if __name__ == '__main__':
|
| 160 |
+
unittest.main(verbosity=2, exit=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_sidebar.py
ADDED
|
@@ -0,0 +1,768 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test sidebar, coverage 85%"""
|
| 2 |
+
from textwrap import dedent
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
from itertools import chain
|
| 6 |
+
import unittest
|
| 7 |
+
import unittest.mock
|
| 8 |
+
from test.support import requires, swap_attr
|
| 9 |
+
from test import support
|
| 10 |
+
import tkinter as tk
|
| 11 |
+
from idlelib.idle_test.tkinter_testing_utils import run_in_tk_mainloop
|
| 12 |
+
|
| 13 |
+
from idlelib.delegator import Delegator
|
| 14 |
+
from idlelib.editor import fixwordbreaks
|
| 15 |
+
from idlelib.percolator import Percolator
|
| 16 |
+
import idlelib.pyshell
|
| 17 |
+
from idlelib.pyshell import fix_x11_paste, PyShell, PyShellFileList
|
| 18 |
+
from idlelib.run import fix_scaling
|
| 19 |
+
import idlelib.sidebar
|
| 20 |
+
from idlelib.sidebar import get_end_linenumber, get_lineno
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Dummy_editwin:
|
| 24 |
+
def __init__(self, text):
|
| 25 |
+
self.text = text
|
| 26 |
+
self.text_frame = self.text.master
|
| 27 |
+
self.per = Percolator(text)
|
| 28 |
+
self.undo = Delegator()
|
| 29 |
+
self.per.insertfilter(self.undo)
|
| 30 |
+
|
| 31 |
+
def setvar(self, name, value):
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
+
def getlineno(self, index):
|
| 35 |
+
return int(float(self.text.index(index)))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class LineNumbersTest(unittest.TestCase):
|
| 39 |
+
|
| 40 |
+
@classmethod
|
| 41 |
+
def setUpClass(cls):
|
| 42 |
+
requires('gui')
|
| 43 |
+
cls.root = tk.Tk()
|
| 44 |
+
cls.root.withdraw()
|
| 45 |
+
|
| 46 |
+
cls.text_frame = tk.Frame(cls.root)
|
| 47 |
+
cls.text_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
|
| 48 |
+
cls.text_frame.rowconfigure(1, weight=1)
|
| 49 |
+
cls.text_frame.columnconfigure(1, weight=1)
|
| 50 |
+
|
| 51 |
+
cls.text = tk.Text(cls.text_frame, width=80, height=24, wrap=tk.NONE)
|
| 52 |
+
cls.text.grid(row=1, column=1, sticky=tk.NSEW)
|
| 53 |
+
|
| 54 |
+
cls.editwin = Dummy_editwin(cls.text)
|
| 55 |
+
cls.editwin.vbar = tk.Scrollbar(cls.text_frame)
|
| 56 |
+
|
| 57 |
+
@classmethod
|
| 58 |
+
def tearDownClass(cls):
|
| 59 |
+
cls.editwin.per.close()
|
| 60 |
+
cls.root.update()
|
| 61 |
+
cls.root.destroy()
|
| 62 |
+
del cls.text, cls.text_frame, cls.editwin, cls.root
|
| 63 |
+
|
| 64 |
+
def setUp(self):
|
| 65 |
+
self.linenumber = idlelib.sidebar.LineNumbers(self.editwin)
|
| 66 |
+
|
| 67 |
+
self.highlight_cfg = {"background": '#abcdef',
|
| 68 |
+
"foreground": '#123456'}
|
| 69 |
+
orig_idleConf_GetHighlight = idlelib.sidebar.idleConf.GetHighlight
|
| 70 |
+
def mock_idleconf_GetHighlight(theme, element):
|
| 71 |
+
if element == 'linenumber':
|
| 72 |
+
return self.highlight_cfg
|
| 73 |
+
return orig_idleConf_GetHighlight(theme, element)
|
| 74 |
+
GetHighlight_patcher = unittest.mock.patch.object(
|
| 75 |
+
idlelib.sidebar.idleConf, 'GetHighlight', mock_idleconf_GetHighlight)
|
| 76 |
+
GetHighlight_patcher.start()
|
| 77 |
+
self.addCleanup(GetHighlight_patcher.stop)
|
| 78 |
+
|
| 79 |
+
self.font_override = 'TkFixedFont'
|
| 80 |
+
def mock_idleconf_GetFont(root, configType, section):
|
| 81 |
+
return self.font_override
|
| 82 |
+
GetFont_patcher = unittest.mock.patch.object(
|
| 83 |
+
idlelib.sidebar.idleConf, 'GetFont', mock_idleconf_GetFont)
|
| 84 |
+
GetFont_patcher.start()
|
| 85 |
+
self.addCleanup(GetFont_patcher.stop)
|
| 86 |
+
|
| 87 |
+
def tearDown(self):
|
| 88 |
+
self.text.delete('1.0', 'end')
|
| 89 |
+
|
| 90 |
+
def get_selection(self):
|
| 91 |
+
return tuple(map(str, self.text.tag_ranges('sel')))
|
| 92 |
+
|
| 93 |
+
def get_line_screen_position(self, line):
|
| 94 |
+
bbox = self.linenumber.sidebar_text.bbox(f'{line}.end -1c')
|
| 95 |
+
x = bbox[0] + 2
|
| 96 |
+
y = bbox[1] + 2
|
| 97 |
+
return x, y
|
| 98 |
+
|
| 99 |
+
def assert_state_disabled(self):
|
| 100 |
+
state = self.linenumber.sidebar_text.config()['state']
|
| 101 |
+
self.assertEqual(state[-1], tk.DISABLED)
|
| 102 |
+
|
| 103 |
+
def get_sidebar_text_contents(self):
|
| 104 |
+
return self.linenumber.sidebar_text.get('1.0', tk.END)
|
| 105 |
+
|
| 106 |
+
def assert_sidebar_n_lines(self, n_lines):
|
| 107 |
+
expected = '\n'.join(chain(map(str, range(1, n_lines + 1)), ['']))
|
| 108 |
+
self.assertEqual(self.get_sidebar_text_contents(), expected)
|
| 109 |
+
|
| 110 |
+
def assert_text_equals(self, expected):
|
| 111 |
+
return self.assertEqual(self.text.get('1.0', 'end'), expected)
|
| 112 |
+
|
| 113 |
+
def test_init_empty(self):
|
| 114 |
+
self.assert_sidebar_n_lines(1)
|
| 115 |
+
|
| 116 |
+
def test_init_not_empty(self):
|
| 117 |
+
self.text.insert('insert', 'foo bar\n'*3)
|
| 118 |
+
self.assert_text_equals('foo bar\n'*3 + '\n')
|
| 119 |
+
self.assert_sidebar_n_lines(4)
|
| 120 |
+
|
| 121 |
+
def test_toggle_linenumbering(self):
|
| 122 |
+
self.assertEqual(self.linenumber.is_shown, False)
|
| 123 |
+
self.linenumber.show_sidebar()
|
| 124 |
+
self.assertEqual(self.linenumber.is_shown, True)
|
| 125 |
+
self.linenumber.hide_sidebar()
|
| 126 |
+
self.assertEqual(self.linenumber.is_shown, False)
|
| 127 |
+
self.linenumber.hide_sidebar()
|
| 128 |
+
self.assertEqual(self.linenumber.is_shown, False)
|
| 129 |
+
self.linenumber.show_sidebar()
|
| 130 |
+
self.assertEqual(self.linenumber.is_shown, True)
|
| 131 |
+
self.linenumber.show_sidebar()
|
| 132 |
+
self.assertEqual(self.linenumber.is_shown, True)
|
| 133 |
+
|
| 134 |
+
def test_insert(self):
|
| 135 |
+
self.text.insert('insert', 'foobar')
|
| 136 |
+
self.assert_text_equals('foobar\n')
|
| 137 |
+
self.assert_sidebar_n_lines(1)
|
| 138 |
+
self.assert_state_disabled()
|
| 139 |
+
|
| 140 |
+
self.text.insert('insert', '\nfoo')
|
| 141 |
+
self.assert_text_equals('foobar\nfoo\n')
|
| 142 |
+
self.assert_sidebar_n_lines(2)
|
| 143 |
+
self.assert_state_disabled()
|
| 144 |
+
|
| 145 |
+
self.text.insert('insert', 'hello\n'*2)
|
| 146 |
+
self.assert_text_equals('foobar\nfoohello\nhello\n\n')
|
| 147 |
+
self.assert_sidebar_n_lines(4)
|
| 148 |
+
self.assert_state_disabled()
|
| 149 |
+
|
| 150 |
+
self.text.insert('insert', '\nworld')
|
| 151 |
+
self.assert_text_equals('foobar\nfoohello\nhello\n\nworld\n')
|
| 152 |
+
self.assert_sidebar_n_lines(5)
|
| 153 |
+
self.assert_state_disabled()
|
| 154 |
+
|
| 155 |
+
def test_delete(self):
|
| 156 |
+
self.text.insert('insert', 'foobar')
|
| 157 |
+
self.assert_text_equals('foobar\n')
|
| 158 |
+
self.text.delete('1.1', '1.3')
|
| 159 |
+
self.assert_text_equals('fbar\n')
|
| 160 |
+
self.assert_sidebar_n_lines(1)
|
| 161 |
+
self.assert_state_disabled()
|
| 162 |
+
|
| 163 |
+
self.text.insert('insert', 'foo\n'*2)
|
| 164 |
+
self.assert_text_equals('fbarfoo\nfoo\n\n')
|
| 165 |
+
self.assert_sidebar_n_lines(3)
|
| 166 |
+
self.assert_state_disabled()
|
| 167 |
+
|
| 168 |
+
# Deleting up to "2.end" doesn't delete the final newline.
|
| 169 |
+
self.text.delete('2.0', '2.end')
|
| 170 |
+
self.assert_text_equals('fbarfoo\n\n\n')
|
| 171 |
+
self.assert_sidebar_n_lines(3)
|
| 172 |
+
self.assert_state_disabled()
|
| 173 |
+
|
| 174 |
+
self.text.delete('1.3', 'end')
|
| 175 |
+
self.assert_text_equals('fba\n')
|
| 176 |
+
self.assert_sidebar_n_lines(1)
|
| 177 |
+
self.assert_state_disabled()
|
| 178 |
+
|
| 179 |
+
# Text widgets always keep a single '\n' character at the end.
|
| 180 |
+
self.text.delete('1.0', 'end')
|
| 181 |
+
self.assert_text_equals('\n')
|
| 182 |
+
self.assert_sidebar_n_lines(1)
|
| 183 |
+
self.assert_state_disabled()
|
| 184 |
+
|
| 185 |
+
def test_sidebar_text_width(self):
|
| 186 |
+
"""
|
| 187 |
+
Test that linenumber text widget is always at the minimum
|
| 188 |
+
width
|
| 189 |
+
"""
|
| 190 |
+
def get_width():
|
| 191 |
+
return self.linenumber.sidebar_text.config()['width'][-1]
|
| 192 |
+
|
| 193 |
+
self.assert_sidebar_n_lines(1)
|
| 194 |
+
self.assertEqual(get_width(), 1)
|
| 195 |
+
|
| 196 |
+
self.text.insert('insert', 'foo')
|
| 197 |
+
self.assert_sidebar_n_lines(1)
|
| 198 |
+
self.assertEqual(get_width(), 1)
|
| 199 |
+
|
| 200 |
+
self.text.insert('insert', 'foo\n'*8)
|
| 201 |
+
self.assert_sidebar_n_lines(9)
|
| 202 |
+
self.assertEqual(get_width(), 1)
|
| 203 |
+
|
| 204 |
+
self.text.insert('insert', 'foo\n')
|
| 205 |
+
self.assert_sidebar_n_lines(10)
|
| 206 |
+
self.assertEqual(get_width(), 2)
|
| 207 |
+
|
| 208 |
+
self.text.insert('insert', 'foo\n')
|
| 209 |
+
self.assert_sidebar_n_lines(11)
|
| 210 |
+
self.assertEqual(get_width(), 2)
|
| 211 |
+
|
| 212 |
+
self.text.delete('insert -1l linestart', 'insert linestart')
|
| 213 |
+
self.assert_sidebar_n_lines(10)
|
| 214 |
+
self.assertEqual(get_width(), 2)
|
| 215 |
+
|
| 216 |
+
self.text.delete('insert -1l linestart', 'insert linestart')
|
| 217 |
+
self.assert_sidebar_n_lines(9)
|
| 218 |
+
self.assertEqual(get_width(), 1)
|
| 219 |
+
|
| 220 |
+
self.text.insert('insert', 'foo\n'*90)
|
| 221 |
+
self.assert_sidebar_n_lines(99)
|
| 222 |
+
self.assertEqual(get_width(), 2)
|
| 223 |
+
|
| 224 |
+
self.text.insert('insert', 'foo\n')
|
| 225 |
+
self.assert_sidebar_n_lines(100)
|
| 226 |
+
self.assertEqual(get_width(), 3)
|
| 227 |
+
|
| 228 |
+
self.text.insert('insert', 'foo\n')
|
| 229 |
+
self.assert_sidebar_n_lines(101)
|
| 230 |
+
self.assertEqual(get_width(), 3)
|
| 231 |
+
|
| 232 |
+
self.text.delete('insert -1l linestart', 'insert linestart')
|
| 233 |
+
self.assert_sidebar_n_lines(100)
|
| 234 |
+
self.assertEqual(get_width(), 3)
|
| 235 |
+
|
| 236 |
+
self.text.delete('insert -1l linestart', 'insert linestart')
|
| 237 |
+
self.assert_sidebar_n_lines(99)
|
| 238 |
+
self.assertEqual(get_width(), 2)
|
| 239 |
+
|
| 240 |
+
self.text.delete('50.0 -1c', 'end -1c')
|
| 241 |
+
self.assert_sidebar_n_lines(49)
|
| 242 |
+
self.assertEqual(get_width(), 2)
|
| 243 |
+
|
| 244 |
+
self.text.delete('5.0 -1c', 'end -1c')
|
| 245 |
+
self.assert_sidebar_n_lines(4)
|
| 246 |
+
self.assertEqual(get_width(), 1)
|
| 247 |
+
|
| 248 |
+
# Text widgets always keep a single '\n' character at the end.
|
| 249 |
+
self.text.delete('1.0', 'end -1c')
|
| 250 |
+
self.assert_sidebar_n_lines(1)
|
| 251 |
+
self.assertEqual(get_width(), 1)
|
| 252 |
+
|
| 253 |
+
# The following tests are temporarily disabled due to relying on
|
| 254 |
+
# simulated user input and inspecting which text is selected, which
|
| 255 |
+
# are fragile and can fail when several GUI tests are run in parallel
|
| 256 |
+
# or when the windows created by the test lose focus.
|
| 257 |
+
#
|
| 258 |
+
# TODO: Re-work these tests or remove them from the test suite.
|
| 259 |
+
|
| 260 |
+
@unittest.skip('test disabled')
|
| 261 |
+
def test_click_selection(self):
|
| 262 |
+
self.linenumber.show_sidebar()
|
| 263 |
+
self.text.insert('1.0', 'one\ntwo\nthree\nfour\n')
|
| 264 |
+
self.root.update()
|
| 265 |
+
|
| 266 |
+
# Click on the second line.
|
| 267 |
+
x, y = self.get_line_screen_position(2)
|
| 268 |
+
self.linenumber.sidebar_text.event_generate('<Button-1>', x=x, y=y)
|
| 269 |
+
self.linenumber.sidebar_text.update()
|
| 270 |
+
self.root.update()
|
| 271 |
+
|
| 272 |
+
self.assertEqual(self.get_selection(), ('2.0', '3.0'))
|
| 273 |
+
|
| 274 |
+
def simulate_drag(self, start_line, end_line):
|
| 275 |
+
start_x, start_y = self.get_line_screen_position(start_line)
|
| 276 |
+
end_x, end_y = self.get_line_screen_position(end_line)
|
| 277 |
+
|
| 278 |
+
self.linenumber.sidebar_text.event_generate('<Button-1>',
|
| 279 |
+
x=start_x, y=start_y)
|
| 280 |
+
self.root.update()
|
| 281 |
+
|
| 282 |
+
def lerp(a, b, steps):
|
| 283 |
+
"""linearly interpolate from a to b (inclusive) in equal steps"""
|
| 284 |
+
last_step = steps - 1
|
| 285 |
+
for i in range(steps):
|
| 286 |
+
yield ((last_step - i) / last_step) * a + (i / last_step) * b
|
| 287 |
+
|
| 288 |
+
for x, y in zip(
|
| 289 |
+
map(int, lerp(start_x, end_x, steps=11)),
|
| 290 |
+
map(int, lerp(start_y, end_y, steps=11)),
|
| 291 |
+
):
|
| 292 |
+
self.linenumber.sidebar_text.event_generate('<B1-Motion>', x=x, y=y)
|
| 293 |
+
self.root.update()
|
| 294 |
+
|
| 295 |
+
self.linenumber.sidebar_text.event_generate('<ButtonRelease-1>',
|
| 296 |
+
x=end_x, y=end_y)
|
| 297 |
+
self.root.update()
|
| 298 |
+
|
| 299 |
+
@unittest.skip('test disabled')
|
| 300 |
+
def test_drag_selection_down(self):
|
| 301 |
+
self.linenumber.show_sidebar()
|
| 302 |
+
self.text.insert('1.0', 'one\ntwo\nthree\nfour\nfive\n')
|
| 303 |
+
self.root.update()
|
| 304 |
+
|
| 305 |
+
# Drag from the second line to the fourth line.
|
| 306 |
+
self.simulate_drag(2, 4)
|
| 307 |
+
self.assertEqual(self.get_selection(), ('2.0', '5.0'))
|
| 308 |
+
|
| 309 |
+
@unittest.skip('test disabled')
|
| 310 |
+
def test_drag_selection_up(self):
|
| 311 |
+
self.linenumber.show_sidebar()
|
| 312 |
+
self.text.insert('1.0', 'one\ntwo\nthree\nfour\nfive\n')
|
| 313 |
+
self.root.update()
|
| 314 |
+
|
| 315 |
+
# Drag from the fourth line to the second line.
|
| 316 |
+
self.simulate_drag(4, 2)
|
| 317 |
+
self.assertEqual(self.get_selection(), ('2.0', '5.0'))
|
| 318 |
+
|
| 319 |
+
def test_scroll(self):
|
| 320 |
+
self.linenumber.show_sidebar()
|
| 321 |
+
self.text.insert('1.0', 'line\n' * 100)
|
| 322 |
+
self.root.update()
|
| 323 |
+
|
| 324 |
+
# Scroll down 10 lines.
|
| 325 |
+
self.text.yview_scroll(10, 'unit')
|
| 326 |
+
self.root.update()
|
| 327 |
+
self.assertEqual(self.text.index('@0,0'), '11.0')
|
| 328 |
+
self.assertEqual(self.linenumber.sidebar_text.index('@0,0'), '11.0')
|
| 329 |
+
|
| 330 |
+
# Generate a mouse-wheel event and make sure it scrolled up or down.
|
| 331 |
+
# The meaning of the "delta" is OS-dependant, so this just checks for
|
| 332 |
+
# any change.
|
| 333 |
+
self.linenumber.sidebar_text.event_generate('<MouseWheel>',
|
| 334 |
+
x=0, y=0,
|
| 335 |
+
delta=10)
|
| 336 |
+
self.root.update()
|
| 337 |
+
self.assertNotEqual(self.text.index('@0,0'), '11.0')
|
| 338 |
+
self.assertNotEqual(self.linenumber.sidebar_text.index('@0,0'), '11.0')
|
| 339 |
+
|
| 340 |
+
def test_font(self):
|
| 341 |
+
ln = self.linenumber
|
| 342 |
+
|
| 343 |
+
orig_font = ln.sidebar_text['font']
|
| 344 |
+
test_font = 'TkTextFont'
|
| 345 |
+
self.assertNotEqual(orig_font, test_font)
|
| 346 |
+
|
| 347 |
+
# Ensure line numbers aren't shown.
|
| 348 |
+
ln.hide_sidebar()
|
| 349 |
+
|
| 350 |
+
self.font_override = test_font
|
| 351 |
+
# Nothing breaks when line numbers aren't shown.
|
| 352 |
+
ln.update_font()
|
| 353 |
+
|
| 354 |
+
# Activate line numbers, previous font change is immediately effective.
|
| 355 |
+
ln.show_sidebar()
|
| 356 |
+
self.assertEqual(ln.sidebar_text['font'], test_font)
|
| 357 |
+
|
| 358 |
+
# Call the font update with line numbers shown, change is picked up.
|
| 359 |
+
self.font_override = orig_font
|
| 360 |
+
ln.update_font()
|
| 361 |
+
self.assertEqual(ln.sidebar_text['font'], orig_font)
|
| 362 |
+
|
| 363 |
+
def test_highlight_colors(self):
|
| 364 |
+
ln = self.linenumber
|
| 365 |
+
|
| 366 |
+
orig_colors = dict(self.highlight_cfg)
|
| 367 |
+
test_colors = {'background': '#222222', 'foreground': '#ffff00'}
|
| 368 |
+
|
| 369 |
+
def assert_colors_are_equal(colors):
|
| 370 |
+
self.assertEqual(ln.sidebar_text['background'], colors['background'])
|
| 371 |
+
self.assertEqual(ln.sidebar_text['foreground'], colors['foreground'])
|
| 372 |
+
|
| 373 |
+
# Ensure line numbers aren't shown.
|
| 374 |
+
ln.hide_sidebar()
|
| 375 |
+
|
| 376 |
+
self.highlight_cfg = test_colors
|
| 377 |
+
# Nothing breaks with inactive line numbers.
|
| 378 |
+
ln.update_colors()
|
| 379 |
+
|
| 380 |
+
# Show line numbers, previous colors change is immediately effective.
|
| 381 |
+
ln.show_sidebar()
|
| 382 |
+
assert_colors_are_equal(test_colors)
|
| 383 |
+
|
| 384 |
+
# Call colors update with no change to the configured colors.
|
| 385 |
+
ln.update_colors()
|
| 386 |
+
assert_colors_are_equal(test_colors)
|
| 387 |
+
|
| 388 |
+
# Call the colors update with line numbers shown, change is picked up.
|
| 389 |
+
self.highlight_cfg = orig_colors
|
| 390 |
+
ln.update_colors()
|
| 391 |
+
assert_colors_are_equal(orig_colors)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
class ShellSidebarTest(unittest.TestCase):
|
| 395 |
+
root: tk.Tk = None
|
| 396 |
+
shell: PyShell = None
|
| 397 |
+
|
| 398 |
+
@classmethod
|
| 399 |
+
def setUpClass(cls):
|
| 400 |
+
requires('gui')
|
| 401 |
+
|
| 402 |
+
cls.root = root = tk.Tk()
|
| 403 |
+
root.withdraw()
|
| 404 |
+
|
| 405 |
+
fix_scaling(root)
|
| 406 |
+
fixwordbreaks(root)
|
| 407 |
+
fix_x11_paste(root)
|
| 408 |
+
|
| 409 |
+
cls.flist = flist = PyShellFileList(root)
|
| 410 |
+
# See #43981 about macosx.setupApp(root, flist) causing failure.
|
| 411 |
+
root.update_idletasks()
|
| 412 |
+
|
| 413 |
+
cls.init_shell()
|
| 414 |
+
|
| 415 |
+
@classmethod
|
| 416 |
+
def tearDownClass(cls):
|
| 417 |
+
if cls.shell is not None:
|
| 418 |
+
cls.shell.executing = False
|
| 419 |
+
cls.shell.close()
|
| 420 |
+
cls.shell = None
|
| 421 |
+
cls.flist = None
|
| 422 |
+
cls.root.update_idletasks()
|
| 423 |
+
cls.root.destroy()
|
| 424 |
+
cls.root = None
|
| 425 |
+
|
| 426 |
+
@classmethod
|
| 427 |
+
def init_shell(cls):
|
| 428 |
+
cls.shell = cls.flist.open_shell()
|
| 429 |
+
cls.shell.pollinterval = 10
|
| 430 |
+
cls.root.update()
|
| 431 |
+
cls.n_preface_lines = get_lineno(cls.shell.text, 'end-1c') - 1
|
| 432 |
+
|
| 433 |
+
@classmethod
|
| 434 |
+
def reset_shell(cls):
|
| 435 |
+
cls.shell.per.bottom.delete(f'{cls.n_preface_lines+1}.0', 'end-1c')
|
| 436 |
+
cls.shell.shell_sidebar.update_sidebar()
|
| 437 |
+
cls.root.update()
|
| 438 |
+
|
| 439 |
+
def setUp(self):
|
| 440 |
+
# In some test environments, e.g. Azure Pipelines (as of
|
| 441 |
+
# Apr. 2021), sys.stdout is changed between tests. However,
|
| 442 |
+
# PyShell relies on overriding sys.stdout when run without a
|
| 443 |
+
# sub-process (as done here; see setUpClass).
|
| 444 |
+
self._saved_stdout = None
|
| 445 |
+
if sys.stdout != self.shell.stdout:
|
| 446 |
+
self._saved_stdout = sys.stdout
|
| 447 |
+
sys.stdout = self.shell.stdout
|
| 448 |
+
|
| 449 |
+
self.reset_shell()
|
| 450 |
+
|
| 451 |
+
def tearDown(self):
|
| 452 |
+
if self._saved_stdout is not None:
|
| 453 |
+
sys.stdout = self._saved_stdout
|
| 454 |
+
|
| 455 |
+
def get_sidebar_lines(self):
|
| 456 |
+
canvas = self.shell.shell_sidebar.canvas
|
| 457 |
+
texts = list(canvas.find(tk.ALL))
|
| 458 |
+
texts_by_y_coords = {
|
| 459 |
+
canvas.bbox(text)[1]: canvas.itemcget(text, 'text')
|
| 460 |
+
for text in texts
|
| 461 |
+
}
|
| 462 |
+
line_y_coords = self.get_shell_line_y_coords()
|
| 463 |
+
return [texts_by_y_coords.get(y, None) for y in line_y_coords]
|
| 464 |
+
|
| 465 |
+
def assert_sidebar_lines_end_with(self, expected_lines):
|
| 466 |
+
self.shell.shell_sidebar.update_sidebar()
|
| 467 |
+
self.assertEqual(
|
| 468 |
+
self.get_sidebar_lines()[-len(expected_lines):],
|
| 469 |
+
expected_lines,
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
def get_shell_line_y_coords(self):
|
| 473 |
+
text = self.shell.text
|
| 474 |
+
y_coords = []
|
| 475 |
+
index = text.index("@0,0")
|
| 476 |
+
if index.split('.', 1)[1] != '0':
|
| 477 |
+
index = text.index(f"{index} +1line linestart")
|
| 478 |
+
while (lineinfo := text.dlineinfo(index)) is not None:
|
| 479 |
+
y_coords.append(lineinfo[1])
|
| 480 |
+
index = text.index(f"{index} +1line")
|
| 481 |
+
return y_coords
|
| 482 |
+
|
| 483 |
+
def get_sidebar_line_y_coords(self):
|
| 484 |
+
canvas = self.shell.shell_sidebar.canvas
|
| 485 |
+
texts = list(canvas.find(tk.ALL))
|
| 486 |
+
texts.sort(key=lambda text: canvas.bbox(text)[1])
|
| 487 |
+
return [canvas.bbox(text)[1] for text in texts]
|
| 488 |
+
|
| 489 |
+
def assert_sidebar_lines_synced(self):
|
| 490 |
+
self.assertLessEqual(
|
| 491 |
+
set(self.get_sidebar_line_y_coords()),
|
| 492 |
+
set(self.get_shell_line_y_coords()),
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
def do_input(self, input):
|
| 496 |
+
shell = self.shell
|
| 497 |
+
text = shell.text
|
| 498 |
+
for line_index, line in enumerate(input.split('\n')):
|
| 499 |
+
if line_index > 0:
|
| 500 |
+
text.event_generate('<<newline-and-indent>>')
|
| 501 |
+
text.insert('insert', line, 'stdin')
|
| 502 |
+
|
| 503 |
+
def test_initial_state(self):
|
| 504 |
+
sidebar_lines = self.get_sidebar_lines()
|
| 505 |
+
self.assertEqual(
|
| 506 |
+
sidebar_lines,
|
| 507 |
+
[None] * (len(sidebar_lines) - 1) + ['>>>'],
|
| 508 |
+
)
|
| 509 |
+
self.assert_sidebar_lines_synced()
|
| 510 |
+
|
| 511 |
+
@run_in_tk_mainloop()
|
| 512 |
+
def test_single_empty_input(self):
|
| 513 |
+
self.do_input('\n')
|
| 514 |
+
yield
|
| 515 |
+
self.assert_sidebar_lines_end_with(['>>>', '>>>'])
|
| 516 |
+
|
| 517 |
+
@run_in_tk_mainloop()
|
| 518 |
+
def test_single_line_statement(self):
|
| 519 |
+
self.do_input('1\n')
|
| 520 |
+
yield
|
| 521 |
+
self.assert_sidebar_lines_end_with(['>>>', None, '>>>'])
|
| 522 |
+
|
| 523 |
+
@run_in_tk_mainloop()
|
| 524 |
+
def test_multi_line_statement(self):
|
| 525 |
+
# Block statements are not indented because IDLE auto-indents.
|
| 526 |
+
self.do_input(dedent('''\
|
| 527 |
+
if True:
|
| 528 |
+
print(1)
|
| 529 |
+
|
| 530 |
+
'''))
|
| 531 |
+
yield
|
| 532 |
+
self.assert_sidebar_lines_end_with([
|
| 533 |
+
'>>>',
|
| 534 |
+
'...',
|
| 535 |
+
'...',
|
| 536 |
+
'...',
|
| 537 |
+
None,
|
| 538 |
+
'>>>',
|
| 539 |
+
])
|
| 540 |
+
|
| 541 |
+
@run_in_tk_mainloop()
|
| 542 |
+
def test_single_long_line_wraps(self):
|
| 543 |
+
self.do_input('1' * 200 + '\n')
|
| 544 |
+
yield
|
| 545 |
+
self.assert_sidebar_lines_end_with(['>>>', None, '>>>'])
|
| 546 |
+
self.assert_sidebar_lines_synced()
|
| 547 |
+
|
| 548 |
+
@run_in_tk_mainloop()
|
| 549 |
+
def test_squeeze_multi_line_output(self):
|
| 550 |
+
shell = self.shell
|
| 551 |
+
text = shell.text
|
| 552 |
+
|
| 553 |
+
self.do_input('print("a\\nb\\nc")\n')
|
| 554 |
+
yield
|
| 555 |
+
self.assert_sidebar_lines_end_with(['>>>', None, None, None, '>>>'])
|
| 556 |
+
|
| 557 |
+
text.mark_set('insert', f'insert -1line linestart')
|
| 558 |
+
text.event_generate('<<squeeze-current-text>>')
|
| 559 |
+
yield
|
| 560 |
+
self.assert_sidebar_lines_end_with(['>>>', None, '>>>'])
|
| 561 |
+
self.assert_sidebar_lines_synced()
|
| 562 |
+
|
| 563 |
+
shell.squeezer.expandingbuttons[0].expand()
|
| 564 |
+
yield
|
| 565 |
+
self.assert_sidebar_lines_end_with(['>>>', None, None, None, '>>>'])
|
| 566 |
+
self.assert_sidebar_lines_synced()
|
| 567 |
+
|
| 568 |
+
@run_in_tk_mainloop()
|
| 569 |
+
def test_interrupt_recall_undo_redo(self):
|
| 570 |
+
text = self.shell.text
|
| 571 |
+
# Block statements are not indented because IDLE auto-indents.
|
| 572 |
+
initial_sidebar_lines = self.get_sidebar_lines()
|
| 573 |
+
|
| 574 |
+
self.do_input(dedent('''\
|
| 575 |
+
if True:
|
| 576 |
+
print(1)
|
| 577 |
+
'''))
|
| 578 |
+
yield
|
| 579 |
+
self.assert_sidebar_lines_end_with(['>>>', '...', '...'])
|
| 580 |
+
with_block_sidebar_lines = self.get_sidebar_lines()
|
| 581 |
+
self.assertNotEqual(with_block_sidebar_lines, initial_sidebar_lines)
|
| 582 |
+
|
| 583 |
+
# Control-C
|
| 584 |
+
text.event_generate('<<interrupt-execution>>')
|
| 585 |
+
yield
|
| 586 |
+
self.assert_sidebar_lines_end_with(['>>>', '...', '...', None, '>>>'])
|
| 587 |
+
|
| 588 |
+
# Recall previous via history
|
| 589 |
+
text.event_generate('<<history-previous>>')
|
| 590 |
+
text.event_generate('<<interrupt-execution>>')
|
| 591 |
+
yield
|
| 592 |
+
self.assert_sidebar_lines_end_with(['>>>', '...', None, '>>>'])
|
| 593 |
+
|
| 594 |
+
# Recall previous via recall
|
| 595 |
+
text.mark_set('insert', text.index('insert -2l'))
|
| 596 |
+
text.event_generate('<<newline-and-indent>>')
|
| 597 |
+
yield
|
| 598 |
+
|
| 599 |
+
text.event_generate('<<undo>>')
|
| 600 |
+
yield
|
| 601 |
+
self.assert_sidebar_lines_end_with(['>>>'])
|
| 602 |
+
|
| 603 |
+
text.event_generate('<<redo>>')
|
| 604 |
+
yield
|
| 605 |
+
self.assert_sidebar_lines_end_with(['>>>', '...'])
|
| 606 |
+
|
| 607 |
+
text.event_generate('<<newline-and-indent>>')
|
| 608 |
+
text.event_generate('<<newline-and-indent>>')
|
| 609 |
+
yield
|
| 610 |
+
self.assert_sidebar_lines_end_with(
|
| 611 |
+
['>>>', '...', '...', '...', None, '>>>']
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
@run_in_tk_mainloop()
|
| 615 |
+
def test_very_long_wrapped_line(self):
|
| 616 |
+
with support.adjust_int_max_str_digits(11_111), \
|
| 617 |
+
swap_attr(self.shell, 'squeezer', None):
|
| 618 |
+
self.do_input('x = ' + '1'*10_000 + '\n')
|
| 619 |
+
yield
|
| 620 |
+
self.assertEqual(self.get_sidebar_lines(), ['>>>'])
|
| 621 |
+
|
| 622 |
+
def test_font(self):
|
| 623 |
+
sidebar = self.shell.shell_sidebar
|
| 624 |
+
|
| 625 |
+
test_font = 'TkTextFont'
|
| 626 |
+
|
| 627 |
+
def mock_idleconf_GetFont(root, configType, section):
|
| 628 |
+
return test_font
|
| 629 |
+
GetFont_patcher = unittest.mock.patch.object(
|
| 630 |
+
idlelib.sidebar.idleConf, 'GetFont', mock_idleconf_GetFont)
|
| 631 |
+
GetFont_patcher.start()
|
| 632 |
+
def cleanup():
|
| 633 |
+
GetFont_patcher.stop()
|
| 634 |
+
sidebar.update_font()
|
| 635 |
+
self.addCleanup(cleanup)
|
| 636 |
+
|
| 637 |
+
def get_sidebar_font():
|
| 638 |
+
canvas = sidebar.canvas
|
| 639 |
+
texts = list(canvas.find(tk.ALL))
|
| 640 |
+
fonts = {canvas.itemcget(text, 'font') for text in texts}
|
| 641 |
+
self.assertEqual(len(fonts), 1)
|
| 642 |
+
return next(iter(fonts))
|
| 643 |
+
|
| 644 |
+
self.assertNotEqual(get_sidebar_font(), test_font)
|
| 645 |
+
sidebar.update_font()
|
| 646 |
+
self.assertEqual(get_sidebar_font(), test_font)
|
| 647 |
+
|
| 648 |
+
def test_highlight_colors(self):
|
| 649 |
+
sidebar = self.shell.shell_sidebar
|
| 650 |
+
|
| 651 |
+
test_colors = {"background": '#abcdef', "foreground": '#123456'}
|
| 652 |
+
|
| 653 |
+
orig_idleConf_GetHighlight = idlelib.sidebar.idleConf.GetHighlight
|
| 654 |
+
def mock_idleconf_GetHighlight(theme, element):
|
| 655 |
+
if element in ['linenumber', 'console']:
|
| 656 |
+
return test_colors
|
| 657 |
+
return orig_idleConf_GetHighlight(theme, element)
|
| 658 |
+
GetHighlight_patcher = unittest.mock.patch.object(
|
| 659 |
+
idlelib.sidebar.idleConf, 'GetHighlight',
|
| 660 |
+
mock_idleconf_GetHighlight)
|
| 661 |
+
GetHighlight_patcher.start()
|
| 662 |
+
def cleanup():
|
| 663 |
+
GetHighlight_patcher.stop()
|
| 664 |
+
sidebar.update_colors()
|
| 665 |
+
self.addCleanup(cleanup)
|
| 666 |
+
|
| 667 |
+
def get_sidebar_colors():
|
| 668 |
+
canvas = sidebar.canvas
|
| 669 |
+
texts = list(canvas.find(tk.ALL))
|
| 670 |
+
fgs = {canvas.itemcget(text, 'fill') for text in texts}
|
| 671 |
+
self.assertEqual(len(fgs), 1)
|
| 672 |
+
fg = next(iter(fgs))
|
| 673 |
+
bg = canvas.cget('background')
|
| 674 |
+
return {"background": bg, "foreground": fg}
|
| 675 |
+
|
| 676 |
+
self.assertNotEqual(get_sidebar_colors(), test_colors)
|
| 677 |
+
sidebar.update_colors()
|
| 678 |
+
self.assertEqual(get_sidebar_colors(), test_colors)
|
| 679 |
+
|
| 680 |
+
@run_in_tk_mainloop()
|
| 681 |
+
def test_mousewheel(self):
|
| 682 |
+
sidebar = self.shell.shell_sidebar
|
| 683 |
+
text = self.shell.text
|
| 684 |
+
|
| 685 |
+
# Enter a 100-line string to scroll the shell screen down.
|
| 686 |
+
self.do_input('x = """' + '\n'*100 + '"""\n')
|
| 687 |
+
yield
|
| 688 |
+
self.assertGreater(get_lineno(text, '@0,0'), 1)
|
| 689 |
+
|
| 690 |
+
last_lineno = get_end_linenumber(text)
|
| 691 |
+
self.assertIsNotNone(text.dlineinfo(text.index(f'{last_lineno}.0')))
|
| 692 |
+
|
| 693 |
+
# Scroll up using the <MouseWheel> event.
|
| 694 |
+
# The meaning delta is platform-dependant.
|
| 695 |
+
delta = -1 if sys.platform == 'darwin' else 120
|
| 696 |
+
sidebar.canvas.event_generate('<MouseWheel>', x=0, y=0, delta=delta)
|
| 697 |
+
yield
|
| 698 |
+
self.assertIsNone(text.dlineinfo(text.index(f'{last_lineno}.0')))
|
| 699 |
+
|
| 700 |
+
# Scroll back down using the <Button-5> event.
|
| 701 |
+
sidebar.canvas.event_generate('<Button-5>', x=0, y=0)
|
| 702 |
+
yield
|
| 703 |
+
self.assertIsNotNone(text.dlineinfo(text.index(f'{last_lineno}.0')))
|
| 704 |
+
|
| 705 |
+
@run_in_tk_mainloop()
|
| 706 |
+
def test_copy(self):
|
| 707 |
+
sidebar = self.shell.shell_sidebar
|
| 708 |
+
text = self.shell.text
|
| 709 |
+
|
| 710 |
+
first_line = get_end_linenumber(text)
|
| 711 |
+
|
| 712 |
+
self.do_input(dedent('''\
|
| 713 |
+
if True:
|
| 714 |
+
print(1)
|
| 715 |
+
|
| 716 |
+
'''))
|
| 717 |
+
yield
|
| 718 |
+
|
| 719 |
+
text.tag_add('sel', f'{first_line}.0', 'end-1c')
|
| 720 |
+
selected_text = text.get('sel.first', 'sel.last')
|
| 721 |
+
self.assertTrue(selected_text.startswith('if True:\n'))
|
| 722 |
+
self.assertIn('\n1\n', selected_text)
|
| 723 |
+
|
| 724 |
+
text.event_generate('<<copy>>')
|
| 725 |
+
self.addCleanup(text.clipboard_clear)
|
| 726 |
+
|
| 727 |
+
copied_text = text.clipboard_get()
|
| 728 |
+
self.assertEqual(copied_text, selected_text)
|
| 729 |
+
|
| 730 |
+
@run_in_tk_mainloop()
|
| 731 |
+
def test_copy_with_prompts(self):
|
| 732 |
+
sidebar = self.shell.shell_sidebar
|
| 733 |
+
text = self.shell.text
|
| 734 |
+
|
| 735 |
+
first_line = get_end_linenumber(text)
|
| 736 |
+
self.do_input(dedent('''\
|
| 737 |
+
if True:
|
| 738 |
+
print(1)
|
| 739 |
+
|
| 740 |
+
'''))
|
| 741 |
+
yield
|
| 742 |
+
|
| 743 |
+
text.tag_add('sel', f'{first_line}.3', 'end-1c')
|
| 744 |
+
selected_text = text.get('sel.first', 'sel.last')
|
| 745 |
+
self.assertTrue(selected_text.startswith('True:\n'))
|
| 746 |
+
|
| 747 |
+
selected_lines_text = text.get('sel.first linestart', 'sel.last')
|
| 748 |
+
selected_lines = selected_lines_text.split('\n')
|
| 749 |
+
selected_lines.pop() # Final '' is a split artifact, not a line.
|
| 750 |
+
# Expect a block of input and a single output line.
|
| 751 |
+
expected_prompts = \
|
| 752 |
+
['>>>'] + ['...'] * (len(selected_lines) - 2) + [None]
|
| 753 |
+
selected_text_with_prompts = '\n'.join(
|
| 754 |
+
line if prompt is None else prompt + ' ' + line
|
| 755 |
+
for prompt, line in zip(expected_prompts,
|
| 756 |
+
selected_lines,
|
| 757 |
+
strict=True)
|
| 758 |
+
) + '\n'
|
| 759 |
+
|
| 760 |
+
text.event_generate('<<copy-with-prompts>>')
|
| 761 |
+
self.addCleanup(text.clipboard_clear)
|
| 762 |
+
|
| 763 |
+
copied_text = text.clipboard_get()
|
| 764 |
+
self.assertEqual(copied_text, selected_text_with_prompts)
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
if __name__ == '__main__':
|
| 768 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_stackviewer.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test stackviewer, coverage 63%."
|
| 2 |
+
|
| 3 |
+
from idlelib import stackviewer
|
| 4 |
+
import unittest
|
| 5 |
+
from test.support import requires
|
| 6 |
+
from tkinter import Tk
|
| 7 |
+
|
| 8 |
+
from idlelib.tree import TreeNode, ScrolledCanvas
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class StackBrowserTest(unittest.TestCase):
|
| 13 |
+
|
| 14 |
+
@classmethod
|
| 15 |
+
def setUpClass(cls):
|
| 16 |
+
svs = stackviewer.sys
|
| 17 |
+
try:
|
| 18 |
+
abc
|
| 19 |
+
except NameError:
|
| 20 |
+
svs.last_type, svs.last_value, svs.last_traceback = (
|
| 21 |
+
sys.exc_info())
|
| 22 |
+
|
| 23 |
+
requires('gui')
|
| 24 |
+
cls.root = Tk()
|
| 25 |
+
cls.root.withdraw()
|
| 26 |
+
|
| 27 |
+
@classmethod
|
| 28 |
+
def tearDownClass(cls):
|
| 29 |
+
svs = stackviewer.sys
|
| 30 |
+
del svs.last_traceback, svs.last_type, svs.last_value
|
| 31 |
+
|
| 32 |
+
cls.root.update_idletasks()
|
| 33 |
+
## for id in cls.root.tk.call('after', 'info'):
|
| 34 |
+
## cls.root.after_cancel(id) # Need for EditorWindow.
|
| 35 |
+
cls.root.destroy()
|
| 36 |
+
del cls.root
|
| 37 |
+
|
| 38 |
+
def test_init(self):
|
| 39 |
+
sb = stackviewer.StackBrowser(self.root)
|
| 40 |
+
isi = self.assertIsInstance
|
| 41 |
+
isi(stackviewer.sc, ScrolledCanvas)
|
| 42 |
+
isi(stackviewer.item, stackviewer.StackTreeItem)
|
| 43 |
+
isi(stackviewer.node, TreeNode)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if __name__ == '__main__':
|
| 47 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_statusbar.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test statusbar, coverage 100%."
|
| 2 |
+
|
| 3 |
+
from idlelib import statusbar
|
| 4 |
+
import unittest
|
| 5 |
+
from test.support import requires
|
| 6 |
+
from tkinter import Tk
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Test(unittest.TestCase):
|
| 10 |
+
|
| 11 |
+
@classmethod
|
| 12 |
+
def setUpClass(cls):
|
| 13 |
+
requires('gui')
|
| 14 |
+
cls.root = Tk()
|
| 15 |
+
cls.root.withdraw()
|
| 16 |
+
|
| 17 |
+
@classmethod
|
| 18 |
+
def tearDownClass(cls):
|
| 19 |
+
cls.root.update_idletasks()
|
| 20 |
+
cls.root.destroy()
|
| 21 |
+
del cls.root
|
| 22 |
+
|
| 23 |
+
def test_init(self):
|
| 24 |
+
bar = statusbar.MultiStatusBar(self.root)
|
| 25 |
+
self.assertEqual(bar.labels, {})
|
| 26 |
+
|
| 27 |
+
def test_set_label(self):
|
| 28 |
+
bar = statusbar.MultiStatusBar(self.root)
|
| 29 |
+
bar.set_label('left', text='sometext', width=10)
|
| 30 |
+
self.assertIn('left', bar.labels)
|
| 31 |
+
left = bar.labels['left']
|
| 32 |
+
self.assertEqual(left['text'], 'sometext')
|
| 33 |
+
self.assertEqual(left['width'], 10)
|
| 34 |
+
bar.set_label('left', text='revised text')
|
| 35 |
+
self.assertEqual(left['text'], 'revised text')
|
| 36 |
+
bar.set_label('right', text='correct text')
|
| 37 |
+
self.assertEqual(bar.labels['right']['text'], 'correct text')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if __name__ == '__main__':
|
| 41 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/idle_test/test_undo.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test undo, coverage 77%."
|
| 2 |
+
# Only test UndoDelegator so far.
|
| 3 |
+
|
| 4 |
+
from idlelib.undo import UndoDelegator
|
| 5 |
+
import unittest
|
| 6 |
+
from test.support import requires
|
| 7 |
+
requires('gui')
|
| 8 |
+
|
| 9 |
+
from unittest.mock import Mock
|
| 10 |
+
from tkinter import Text, Tk
|
| 11 |
+
from idlelib.percolator import Percolator
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class UndoDelegatorTest(unittest.TestCase):
|
| 15 |
+
|
| 16 |
+
@classmethod
|
| 17 |
+
def setUpClass(cls):
|
| 18 |
+
cls.root = Tk()
|
| 19 |
+
cls.text = Text(cls.root)
|
| 20 |
+
cls.percolator = Percolator(cls.text)
|
| 21 |
+
|
| 22 |
+
@classmethod
|
| 23 |
+
def tearDownClass(cls):
|
| 24 |
+
cls.percolator.redir.close()
|
| 25 |
+
del cls.percolator, cls.text
|
| 26 |
+
cls.root.destroy()
|
| 27 |
+
del cls.root
|
| 28 |
+
|
| 29 |
+
def setUp(self):
|
| 30 |
+
self.delegator = UndoDelegator()
|
| 31 |
+
self.delegator.bell = Mock()
|
| 32 |
+
self.percolator.insertfilter(self.delegator)
|
| 33 |
+
|
| 34 |
+
def tearDown(self):
|
| 35 |
+
self.percolator.removefilter(self.delegator)
|
| 36 |
+
self.text.delete('1.0', 'end')
|
| 37 |
+
self.delegator.resetcache()
|
| 38 |
+
|
| 39 |
+
def test_undo_event(self):
|
| 40 |
+
text = self.text
|
| 41 |
+
|
| 42 |
+
text.insert('insert', 'foobar')
|
| 43 |
+
text.insert('insert', 'h')
|
| 44 |
+
text.event_generate('<<undo>>')
|
| 45 |
+
self.assertEqual(text.get('1.0', 'end'), '\n')
|
| 46 |
+
|
| 47 |
+
text.insert('insert', 'foo')
|
| 48 |
+
text.insert('insert', 'bar')
|
| 49 |
+
text.delete('1.2', '1.4')
|
| 50 |
+
text.insert('insert', 'hello')
|
| 51 |
+
text.event_generate('<<undo>>')
|
| 52 |
+
self.assertEqual(text.get('1.0', '1.4'), 'foar')
|
| 53 |
+
text.event_generate('<<undo>>')
|
| 54 |
+
self.assertEqual(text.get('1.0', '1.6'), 'foobar')
|
| 55 |
+
text.event_generate('<<undo>>')
|
| 56 |
+
self.assertEqual(text.get('1.0', '1.3'), 'foo')
|
| 57 |
+
text.event_generate('<<undo>>')
|
| 58 |
+
self.delegator.undo_event('event')
|
| 59 |
+
self.assertTrue(self.delegator.bell.called)
|
| 60 |
+
|
| 61 |
+
def test_redo_event(self):
|
| 62 |
+
text = self.text
|
| 63 |
+
|
| 64 |
+
text.insert('insert', 'foo')
|
| 65 |
+
text.insert('insert', 'bar')
|
| 66 |
+
text.delete('1.0', '1.3')
|
| 67 |
+
text.event_generate('<<undo>>')
|
| 68 |
+
text.event_generate('<<redo>>')
|
| 69 |
+
self.assertEqual(text.get('1.0', '1.3'), 'bar')
|
| 70 |
+
text.event_generate('<<redo>>')
|
| 71 |
+
self.assertTrue(self.delegator.bell.called)
|
| 72 |
+
|
| 73 |
+
def test_dump_event(self):
|
| 74 |
+
"""
|
| 75 |
+
Dump_event cannot be tested directly without changing
|
| 76 |
+
environment variables. So, test statements in dump_event
|
| 77 |
+
indirectly
|
| 78 |
+
"""
|
| 79 |
+
text = self.text
|
| 80 |
+
d = self.delegator
|
| 81 |
+
|
| 82 |
+
text.insert('insert', 'foo')
|
| 83 |
+
text.insert('insert', 'bar')
|
| 84 |
+
text.delete('1.2', '1.4')
|
| 85 |
+
self.assertTupleEqual((d.pointer, d.can_merge), (3, True))
|
| 86 |
+
text.event_generate('<<undo>>')
|
| 87 |
+
self.assertTupleEqual((d.pointer, d.can_merge), (2, False))
|
| 88 |
+
|
| 89 |
+
def test_get_set_saved(self):
|
| 90 |
+
# test the getter method get_saved
|
| 91 |
+
# test the setter method set_saved
|
| 92 |
+
# indirectly test check_saved
|
| 93 |
+
d = self.delegator
|
| 94 |
+
|
| 95 |
+
self.assertTrue(d.get_saved())
|
| 96 |
+
self.text.insert('insert', 'a')
|
| 97 |
+
self.assertFalse(d.get_saved())
|
| 98 |
+
d.saved_change_hook = Mock()
|
| 99 |
+
|
| 100 |
+
d.set_saved(True)
|
| 101 |
+
self.assertEqual(d.pointer, d.saved)
|
| 102 |
+
self.assertTrue(d.saved_change_hook.called)
|
| 103 |
+
|
| 104 |
+
d.set_saved(False)
|
| 105 |
+
self.assertEqual(d.saved, -1)
|
| 106 |
+
self.assertTrue(d.saved_change_hook.called)
|
| 107 |
+
|
| 108 |
+
def test_undo_start_stop(self):
|
| 109 |
+
# test the undo_block_start and undo_block_stop methods
|
| 110 |
+
text = self.text
|
| 111 |
+
|
| 112 |
+
text.insert('insert', 'foo')
|
| 113 |
+
self.delegator.undo_block_start()
|
| 114 |
+
text.insert('insert', 'bar')
|
| 115 |
+
text.insert('insert', 'bar')
|
| 116 |
+
self.delegator.undo_block_stop()
|
| 117 |
+
self.assertEqual(text.get('1.0', '1.3'), 'foo')
|
| 118 |
+
|
| 119 |
+
# test another code path
|
| 120 |
+
self.delegator.undo_block_start()
|
| 121 |
+
text.insert('insert', 'bar')
|
| 122 |
+
self.delegator.undo_block_stop()
|
| 123 |
+
self.assertEqual(text.get('1.0', '1.3'), 'foo')
|
| 124 |
+
|
| 125 |
+
def test_addcmd(self):
|
| 126 |
+
text = self.text
|
| 127 |
+
# when number of undo operations exceeds max_undo
|
| 128 |
+
self.delegator.max_undo = max_undo = 10
|
| 129 |
+
for i in range(max_undo + 10):
|
| 130 |
+
text.insert('insert', 'foo')
|
| 131 |
+
self.assertLessEqual(len(self.delegator.undolist), max_undo)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
if __name__ == '__main__':
|
| 135 |
+
unittest.main(verbosity=2, exit=False)
|
parrot/lib/python3.10/idlelib/idle_test/test_zzdummy.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test zzdummy, coverage 100%."
|
| 2 |
+
|
| 3 |
+
from idlelib import zzdummy
|
| 4 |
+
import unittest
|
| 5 |
+
from test.support import requires
|
| 6 |
+
from tkinter import Tk, Text
|
| 7 |
+
from unittest import mock
|
| 8 |
+
from idlelib import config
|
| 9 |
+
from idlelib import editor
|
| 10 |
+
from idlelib import format
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
usercfg = zzdummy.idleConf.userCfg
|
| 14 |
+
testcfg = {
|
| 15 |
+
'main': config.IdleUserConfParser(''),
|
| 16 |
+
'highlight': config.IdleUserConfParser(''),
|
| 17 |
+
'keys': config.IdleUserConfParser(''),
|
| 18 |
+
'extensions': config.IdleUserConfParser(''),
|
| 19 |
+
}
|
| 20 |
+
code_sample = """\
|
| 21 |
+
|
| 22 |
+
class C1:
|
| 23 |
+
# Class comment.
|
| 24 |
+
def __init__(self, a, b):
|
| 25 |
+
self.a = a
|
| 26 |
+
self.b = b
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class DummyEditwin:
|
| 31 |
+
get_selection_indices = editor.EditorWindow.get_selection_indices
|
| 32 |
+
def __init__(self, root, text):
|
| 33 |
+
self.root = root
|
| 34 |
+
self.top = root
|
| 35 |
+
self.text = text
|
| 36 |
+
self.fregion = format.FormatRegion(self)
|
| 37 |
+
self.text.undo_block_start = mock.Mock()
|
| 38 |
+
self.text.undo_block_stop = mock.Mock()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ZZDummyTest(unittest.TestCase):
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def setUpClass(cls):
|
| 45 |
+
requires('gui')
|
| 46 |
+
root = cls.root = Tk()
|
| 47 |
+
root.withdraw()
|
| 48 |
+
text = cls.text = Text(cls.root)
|
| 49 |
+
cls.editor = DummyEditwin(root, text)
|
| 50 |
+
zzdummy.idleConf.userCfg = testcfg
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def tearDownClass(cls):
|
| 54 |
+
zzdummy.idleConf.userCfg = usercfg
|
| 55 |
+
del cls.editor, cls.text
|
| 56 |
+
cls.root.update_idletasks()
|
| 57 |
+
for id in cls.root.tk.call('after', 'info'):
|
| 58 |
+
cls.root.after_cancel(id) # Need for EditorWindow.
|
| 59 |
+
cls.root.destroy()
|
| 60 |
+
del cls.root
|
| 61 |
+
|
| 62 |
+
def setUp(self):
|
| 63 |
+
text = self.text
|
| 64 |
+
text.insert('1.0', code_sample)
|
| 65 |
+
text.undo_block_start.reset_mock()
|
| 66 |
+
text.undo_block_stop.reset_mock()
|
| 67 |
+
zz = self.zz = zzdummy.ZzDummy(self.editor)
|
| 68 |
+
zzdummy.ZzDummy.ztext = '# ignore #'
|
| 69 |
+
|
| 70 |
+
def tearDown(self):
|
| 71 |
+
self.text.delete('1.0', 'end')
|
| 72 |
+
del self.zz
|
| 73 |
+
|
| 74 |
+
def checklines(self, text, value):
|
| 75 |
+
# Verify that there are lines being checked.
|
| 76 |
+
end_line = int(float(text.index('end')))
|
| 77 |
+
|
| 78 |
+
# Check each line for the starting text.
|
| 79 |
+
actual = []
|
| 80 |
+
for line in range(1, end_line):
|
| 81 |
+
txt = text.get(f'{line}.0', f'{line}.end')
|
| 82 |
+
actual.append(txt.startswith(value))
|
| 83 |
+
return actual
|
| 84 |
+
|
| 85 |
+
def test_init(self):
|
| 86 |
+
zz = self.zz
|
| 87 |
+
self.assertEqual(zz.editwin, self.editor)
|
| 88 |
+
self.assertEqual(zz.text, self.editor.text)
|
| 89 |
+
|
| 90 |
+
def test_reload(self):
|
| 91 |
+
self.assertEqual(self.zz.ztext, '# ignore #')
|
| 92 |
+
testcfg['extensions'].SetOption('ZzDummy', 'z-text', 'spam')
|
| 93 |
+
zzdummy.ZzDummy.reload()
|
| 94 |
+
self.assertEqual(self.zz.ztext, 'spam')
|
| 95 |
+
|
| 96 |
+
def test_z_in_event(self):
|
| 97 |
+
eq = self.assertEqual
|
| 98 |
+
zz = self.zz
|
| 99 |
+
text = zz.text
|
| 100 |
+
eq(self.zz.ztext, '# ignore #')
|
| 101 |
+
|
| 102 |
+
# No lines have the leading text.
|
| 103 |
+
expected = [False, False, False, False, False, False, False]
|
| 104 |
+
actual = self.checklines(text, zz.ztext)
|
| 105 |
+
eq(expected, actual)
|
| 106 |
+
|
| 107 |
+
text.tag_add('sel', '2.0', '4.end')
|
| 108 |
+
eq(zz.z_in_event(), 'break')
|
| 109 |
+
expected = [False, True, True, True, False, False, False]
|
| 110 |
+
actual = self.checklines(text, zz.ztext)
|
| 111 |
+
eq(expected, actual)
|
| 112 |
+
|
| 113 |
+
text.undo_block_start.assert_called_once()
|
| 114 |
+
text.undo_block_stop.assert_called_once()
|
| 115 |
+
|
| 116 |
+
def test_z_out_event(self):
|
| 117 |
+
eq = self.assertEqual
|
| 118 |
+
zz = self.zz
|
| 119 |
+
text = zz.text
|
| 120 |
+
eq(self.zz.ztext, '# ignore #')
|
| 121 |
+
|
| 122 |
+
# Prepend text.
|
| 123 |
+
text.tag_add('sel', '2.0', '5.end')
|
| 124 |
+
zz.z_in_event()
|
| 125 |
+
text.undo_block_start.reset_mock()
|
| 126 |
+
text.undo_block_stop.reset_mock()
|
| 127 |
+
|
| 128 |
+
# Select a few lines to remove text.
|
| 129 |
+
text.tag_remove('sel', '1.0', 'end')
|
| 130 |
+
text.tag_add('sel', '3.0', '4.end')
|
| 131 |
+
eq(zz.z_out_event(), 'break')
|
| 132 |
+
expected = [False, True, False, False, True, False, False]
|
| 133 |
+
actual = self.checklines(text, zz.ztext)
|
| 134 |
+
eq(expected, actual)
|
| 135 |
+
|
| 136 |
+
text.undo_block_start.assert_called_once()
|
| 137 |
+
text.undo_block_stop.assert_called_once()
|
| 138 |
+
|
| 139 |
+
def test_roundtrip(self):
|
| 140 |
+
# Insert and remove to all code should give back original text.
|
| 141 |
+
zz = self.zz
|
| 142 |
+
text = zz.text
|
| 143 |
+
|
| 144 |
+
text.tag_add('sel', '1.0', 'end-1c')
|
| 145 |
+
zz.z_in_event()
|
| 146 |
+
zz.z_out_event()
|
| 147 |
+
|
| 148 |
+
self.assertEqual(text.get('1.0', 'end-1c'), code_sample)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if __name__ == '__main__':
|
| 152 |
+
unittest.main(verbosity=2)
|
parrot/lib/python3.10/idlelib/mainmenu.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Define the menu contents, hotkeys, and event bindings.
|
| 2 |
+
|
| 3 |
+
There is additional configuration information in the EditorWindow class (and
|
| 4 |
+
subclasses): the menus are created there based on the menu_specs (class)
|
| 5 |
+
variable, and menus not created are silently skipped in the code here. This
|
| 6 |
+
makes it possible, for example, to define a Debug menu which is only present in
|
| 7 |
+
the PythonShell window, and a Format menu which is only present in the Editor
|
| 8 |
+
windows.
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
from importlib.util import find_spec
|
| 12 |
+
|
| 13 |
+
from idlelib.config import idleConf
|
| 14 |
+
|
| 15 |
+
# Warning: menudefs is altered in macosx.overrideRootMenu()
|
| 16 |
+
# after it is determined that an OS X Aqua Tk is in use,
|
| 17 |
+
# which cannot be done until after Tk() is first called.
|
| 18 |
+
# Do not alter the 'file', 'options', or 'help' cascades here
|
| 19 |
+
# without altering overrideRootMenu() as well.
|
| 20 |
+
# TODO: Make this more robust
|
| 21 |
+
|
| 22 |
+
menudefs = [
|
| 23 |
+
# underscore prefixes character to underscore
|
| 24 |
+
('file', [
|
| 25 |
+
('_New File', '<<open-new-window>>'),
|
| 26 |
+
('_Open...', '<<open-window-from-file>>'),
|
| 27 |
+
('Open _Module...', '<<open-module>>'),
|
| 28 |
+
('Module _Browser', '<<open-class-browser>>'),
|
| 29 |
+
('_Path Browser', '<<open-path-browser>>'),
|
| 30 |
+
None,
|
| 31 |
+
('_Save', '<<save-window>>'),
|
| 32 |
+
('Save _As...', '<<save-window-as-file>>'),
|
| 33 |
+
('Save Cop_y As...', '<<save-copy-of-window-as-file>>'),
|
| 34 |
+
None,
|
| 35 |
+
('Prin_t Window', '<<print-window>>'),
|
| 36 |
+
None,
|
| 37 |
+
('_Close Window', '<<close-window>>'),
|
| 38 |
+
('E_xit IDLE', '<<close-all-windows>>'),
|
| 39 |
+
]),
|
| 40 |
+
|
| 41 |
+
('edit', [
|
| 42 |
+
('_Undo', '<<undo>>'),
|
| 43 |
+
('_Redo', '<<redo>>'),
|
| 44 |
+
None,
|
| 45 |
+
('Select _All', '<<select-all>>'),
|
| 46 |
+
('Cu_t', '<<cut>>'),
|
| 47 |
+
('_Copy', '<<copy>>'),
|
| 48 |
+
('_Paste', '<<paste>>'),
|
| 49 |
+
None,
|
| 50 |
+
('_Find...', '<<find>>'),
|
| 51 |
+
('Find A_gain', '<<find-again>>'),
|
| 52 |
+
('Find _Selection', '<<find-selection>>'),
|
| 53 |
+
('Find in Files...', '<<find-in-files>>'),
|
| 54 |
+
('R_eplace...', '<<replace>>'),
|
| 55 |
+
None,
|
| 56 |
+
('Go to _Line', '<<goto-line>>'),
|
| 57 |
+
('S_how Completions', '<<force-open-completions>>'),
|
| 58 |
+
('E_xpand Word', '<<expand-word>>'),
|
| 59 |
+
('Show C_all Tip', '<<force-open-calltip>>'),
|
| 60 |
+
('Show Surrounding P_arens', '<<flash-paren>>'),
|
| 61 |
+
]),
|
| 62 |
+
|
| 63 |
+
('format', [
|
| 64 |
+
('F_ormat Paragraph', '<<format-paragraph>>'),
|
| 65 |
+
('_Indent Region', '<<indent-region>>'),
|
| 66 |
+
('_Dedent Region', '<<dedent-region>>'),
|
| 67 |
+
('Comment _Out Region', '<<comment-region>>'),
|
| 68 |
+
('U_ncomment Region', '<<uncomment-region>>'),
|
| 69 |
+
('Tabify Region', '<<tabify-region>>'),
|
| 70 |
+
('Untabify Region', '<<untabify-region>>'),
|
| 71 |
+
('Toggle Tabs', '<<toggle-tabs>>'),
|
| 72 |
+
('New Indent Width', '<<change-indentwidth>>'),
|
| 73 |
+
('S_trip Trailing Whitespace', '<<do-rstrip>>'),
|
| 74 |
+
]),
|
| 75 |
+
|
| 76 |
+
('run', [
|
| 77 |
+
('R_un Module', '<<run-module>>'),
|
| 78 |
+
('Run... _Customized', '<<run-custom>>'),
|
| 79 |
+
('C_heck Module', '<<check-module>>'),
|
| 80 |
+
('Python Shell', '<<open-python-shell>>'),
|
| 81 |
+
]),
|
| 82 |
+
|
| 83 |
+
('shell', [
|
| 84 |
+
('_View Last Restart', '<<view-restart>>'),
|
| 85 |
+
('_Restart Shell', '<<restart-shell>>'),
|
| 86 |
+
None,
|
| 87 |
+
('_Previous History', '<<history-previous>>'),
|
| 88 |
+
('_Next History', '<<history-next>>'),
|
| 89 |
+
None,
|
| 90 |
+
('_Interrupt Execution', '<<interrupt-execution>>'),
|
| 91 |
+
]),
|
| 92 |
+
|
| 93 |
+
('debug', [
|
| 94 |
+
('_Go to File/Line', '<<goto-file-line>>'),
|
| 95 |
+
('!_Debugger', '<<toggle-debugger>>'),
|
| 96 |
+
('_Stack Viewer', '<<open-stack-viewer>>'),
|
| 97 |
+
('!_Auto-open Stack Viewer', '<<toggle-jit-stack-viewer>>'),
|
| 98 |
+
]),
|
| 99 |
+
|
| 100 |
+
('options', [
|
| 101 |
+
('Configure _IDLE', '<<open-config-dialog>>'),
|
| 102 |
+
None,
|
| 103 |
+
('Show _Code Context', '<<toggle-code-context>>'),
|
| 104 |
+
('Show _Line Numbers', '<<toggle-line-numbers>>'),
|
| 105 |
+
('_Zoom Height', '<<zoom-height>>'),
|
| 106 |
+
]),
|
| 107 |
+
|
| 108 |
+
('window', [
|
| 109 |
+
]),
|
| 110 |
+
|
| 111 |
+
('help', [
|
| 112 |
+
('_About IDLE', '<<about-idle>>'),
|
| 113 |
+
None,
|
| 114 |
+
('_IDLE Doc', '<<help>>'),
|
| 115 |
+
('Python _Docs', '<<python-docs>>'),
|
| 116 |
+
]),
|
| 117 |
+
]
|
| 118 |
+
|
| 119 |
+
if find_spec('turtledemo'):
|
| 120 |
+
menudefs[-1][1].append(('Turtle Demo', '<<open-turtle-demo>>'))
|
| 121 |
+
|
| 122 |
+
default_keydefs = idleConf.GetCurrentKeySet()
|
| 123 |
+
|
| 124 |
+
if __name__ == '__main__':
|
| 125 |
+
from unittest import main
|
| 126 |
+
main('idlelib.idle_test.test_mainmenu', verbosity=2)
|
parrot/lib/python3.10/idlelib/multicall.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MultiCall - a class which inherits its methods from a Tkinter widget (Text, for
|
| 3 |
+
example), but enables multiple calls of functions per virtual event - all
|
| 4 |
+
matching events will be called, not only the most specific one. This is done
|
| 5 |
+
by wrapping the event functions - event_add, event_delete and event_info.
|
| 6 |
+
MultiCall recognizes only a subset of legal event sequences. Sequences which
|
| 7 |
+
are not recognized are treated by the original Tk handling mechanism. A
|
| 8 |
+
more-specific event will be called before a less-specific event.
|
| 9 |
+
|
| 10 |
+
The recognized sequences are complete one-event sequences (no emacs-style
|
| 11 |
+
Ctrl-X Ctrl-C, no shortcuts like <3>), for all types of events.
|
| 12 |
+
Key/Button Press/Release events can have modifiers.
|
| 13 |
+
The recognized modifiers are Shift, Control, Option and Command for Mac, and
|
| 14 |
+
Control, Alt, Shift, Meta/M for other platforms.
|
| 15 |
+
|
| 16 |
+
For all events which were handled by MultiCall, a new member is added to the
|
| 17 |
+
event instance passed to the binded functions - mc_type. This is one of the
|
| 18 |
+
event type constants defined in this module (such as MC_KEYPRESS).
|
| 19 |
+
For Key/Button events (which are handled by MultiCall and may receive
|
| 20 |
+
modifiers), another member is added - mc_state. This member gives the state
|
| 21 |
+
of the recognized modifiers, as a combination of the modifier constants
|
| 22 |
+
also defined in this module (for example, MC_SHIFT).
|
| 23 |
+
Using these members is absolutely portable.
|
| 24 |
+
|
| 25 |
+
The order by which events are called is defined by these rules:
|
| 26 |
+
1. A more-specific event will be called before a less-specific event.
|
| 27 |
+
2. A recently-binded event will be called before a previously-binded event,
|
| 28 |
+
unless this conflicts with the first rule.
|
| 29 |
+
Each function will be called at most once for each event.
|
| 30 |
+
"""
|
| 31 |
+
import re
|
| 32 |
+
import sys
|
| 33 |
+
|
| 34 |
+
import tkinter
|
| 35 |
+
|
| 36 |
+
# the event type constants, which define the meaning of mc_type
|
| 37 |
+
MC_KEYPRESS=0; MC_KEYRELEASE=1; MC_BUTTONPRESS=2; MC_BUTTONRELEASE=3;
|
| 38 |
+
MC_ACTIVATE=4; MC_CIRCULATE=5; MC_COLORMAP=6; MC_CONFIGURE=7;
|
| 39 |
+
MC_DEACTIVATE=8; MC_DESTROY=9; MC_ENTER=10; MC_EXPOSE=11; MC_FOCUSIN=12;
|
| 40 |
+
MC_FOCUSOUT=13; MC_GRAVITY=14; MC_LEAVE=15; MC_MAP=16; MC_MOTION=17;
|
| 41 |
+
MC_MOUSEWHEEL=18; MC_PROPERTY=19; MC_REPARENT=20; MC_UNMAP=21; MC_VISIBILITY=22;
|
| 42 |
+
# the modifier state constants, which define the meaning of mc_state
|
| 43 |
+
MC_SHIFT = 1<<0; MC_CONTROL = 1<<2; MC_ALT = 1<<3; MC_META = 1<<5
|
| 44 |
+
MC_OPTION = 1<<6; MC_COMMAND = 1<<7
|
| 45 |
+
|
| 46 |
+
# define the list of modifiers, to be used in complex event types.
|
| 47 |
+
if sys.platform == "darwin":
|
| 48 |
+
_modifiers = (("Shift",), ("Control",), ("Option",), ("Command",))
|
| 49 |
+
_modifier_masks = (MC_SHIFT, MC_CONTROL, MC_OPTION, MC_COMMAND)
|
| 50 |
+
else:
|
| 51 |
+
_modifiers = (("Control",), ("Alt",), ("Shift",), ("Meta", "M"))
|
| 52 |
+
_modifier_masks = (MC_CONTROL, MC_ALT, MC_SHIFT, MC_META)
|
| 53 |
+
|
| 54 |
+
# a dictionary to map a modifier name into its number
|
| 55 |
+
_modifier_names = dict([(name, number)
|
| 56 |
+
for number in range(len(_modifiers))
|
| 57 |
+
for name in _modifiers[number]])
|
| 58 |
+
|
| 59 |
+
# In 3.4, if no shell window is ever open, the underlying Tk widget is
|
| 60 |
+
# destroyed before .__del__ methods here are called. The following
|
| 61 |
+
# is used to selectively ignore shutdown exceptions to avoid
|
| 62 |
+
# 'Exception ignored' messages. See http://bugs.python.org/issue20167
|
| 63 |
+
APPLICATION_GONE = "application has been destroyed"
|
| 64 |
+
|
| 65 |
+
# A binder is a class which binds functions to one type of event. It has two
|
| 66 |
+
# methods: bind and unbind, which get a function and a parsed sequence, as
|
| 67 |
+
# returned by _parse_sequence(). There are two types of binders:
|
| 68 |
+
# _SimpleBinder handles event types with no modifiers and no detail.
|
| 69 |
+
# No Python functions are called when no events are binded.
|
| 70 |
+
# _ComplexBinder handles event types with modifiers and a detail.
|
| 71 |
+
# A Python function is called each time an event is generated.
|
| 72 |
+
|
| 73 |
+
class _SimpleBinder:
|
| 74 |
+
def __init__(self, type, widget, widgetinst):
|
| 75 |
+
self.type = type
|
| 76 |
+
self.sequence = '<'+_types[type][0]+'>'
|
| 77 |
+
self.widget = widget
|
| 78 |
+
self.widgetinst = widgetinst
|
| 79 |
+
self.bindedfuncs = []
|
| 80 |
+
self.handlerid = None
|
| 81 |
+
|
| 82 |
+
def bind(self, triplet, func):
|
| 83 |
+
if not self.handlerid:
|
| 84 |
+
def handler(event, l = self.bindedfuncs, mc_type = self.type):
|
| 85 |
+
event.mc_type = mc_type
|
| 86 |
+
wascalled = {}
|
| 87 |
+
for i in range(len(l)-1, -1, -1):
|
| 88 |
+
func = l[i]
|
| 89 |
+
if func not in wascalled:
|
| 90 |
+
wascalled[func] = True
|
| 91 |
+
r = func(event)
|
| 92 |
+
if r:
|
| 93 |
+
return r
|
| 94 |
+
self.handlerid = self.widget.bind(self.widgetinst,
|
| 95 |
+
self.sequence, handler)
|
| 96 |
+
self.bindedfuncs.append(func)
|
| 97 |
+
|
| 98 |
+
def unbind(self, triplet, func):
|
| 99 |
+
self.bindedfuncs.remove(func)
|
| 100 |
+
if not self.bindedfuncs:
|
| 101 |
+
self.widget.unbind(self.widgetinst, self.sequence, self.handlerid)
|
| 102 |
+
self.handlerid = None
|
| 103 |
+
|
| 104 |
+
def __del__(self):
|
| 105 |
+
if self.handlerid:
|
| 106 |
+
try:
|
| 107 |
+
self.widget.unbind(self.widgetinst, self.sequence,
|
| 108 |
+
self.handlerid)
|
| 109 |
+
except tkinter.TclError as e:
|
| 110 |
+
if not APPLICATION_GONE in e.args[0]:
|
| 111 |
+
raise
|
| 112 |
+
|
| 113 |
+
# An int in range(1 << len(_modifiers)) represents a combination of modifiers
|
| 114 |
+
# (if the least significant bit is on, _modifiers[0] is on, and so on).
|
| 115 |
+
# _state_subsets gives for each combination of modifiers, or *state*,
|
| 116 |
+
# a list of the states which are a subset of it. This list is ordered by the
|
| 117 |
+
# number of modifiers is the state - the most specific state comes first.
|
| 118 |
+
_states = range(1 << len(_modifiers))
|
| 119 |
+
_state_names = [''.join(m[0]+'-'
|
| 120 |
+
for i, m in enumerate(_modifiers)
|
| 121 |
+
if (1 << i) & s)
|
| 122 |
+
for s in _states]
|
| 123 |
+
|
| 124 |
+
def expand_substates(states):
|
| 125 |
+
'''For each item of states return a list containing all combinations of
|
| 126 |
+
that item with individual bits reset, sorted by the number of set bits.
|
| 127 |
+
'''
|
| 128 |
+
def nbits(n):
|
| 129 |
+
"number of bits set in n base 2"
|
| 130 |
+
nb = 0
|
| 131 |
+
while n:
|
| 132 |
+
n, rem = divmod(n, 2)
|
| 133 |
+
nb += rem
|
| 134 |
+
return nb
|
| 135 |
+
statelist = []
|
| 136 |
+
for state in states:
|
| 137 |
+
substates = list(set(state & x for x in states))
|
| 138 |
+
substates.sort(key=nbits, reverse=True)
|
| 139 |
+
statelist.append(substates)
|
| 140 |
+
return statelist
|
| 141 |
+
|
| 142 |
+
_state_subsets = expand_substates(_states)
|
| 143 |
+
|
| 144 |
+
# _state_codes gives for each state, the portable code to be passed as mc_state
|
| 145 |
+
_state_codes = []
|
| 146 |
+
for s in _states:
|
| 147 |
+
r = 0
|
| 148 |
+
for i in range(len(_modifiers)):
|
| 149 |
+
if (1 << i) & s:
|
| 150 |
+
r |= _modifier_masks[i]
|
| 151 |
+
_state_codes.append(r)
|
| 152 |
+
|
| 153 |
+
class _ComplexBinder:
|
| 154 |
+
# This class binds many functions, and only unbinds them when it is deleted.
|
| 155 |
+
# self.handlerids is the list of seqs and ids of binded handler functions.
|
| 156 |
+
# The binded functions sit in a dictionary of lists of lists, which maps
|
| 157 |
+
# a detail (or None) and a state into a list of functions.
|
| 158 |
+
# When a new detail is discovered, handlers for all the possible states
|
| 159 |
+
# are binded.
|
| 160 |
+
|
| 161 |
+
def __create_handler(self, lists, mc_type, mc_state):
|
| 162 |
+
def handler(event, lists = lists,
|
| 163 |
+
mc_type = mc_type, mc_state = mc_state,
|
| 164 |
+
ishandlerrunning = self.ishandlerrunning,
|
| 165 |
+
doafterhandler = self.doafterhandler):
|
| 166 |
+
ishandlerrunning[:] = [True]
|
| 167 |
+
event.mc_type = mc_type
|
| 168 |
+
event.mc_state = mc_state
|
| 169 |
+
wascalled = {}
|
| 170 |
+
r = None
|
| 171 |
+
for l in lists:
|
| 172 |
+
for i in range(len(l)-1, -1, -1):
|
| 173 |
+
func = l[i]
|
| 174 |
+
if func not in wascalled:
|
| 175 |
+
wascalled[func] = True
|
| 176 |
+
r = l[i](event)
|
| 177 |
+
if r:
|
| 178 |
+
break
|
| 179 |
+
if r:
|
| 180 |
+
break
|
| 181 |
+
ishandlerrunning[:] = []
|
| 182 |
+
# Call all functions in doafterhandler and remove them from list
|
| 183 |
+
for f in doafterhandler:
|
| 184 |
+
f()
|
| 185 |
+
doafterhandler[:] = []
|
| 186 |
+
if r:
|
| 187 |
+
return r
|
| 188 |
+
return handler
|
| 189 |
+
|
| 190 |
+
def __init__(self, type, widget, widgetinst):
|
| 191 |
+
self.type = type
|
| 192 |
+
self.typename = _types[type][0]
|
| 193 |
+
self.widget = widget
|
| 194 |
+
self.widgetinst = widgetinst
|
| 195 |
+
self.bindedfuncs = {None: [[] for s in _states]}
|
| 196 |
+
self.handlerids = []
|
| 197 |
+
# we don't want to change the lists of functions while a handler is
|
| 198 |
+
# running - it will mess up the loop and anyway, we usually want the
|
| 199 |
+
# change to happen from the next event. So we have a list of functions
|
| 200 |
+
# for the handler to run after it finishes calling the binded functions.
|
| 201 |
+
# It calls them only once.
|
| 202 |
+
# ishandlerrunning is a list. An empty one means no, otherwise - yes.
|
| 203 |
+
# this is done so that it would be mutable.
|
| 204 |
+
self.ishandlerrunning = []
|
| 205 |
+
self.doafterhandler = []
|
| 206 |
+
for s in _states:
|
| 207 |
+
lists = [self.bindedfuncs[None][i] for i in _state_subsets[s]]
|
| 208 |
+
handler = self.__create_handler(lists, type, _state_codes[s])
|
| 209 |
+
seq = '<'+_state_names[s]+self.typename+'>'
|
| 210 |
+
self.handlerids.append((seq, self.widget.bind(self.widgetinst,
|
| 211 |
+
seq, handler)))
|
| 212 |
+
|
| 213 |
+
def bind(self, triplet, func):
|
| 214 |
+
if triplet[2] not in self.bindedfuncs:
|
| 215 |
+
self.bindedfuncs[triplet[2]] = [[] for s in _states]
|
| 216 |
+
for s in _states:
|
| 217 |
+
lists = [ self.bindedfuncs[detail][i]
|
| 218 |
+
for detail in (triplet[2], None)
|
| 219 |
+
for i in _state_subsets[s] ]
|
| 220 |
+
handler = self.__create_handler(lists, self.type,
|
| 221 |
+
_state_codes[s])
|
| 222 |
+
seq = "<%s%s-%s>"% (_state_names[s], self.typename, triplet[2])
|
| 223 |
+
self.handlerids.append((seq, self.widget.bind(self.widgetinst,
|
| 224 |
+
seq, handler)))
|
| 225 |
+
doit = lambda: self.bindedfuncs[triplet[2]][triplet[0]].append(func)
|
| 226 |
+
if not self.ishandlerrunning:
|
| 227 |
+
doit()
|
| 228 |
+
else:
|
| 229 |
+
self.doafterhandler.append(doit)
|
| 230 |
+
|
| 231 |
+
def unbind(self, triplet, func):
|
| 232 |
+
doit = lambda: self.bindedfuncs[triplet[2]][triplet[0]].remove(func)
|
| 233 |
+
if not self.ishandlerrunning:
|
| 234 |
+
doit()
|
| 235 |
+
else:
|
| 236 |
+
self.doafterhandler.append(doit)
|
| 237 |
+
|
| 238 |
+
def __del__(self):
|
| 239 |
+
for seq, id in self.handlerids:
|
| 240 |
+
try:
|
| 241 |
+
self.widget.unbind(self.widgetinst, seq, id)
|
| 242 |
+
except tkinter.TclError as e:
|
| 243 |
+
if not APPLICATION_GONE in e.args[0]:
|
| 244 |
+
raise
|
| 245 |
+
|
| 246 |
+
# define the list of event types to be handled by MultiEvent. the order is
|
| 247 |
+
# compatible with the definition of event type constants.
|
| 248 |
+
_types = (
|
| 249 |
+
("KeyPress", "Key"), ("KeyRelease",), ("ButtonPress", "Button"),
|
| 250 |
+
("ButtonRelease",), ("Activate",), ("Circulate",), ("Colormap",),
|
| 251 |
+
("Configure",), ("Deactivate",), ("Destroy",), ("Enter",), ("Expose",),
|
| 252 |
+
("FocusIn",), ("FocusOut",), ("Gravity",), ("Leave",), ("Map",),
|
| 253 |
+
("Motion",), ("MouseWheel",), ("Property",), ("Reparent",), ("Unmap",),
|
| 254 |
+
("Visibility",),
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
# which binder should be used for every event type?
|
| 258 |
+
_binder_classes = (_ComplexBinder,) * 4 + (_SimpleBinder,) * (len(_types)-4)
|
| 259 |
+
|
| 260 |
+
# A dictionary to map a type name into its number
|
| 261 |
+
_type_names = dict([(name, number)
|
| 262 |
+
for number in range(len(_types))
|
| 263 |
+
for name in _types[number]])
|
| 264 |
+
|
| 265 |
+
_keysym_re = re.compile(r"^\w+$")
|
| 266 |
+
_button_re = re.compile(r"^[1-5]$")
|
| 267 |
+
def _parse_sequence(sequence):
|
| 268 |
+
"""Get a string which should describe an event sequence. If it is
|
| 269 |
+
successfully parsed as one, return a tuple containing the state (as an int),
|
| 270 |
+
the event type (as an index of _types), and the detail - None if none, or a
|
| 271 |
+
string if there is one. If the parsing is unsuccessful, return None.
|
| 272 |
+
"""
|
| 273 |
+
if not sequence or sequence[0] != '<' or sequence[-1] != '>':
|
| 274 |
+
return None
|
| 275 |
+
words = sequence[1:-1].split('-')
|
| 276 |
+
modifiers = 0
|
| 277 |
+
while words and words[0] in _modifier_names:
|
| 278 |
+
modifiers |= 1 << _modifier_names[words[0]]
|
| 279 |
+
del words[0]
|
| 280 |
+
if words and words[0] in _type_names:
|
| 281 |
+
type = _type_names[words[0]]
|
| 282 |
+
del words[0]
|
| 283 |
+
else:
|
| 284 |
+
return None
|
| 285 |
+
if _binder_classes[type] is _SimpleBinder:
|
| 286 |
+
if modifiers or words:
|
| 287 |
+
return None
|
| 288 |
+
else:
|
| 289 |
+
detail = None
|
| 290 |
+
else:
|
| 291 |
+
# _ComplexBinder
|
| 292 |
+
if type in [_type_names[s] for s in ("KeyPress", "KeyRelease")]:
|
| 293 |
+
type_re = _keysym_re
|
| 294 |
+
else:
|
| 295 |
+
type_re = _button_re
|
| 296 |
+
|
| 297 |
+
if not words:
|
| 298 |
+
detail = None
|
| 299 |
+
elif len(words) == 1 and type_re.match(words[0]):
|
| 300 |
+
detail = words[0]
|
| 301 |
+
else:
|
| 302 |
+
return None
|
| 303 |
+
|
| 304 |
+
return modifiers, type, detail
|
| 305 |
+
|
| 306 |
+
def _triplet_to_sequence(triplet):
|
| 307 |
+
if triplet[2]:
|
| 308 |
+
return '<'+_state_names[triplet[0]]+_types[triplet[1]][0]+'-'+ \
|
| 309 |
+
triplet[2]+'>'
|
| 310 |
+
else:
|
| 311 |
+
return '<'+_state_names[triplet[0]]+_types[triplet[1]][0]+'>'
|
| 312 |
+
|
| 313 |
+
_multicall_dict = {}
|
| 314 |
+
def MultiCallCreator(widget):
|
| 315 |
+
"""Return a MultiCall class which inherits its methods from the
|
| 316 |
+
given widget class (for example, Tkinter.Text). This is used
|
| 317 |
+
instead of a templating mechanism.
|
| 318 |
+
"""
|
| 319 |
+
if widget in _multicall_dict:
|
| 320 |
+
return _multicall_dict[widget]
|
| 321 |
+
|
| 322 |
+
class MultiCall (widget):
|
| 323 |
+
assert issubclass(widget, tkinter.Misc)
|
| 324 |
+
|
| 325 |
+
def __init__(self, *args, **kwargs):
|
| 326 |
+
widget.__init__(self, *args, **kwargs)
|
| 327 |
+
# a dictionary which maps a virtual event to a tuple with:
|
| 328 |
+
# 0. the function binded
|
| 329 |
+
# 1. a list of triplets - the sequences it is binded to
|
| 330 |
+
self.__eventinfo = {}
|
| 331 |
+
self.__binders = [_binder_classes[i](i, widget, self)
|
| 332 |
+
for i in range(len(_types))]
|
| 333 |
+
|
| 334 |
+
def bind(self, sequence=None, func=None, add=None):
|
| 335 |
+
#print("bind(%s, %s, %s)" % (sequence, func, add),
|
| 336 |
+
# file=sys.__stderr__)
|
| 337 |
+
if type(sequence) is str and len(sequence) > 2 and \
|
| 338 |
+
sequence[:2] == "<<" and sequence[-2:] == ">>":
|
| 339 |
+
if sequence in self.__eventinfo:
|
| 340 |
+
ei = self.__eventinfo[sequence]
|
| 341 |
+
if ei[0] is not None:
|
| 342 |
+
for triplet in ei[1]:
|
| 343 |
+
self.__binders[triplet[1]].unbind(triplet, ei[0])
|
| 344 |
+
ei[0] = func
|
| 345 |
+
if ei[0] is not None:
|
| 346 |
+
for triplet in ei[1]:
|
| 347 |
+
self.__binders[triplet[1]].bind(triplet, func)
|
| 348 |
+
else:
|
| 349 |
+
self.__eventinfo[sequence] = [func, []]
|
| 350 |
+
return widget.bind(self, sequence, func, add)
|
| 351 |
+
|
| 352 |
+
def unbind(self, sequence, funcid=None):
|
| 353 |
+
if type(sequence) is str and len(sequence) > 2 and \
|
| 354 |
+
sequence[:2] == "<<" and sequence[-2:] == ">>" and \
|
| 355 |
+
sequence in self.__eventinfo:
|
| 356 |
+
func, triplets = self.__eventinfo[sequence]
|
| 357 |
+
if func is not None:
|
| 358 |
+
for triplet in triplets:
|
| 359 |
+
self.__binders[triplet[1]].unbind(triplet, func)
|
| 360 |
+
self.__eventinfo[sequence][0] = None
|
| 361 |
+
return widget.unbind(self, sequence, funcid)
|
| 362 |
+
|
| 363 |
+
def event_add(self, virtual, *sequences):
|
| 364 |
+
#print("event_add(%s, %s)" % (repr(virtual), repr(sequences)),
|
| 365 |
+
# file=sys.__stderr__)
|
| 366 |
+
if virtual not in self.__eventinfo:
|
| 367 |
+
self.__eventinfo[virtual] = [None, []]
|
| 368 |
+
|
| 369 |
+
func, triplets = self.__eventinfo[virtual]
|
| 370 |
+
for seq in sequences:
|
| 371 |
+
triplet = _parse_sequence(seq)
|
| 372 |
+
if triplet is None:
|
| 373 |
+
#print("Tkinter event_add(%s)" % seq, file=sys.__stderr__)
|
| 374 |
+
widget.event_add(self, virtual, seq)
|
| 375 |
+
else:
|
| 376 |
+
if func is not None:
|
| 377 |
+
self.__binders[triplet[1]].bind(triplet, func)
|
| 378 |
+
triplets.append(triplet)
|
| 379 |
+
|
| 380 |
+
def event_delete(self, virtual, *sequences):
|
| 381 |
+
if virtual not in self.__eventinfo:
|
| 382 |
+
return
|
| 383 |
+
func, triplets = self.__eventinfo[virtual]
|
| 384 |
+
for seq in sequences:
|
| 385 |
+
triplet = _parse_sequence(seq)
|
| 386 |
+
if triplet is None:
|
| 387 |
+
#print("Tkinter event_delete: %s" % seq, file=sys.__stderr__)
|
| 388 |
+
widget.event_delete(self, virtual, seq)
|
| 389 |
+
else:
|
| 390 |
+
if func is not None:
|
| 391 |
+
self.__binders[triplet[1]].unbind(triplet, func)
|
| 392 |
+
triplets.remove(triplet)
|
| 393 |
+
|
| 394 |
+
def event_info(self, virtual=None):
|
| 395 |
+
if virtual is None or virtual not in self.__eventinfo:
|
| 396 |
+
return widget.event_info(self, virtual)
|
| 397 |
+
else:
|
| 398 |
+
return tuple(map(_triplet_to_sequence,
|
| 399 |
+
self.__eventinfo[virtual][1])) + \
|
| 400 |
+
widget.event_info(self, virtual)
|
| 401 |
+
|
| 402 |
+
def __del__(self):
|
| 403 |
+
for virtual in self.__eventinfo:
|
| 404 |
+
func, triplets = self.__eventinfo[virtual]
|
| 405 |
+
if func:
|
| 406 |
+
for triplet in triplets:
|
| 407 |
+
try:
|
| 408 |
+
self.__binders[triplet[1]].unbind(triplet, func)
|
| 409 |
+
except tkinter.TclError as e:
|
| 410 |
+
if not APPLICATION_GONE in e.args[0]:
|
| 411 |
+
raise
|
| 412 |
+
|
| 413 |
+
_multicall_dict[widget] = MultiCall
|
| 414 |
+
return MultiCall
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def _multi_call(parent): # htest #
|
| 418 |
+
top = tkinter.Toplevel(parent)
|
| 419 |
+
top.title("Test MultiCall")
|
| 420 |
+
x, y = map(int, parent.geometry().split('+')[1:])
|
| 421 |
+
top.geometry("+%d+%d" % (x, y + 175))
|
| 422 |
+
text = MultiCallCreator(tkinter.Text)(top)
|
| 423 |
+
text.pack()
|
| 424 |
+
def bindseq(seq, n=[0]):
|
| 425 |
+
def handler(event):
|
| 426 |
+
print(seq)
|
| 427 |
+
text.bind("<<handler%d>>"%n[0], handler)
|
| 428 |
+
text.event_add("<<handler%d>>"%n[0], seq)
|
| 429 |
+
n[0] += 1
|
| 430 |
+
bindseq("<Key>")
|
| 431 |
+
bindseq("<Control-Key>")
|
| 432 |
+
bindseq("<Alt-Key-a>")
|
| 433 |
+
bindseq("<Control-Key-a>")
|
| 434 |
+
bindseq("<Alt-Control-Key-a>")
|
| 435 |
+
bindseq("<Key-b>")
|
| 436 |
+
bindseq("<Control-Button-1>")
|
| 437 |
+
bindseq("<Button-2>")
|
| 438 |
+
bindseq("<Alt-Button-1>")
|
| 439 |
+
bindseq("<FocusOut>")
|
| 440 |
+
bindseq("<Enter>")
|
| 441 |
+
bindseq("<Leave>")
|
| 442 |
+
|
| 443 |
+
if __name__ == "__main__":
|
| 444 |
+
from unittest import main
|
| 445 |
+
main('idlelib.idle_test.test_mainmenu', verbosity=2, exit=False)
|
| 446 |
+
|
| 447 |
+
from idlelib.idle_test.htest import run
|
| 448 |
+
run(_multi_call)
|
parrot/lib/python3.10/idlelib/outwin.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
from tkinter import messagebox
|
| 7 |
+
|
| 8 |
+
from idlelib.editor import EditorWindow
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
file_line_pats = [
|
| 12 |
+
# order of patterns matters
|
| 13 |
+
r'file "([^"]*)", line (\d+)',
|
| 14 |
+
r'([^\s]+)\((\d+)\)',
|
| 15 |
+
r'^(\s*\S.*?):\s*(\d+):', # Win filename, maybe starting with spaces
|
| 16 |
+
r'([^\s]+):\s*(\d+):', # filename or path, ltrim
|
| 17 |
+
r'^\s*(\S.*?):\s*(\d+):', # Win abs path with embedded spaces, ltrim
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
file_line_progs = None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def compile_progs():
|
| 24 |
+
"Compile the patterns for matching to file name and line number."
|
| 25 |
+
global file_line_progs
|
| 26 |
+
file_line_progs = [re.compile(pat, re.IGNORECASE)
|
| 27 |
+
for pat in file_line_pats]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def file_line_helper(line):
|
| 31 |
+
"""Extract file name and line number from line of text.
|
| 32 |
+
|
| 33 |
+
Check if line of text contains one of the file/line patterns.
|
| 34 |
+
If it does and if the file and line are valid, return
|
| 35 |
+
a tuple of the file name and line number. If it doesn't match
|
| 36 |
+
or if the file or line is invalid, return None.
|
| 37 |
+
"""
|
| 38 |
+
if not file_line_progs:
|
| 39 |
+
compile_progs()
|
| 40 |
+
for prog in file_line_progs:
|
| 41 |
+
match = prog.search(line)
|
| 42 |
+
if match:
|
| 43 |
+
filename, lineno = match.group(1, 2)
|
| 44 |
+
try:
|
| 45 |
+
f = open(filename, "r")
|
| 46 |
+
f.close()
|
| 47 |
+
break
|
| 48 |
+
except OSError:
|
| 49 |
+
continue
|
| 50 |
+
else:
|
| 51 |
+
return None
|
| 52 |
+
try:
|
| 53 |
+
return filename, int(lineno)
|
| 54 |
+
except TypeError:
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class OutputWindow(EditorWindow):
|
| 59 |
+
"""An editor window that can serve as an output file.
|
| 60 |
+
|
| 61 |
+
Also the future base class for the Python shell window.
|
| 62 |
+
This class has no input facilities.
|
| 63 |
+
|
| 64 |
+
Adds binding to open a file at a line to the text widget.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
# Our own right-button menu
|
| 68 |
+
rmenu_specs = [
|
| 69 |
+
("Cut", "<<cut>>", "rmenu_check_cut"),
|
| 70 |
+
("Copy", "<<copy>>", "rmenu_check_copy"),
|
| 71 |
+
("Paste", "<<paste>>", "rmenu_check_paste"),
|
| 72 |
+
(None, None, None),
|
| 73 |
+
("Go to file/line", "<<goto-file-line>>", None),
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
allow_code_context = False
|
| 77 |
+
|
| 78 |
+
def __init__(self, *args):
|
| 79 |
+
EditorWindow.__init__(self, *args)
|
| 80 |
+
self.text.bind("<<goto-file-line>>", self.goto_file_line)
|
| 81 |
+
|
| 82 |
+
# Customize EditorWindow
|
| 83 |
+
def ispythonsource(self, filename):
|
| 84 |
+
"Python source is only part of output: do not colorize."
|
| 85 |
+
return False
|
| 86 |
+
|
| 87 |
+
def short_title(self):
|
| 88 |
+
"Customize EditorWindow title."
|
| 89 |
+
return "Output"
|
| 90 |
+
|
| 91 |
+
def maybesave(self):
|
| 92 |
+
"Customize EditorWindow to not display save file messagebox."
|
| 93 |
+
return 'yes' if self.get_saved() else 'no'
|
| 94 |
+
|
| 95 |
+
# Act as output file
|
| 96 |
+
def write(self, s, tags=(), mark="insert"):
|
| 97 |
+
"""Write text to text widget.
|
| 98 |
+
|
| 99 |
+
The text is inserted at the given index with the provided
|
| 100 |
+
tags. The text widget is then scrolled to make it visible
|
| 101 |
+
and updated to display it, giving the effect of seeing each
|
| 102 |
+
line as it is added.
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
s: Text to insert into text widget.
|
| 106 |
+
tags: Tuple of tag strings to apply on the insert.
|
| 107 |
+
mark: Index for the insert.
|
| 108 |
+
|
| 109 |
+
Return:
|
| 110 |
+
Length of text inserted.
|
| 111 |
+
"""
|
| 112 |
+
assert isinstance(s, str)
|
| 113 |
+
self.text.insert(mark, s, tags)
|
| 114 |
+
self.text.see(mark)
|
| 115 |
+
self.text.update()
|
| 116 |
+
return len(s)
|
| 117 |
+
|
| 118 |
+
def writelines(self, lines):
|
| 119 |
+
"Write each item in lines iterable."
|
| 120 |
+
for line in lines:
|
| 121 |
+
self.write(line)
|
| 122 |
+
|
| 123 |
+
def flush(self):
|
| 124 |
+
"No flushing needed as write() directly writes to widget."
|
| 125 |
+
pass
|
| 126 |
+
|
| 127 |
+
def showerror(self, *args, **kwargs):
|
| 128 |
+
messagebox.showerror(*args, **kwargs)
|
| 129 |
+
|
| 130 |
+
def goto_file_line(self, event=None):
|
| 131 |
+
"""Handle request to open file/line.
|
| 132 |
+
|
| 133 |
+
If the selected or previous line in the output window
|
| 134 |
+
contains a file name and line number, then open that file
|
| 135 |
+
name in a new window and position on the line number.
|
| 136 |
+
|
| 137 |
+
Otherwise, display an error messagebox.
|
| 138 |
+
"""
|
| 139 |
+
line = self.text.get("insert linestart", "insert lineend")
|
| 140 |
+
result = file_line_helper(line)
|
| 141 |
+
if not result:
|
| 142 |
+
# Try the previous line. This is handy e.g. in tracebacks,
|
| 143 |
+
# where you tend to right-click on the displayed source line
|
| 144 |
+
line = self.text.get("insert -1line linestart",
|
| 145 |
+
"insert -1line lineend")
|
| 146 |
+
result = file_line_helper(line)
|
| 147 |
+
if not result:
|
| 148 |
+
self.showerror(
|
| 149 |
+
"No special line",
|
| 150 |
+
"The line you point at doesn't look like "
|
| 151 |
+
"a valid file name followed by a line number.",
|
| 152 |
+
parent=self.text)
|
| 153 |
+
return
|
| 154 |
+
filename, lineno = result
|
| 155 |
+
self.flist.gotofileline(filename, lineno)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
# These classes are currently not used but might come in handy
|
| 159 |
+
class OnDemandOutputWindow:
|
| 160 |
+
|
| 161 |
+
tagdefs = {
|
| 162 |
+
# XXX Should use IdlePrefs.ColorPrefs
|
| 163 |
+
"stdout": {"foreground": "blue"},
|
| 164 |
+
"stderr": {"foreground": "#007700"},
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
def __init__(self, flist):
|
| 168 |
+
self.flist = flist
|
| 169 |
+
self.owin = None
|
| 170 |
+
|
| 171 |
+
def write(self, s, tags, mark):
|
| 172 |
+
if not self.owin:
|
| 173 |
+
self.setup()
|
| 174 |
+
self.owin.write(s, tags, mark)
|
| 175 |
+
|
| 176 |
+
def setup(self):
|
| 177 |
+
self.owin = owin = OutputWindow(self.flist)
|
| 178 |
+
text = owin.text
|
| 179 |
+
for tag, cnf in self.tagdefs.items():
|
| 180 |
+
if cnf:
|
| 181 |
+
text.tag_configure(tag, **cnf)
|
| 182 |
+
text.tag_raise('sel')
|
| 183 |
+
self.write = self.owin.write
|
| 184 |
+
|
| 185 |
+
if __name__ == '__main__':
|
| 186 |
+
from unittest import main
|
| 187 |
+
main('idlelib.idle_test.test_outwin', verbosity=2, exit=False)
|
parrot/lib/python3.10/idlelib/pyparse.py
ADDED
|
@@ -0,0 +1,589 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Define partial Python code Parser used by editor and hyperparser.
|
| 2 |
+
|
| 3 |
+
Instances of ParseMap are used with str.translate.
|
| 4 |
+
|
| 5 |
+
The following bound search and match functions are defined:
|
| 6 |
+
_synchre - start of popular statement;
|
| 7 |
+
_junkre - whitespace or comment line;
|
| 8 |
+
_match_stringre: string, possibly without closer;
|
| 9 |
+
_itemre - line that may have bracket structure start;
|
| 10 |
+
_closere - line that must be followed by dedent.
|
| 11 |
+
_chew_ordinaryre - non-special characters.
|
| 12 |
+
"""
|
| 13 |
+
import re
|
| 14 |
+
|
| 15 |
+
# Reason last statement is continued (or C_NONE if it's not).
|
| 16 |
+
(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE,
|
| 17 |
+
C_STRING_NEXT_LINES, C_BRACKET) = range(5)
|
| 18 |
+
|
| 19 |
+
# Find what looks like the start of a popular statement.
|
| 20 |
+
|
| 21 |
+
_synchre = re.compile(r"""
|
| 22 |
+
^
|
| 23 |
+
[ \t]*
|
| 24 |
+
(?: while
|
| 25 |
+
| else
|
| 26 |
+
| def
|
| 27 |
+
| return
|
| 28 |
+
| assert
|
| 29 |
+
| break
|
| 30 |
+
| class
|
| 31 |
+
| continue
|
| 32 |
+
| elif
|
| 33 |
+
| try
|
| 34 |
+
| except
|
| 35 |
+
| raise
|
| 36 |
+
| import
|
| 37 |
+
| yield
|
| 38 |
+
)
|
| 39 |
+
\b
|
| 40 |
+
""", re.VERBOSE | re.MULTILINE).search
|
| 41 |
+
|
| 42 |
+
# Match blank line or non-indenting comment line.
|
| 43 |
+
|
| 44 |
+
_junkre = re.compile(r"""
|
| 45 |
+
[ \t]*
|
| 46 |
+
(?: \# \S .* )?
|
| 47 |
+
\n
|
| 48 |
+
""", re.VERBOSE).match
|
| 49 |
+
|
| 50 |
+
# Match any flavor of string; the terminating quote is optional
|
| 51 |
+
# so that we're robust in the face of incomplete program text.
|
| 52 |
+
|
| 53 |
+
_match_stringre = re.compile(r"""
|
| 54 |
+
\""" [^"\\]* (?:
|
| 55 |
+
(?: \\. | "(?!"") )
|
| 56 |
+
[^"\\]*
|
| 57 |
+
)*
|
| 58 |
+
(?: \""" )?
|
| 59 |
+
|
| 60 |
+
| " [^"\\\n]* (?: \\. [^"\\\n]* )* "?
|
| 61 |
+
|
| 62 |
+
| ''' [^'\\]* (?:
|
| 63 |
+
(?: \\. | '(?!'') )
|
| 64 |
+
[^'\\]*
|
| 65 |
+
)*
|
| 66 |
+
(?: ''' )?
|
| 67 |
+
|
| 68 |
+
| ' [^'\\\n]* (?: \\. [^'\\\n]* )* '?
|
| 69 |
+
""", re.VERBOSE | re.DOTALL).match
|
| 70 |
+
|
| 71 |
+
# Match a line that starts with something interesting;
|
| 72 |
+
# used to find the first item of a bracket structure.
|
| 73 |
+
|
| 74 |
+
_itemre = re.compile(r"""
|
| 75 |
+
[ \t]*
|
| 76 |
+
[^\s#\\] # if we match, m.end()-1 is the interesting char
|
| 77 |
+
""", re.VERBOSE).match
|
| 78 |
+
|
| 79 |
+
# Match start of statements that should be followed by a dedent.
|
| 80 |
+
|
| 81 |
+
_closere = re.compile(r"""
|
| 82 |
+
\s*
|
| 83 |
+
(?: return
|
| 84 |
+
| break
|
| 85 |
+
| continue
|
| 86 |
+
| raise
|
| 87 |
+
| pass
|
| 88 |
+
)
|
| 89 |
+
\b
|
| 90 |
+
""", re.VERBOSE).match
|
| 91 |
+
|
| 92 |
+
# Chew up non-special chars as quickly as possible. If match is
|
| 93 |
+
# successful, m.end() less 1 is the index of the last boring char
|
| 94 |
+
# matched. If match is unsuccessful, the string starts with an
|
| 95 |
+
# interesting char.
|
| 96 |
+
|
| 97 |
+
_chew_ordinaryre = re.compile(r"""
|
| 98 |
+
[^[\](){}#'"\\]+
|
| 99 |
+
""", re.VERBOSE).match
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class ParseMap(dict):
|
| 103 |
+
r"""Dict subclass that maps anything not in dict to 'x'.
|
| 104 |
+
|
| 105 |
+
This is designed to be used with str.translate in study1.
|
| 106 |
+
Anything not specifically mapped otherwise becomes 'x'.
|
| 107 |
+
Example: replace everything except whitespace with 'x'.
|
| 108 |
+
|
| 109 |
+
>>> keepwhite = ParseMap((ord(c), ord(c)) for c in ' \t\n\r')
|
| 110 |
+
>>> "a + b\tc\nd".translate(keepwhite)
|
| 111 |
+
'x x x\tx\nx'
|
| 112 |
+
"""
|
| 113 |
+
# Calling this triples access time; see bpo-32940
|
| 114 |
+
def __missing__(self, key):
|
| 115 |
+
return 120 # ord('x')
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# Map all ascii to 120 to avoid __missing__ call, then replace some.
|
| 119 |
+
trans = ParseMap.fromkeys(range(128), 120)
|
| 120 |
+
trans.update((ord(c), ord('(')) for c in "({[") # open brackets => '(';
|
| 121 |
+
trans.update((ord(c), ord(')')) for c in ")}]") # close brackets => ')'.
|
| 122 |
+
trans.update((ord(c), ord(c)) for c in "\"'\\\n#") # Keep these.
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class Parser:
|
| 126 |
+
|
| 127 |
+
def __init__(self, indentwidth, tabwidth):
|
| 128 |
+
self.indentwidth = indentwidth
|
| 129 |
+
self.tabwidth = tabwidth
|
| 130 |
+
|
| 131 |
+
def set_code(self, s):
|
| 132 |
+
assert len(s) == 0 or s[-1] == '\n'
|
| 133 |
+
self.code = s
|
| 134 |
+
self.study_level = 0
|
| 135 |
+
|
| 136 |
+
def find_good_parse_start(self, is_char_in_string):
|
| 137 |
+
"""
|
| 138 |
+
Return index of a good place to begin parsing, as close to the
|
| 139 |
+
end of the string as possible. This will be the start of some
|
| 140 |
+
popular stmt like "if" or "def". Return None if none found:
|
| 141 |
+
the caller should pass more prior context then, if possible, or
|
| 142 |
+
if not (the entire program text up until the point of interest
|
| 143 |
+
has already been tried) pass 0 to set_lo().
|
| 144 |
+
|
| 145 |
+
This will be reliable iff given a reliable is_char_in_string()
|
| 146 |
+
function, meaning that when it says "no", it's absolutely
|
| 147 |
+
guaranteed that the char is not in a string.
|
| 148 |
+
"""
|
| 149 |
+
code, pos = self.code, None
|
| 150 |
+
|
| 151 |
+
# Peek back from the end for a good place to start,
|
| 152 |
+
# but don't try too often; pos will be left None, or
|
| 153 |
+
# bumped to a legitimate synch point.
|
| 154 |
+
limit = len(code)
|
| 155 |
+
for tries in range(5):
|
| 156 |
+
i = code.rfind(":\n", 0, limit)
|
| 157 |
+
if i < 0:
|
| 158 |
+
break
|
| 159 |
+
i = code.rfind('\n', 0, i) + 1 # start of colon line (-1+1=0)
|
| 160 |
+
m = _synchre(code, i, limit)
|
| 161 |
+
if m and not is_char_in_string(m.start()):
|
| 162 |
+
pos = m.start()
|
| 163 |
+
break
|
| 164 |
+
limit = i
|
| 165 |
+
if pos is None:
|
| 166 |
+
# Nothing looks like a block-opener, or stuff does
|
| 167 |
+
# but is_char_in_string keeps returning true; most likely
|
| 168 |
+
# we're in or near a giant string, the colorizer hasn't
|
| 169 |
+
# caught up enough to be helpful, or there simply *aren't*
|
| 170 |
+
# any interesting stmts. In any of these cases we're
|
| 171 |
+
# going to have to parse the whole thing to be sure, so
|
| 172 |
+
# give it one last try from the start, but stop wasting
|
| 173 |
+
# time here regardless of the outcome.
|
| 174 |
+
m = _synchre(code)
|
| 175 |
+
if m and not is_char_in_string(m.start()):
|
| 176 |
+
pos = m.start()
|
| 177 |
+
return pos
|
| 178 |
+
|
| 179 |
+
# Peeking back worked; look forward until _synchre no longer
|
| 180 |
+
# matches.
|
| 181 |
+
i = pos + 1
|
| 182 |
+
while m := _synchre(code, i):
|
| 183 |
+
s, i = m.span()
|
| 184 |
+
if not is_char_in_string(s):
|
| 185 |
+
pos = s
|
| 186 |
+
return pos
|
| 187 |
+
|
| 188 |
+
def set_lo(self, lo):
|
| 189 |
+
""" Throw away the start of the string.
|
| 190 |
+
|
| 191 |
+
Intended to be called with the result of find_good_parse_start().
|
| 192 |
+
"""
|
| 193 |
+
assert lo == 0 or self.code[lo-1] == '\n'
|
| 194 |
+
if lo > 0:
|
| 195 |
+
self.code = self.code[lo:]
|
| 196 |
+
|
| 197 |
+
def _study1(self):
|
| 198 |
+
"""Find the line numbers of non-continuation lines.
|
| 199 |
+
|
| 200 |
+
As quickly as humanly possible <wink>, find the line numbers (0-
|
| 201 |
+
based) of the non-continuation lines.
|
| 202 |
+
Creates self.{goodlines, continuation}.
|
| 203 |
+
"""
|
| 204 |
+
if self.study_level >= 1:
|
| 205 |
+
return
|
| 206 |
+
self.study_level = 1
|
| 207 |
+
|
| 208 |
+
# Map all uninteresting characters to "x", all open brackets
|
| 209 |
+
# to "(", all close brackets to ")", then collapse runs of
|
| 210 |
+
# uninteresting characters. This can cut the number of chars
|
| 211 |
+
# by a factor of 10-40, and so greatly speed the following loop.
|
| 212 |
+
code = self.code
|
| 213 |
+
code = code.translate(trans)
|
| 214 |
+
code = code.replace('xxxxxxxx', 'x')
|
| 215 |
+
code = code.replace('xxxx', 'x')
|
| 216 |
+
code = code.replace('xx', 'x')
|
| 217 |
+
code = code.replace('xx', 'x')
|
| 218 |
+
code = code.replace('\nx', '\n')
|
| 219 |
+
# Replacing x\n with \n would be incorrect because
|
| 220 |
+
# x may be preceded by a backslash.
|
| 221 |
+
|
| 222 |
+
# March over the squashed version of the program, accumulating
|
| 223 |
+
# the line numbers of non-continued stmts, and determining
|
| 224 |
+
# whether & why the last stmt is a continuation.
|
| 225 |
+
continuation = C_NONE
|
| 226 |
+
level = lno = 0 # level is nesting level; lno is line number
|
| 227 |
+
self.goodlines = goodlines = [0]
|
| 228 |
+
push_good = goodlines.append
|
| 229 |
+
i, n = 0, len(code)
|
| 230 |
+
while i < n:
|
| 231 |
+
ch = code[i]
|
| 232 |
+
i = i+1
|
| 233 |
+
|
| 234 |
+
# cases are checked in decreasing order of frequency
|
| 235 |
+
if ch == 'x':
|
| 236 |
+
continue
|
| 237 |
+
|
| 238 |
+
if ch == '\n':
|
| 239 |
+
lno = lno + 1
|
| 240 |
+
if level == 0:
|
| 241 |
+
push_good(lno)
|
| 242 |
+
# else we're in an unclosed bracket structure
|
| 243 |
+
continue
|
| 244 |
+
|
| 245 |
+
if ch == '(':
|
| 246 |
+
level = level + 1
|
| 247 |
+
continue
|
| 248 |
+
|
| 249 |
+
if ch == ')':
|
| 250 |
+
if level:
|
| 251 |
+
level = level - 1
|
| 252 |
+
# else the program is invalid, but we can't complain
|
| 253 |
+
continue
|
| 254 |
+
|
| 255 |
+
if ch == '"' or ch == "'":
|
| 256 |
+
# consume the string
|
| 257 |
+
quote = ch
|
| 258 |
+
if code[i-1:i+2] == quote * 3:
|
| 259 |
+
quote = quote * 3
|
| 260 |
+
firstlno = lno
|
| 261 |
+
w = len(quote) - 1
|
| 262 |
+
i = i+w
|
| 263 |
+
while i < n:
|
| 264 |
+
ch = code[i]
|
| 265 |
+
i = i+1
|
| 266 |
+
|
| 267 |
+
if ch == 'x':
|
| 268 |
+
continue
|
| 269 |
+
|
| 270 |
+
if code[i-1:i+w] == quote:
|
| 271 |
+
i = i+w
|
| 272 |
+
break
|
| 273 |
+
|
| 274 |
+
if ch == '\n':
|
| 275 |
+
lno = lno + 1
|
| 276 |
+
if w == 0:
|
| 277 |
+
# unterminated single-quoted string
|
| 278 |
+
if level == 0:
|
| 279 |
+
push_good(lno)
|
| 280 |
+
break
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
if ch == '\\':
|
| 284 |
+
assert i < n
|
| 285 |
+
if code[i] == '\n':
|
| 286 |
+
lno = lno + 1
|
| 287 |
+
i = i+1
|
| 288 |
+
continue
|
| 289 |
+
|
| 290 |
+
# else comment char or paren inside string
|
| 291 |
+
|
| 292 |
+
else:
|
| 293 |
+
# didn't break out of the loop, so we're still
|
| 294 |
+
# inside a string
|
| 295 |
+
if (lno - 1) == firstlno:
|
| 296 |
+
# before the previous \n in code, we were in the first
|
| 297 |
+
# line of the string
|
| 298 |
+
continuation = C_STRING_FIRST_LINE
|
| 299 |
+
else:
|
| 300 |
+
continuation = C_STRING_NEXT_LINES
|
| 301 |
+
continue # with outer loop
|
| 302 |
+
|
| 303 |
+
if ch == '#':
|
| 304 |
+
# consume the comment
|
| 305 |
+
i = code.find('\n', i)
|
| 306 |
+
assert i >= 0
|
| 307 |
+
continue
|
| 308 |
+
|
| 309 |
+
assert ch == '\\'
|
| 310 |
+
assert i < n
|
| 311 |
+
if code[i] == '\n':
|
| 312 |
+
lno = lno + 1
|
| 313 |
+
if i+1 == n:
|
| 314 |
+
continuation = C_BACKSLASH
|
| 315 |
+
i = i+1
|
| 316 |
+
|
| 317 |
+
# The last stmt may be continued for all 3 reasons.
|
| 318 |
+
# String continuation takes precedence over bracket
|
| 319 |
+
# continuation, which beats backslash continuation.
|
| 320 |
+
if (continuation != C_STRING_FIRST_LINE
|
| 321 |
+
and continuation != C_STRING_NEXT_LINES and level > 0):
|
| 322 |
+
continuation = C_BRACKET
|
| 323 |
+
self.continuation = continuation
|
| 324 |
+
|
| 325 |
+
# Push the final line number as a sentinel value, regardless of
|
| 326 |
+
# whether it's continued.
|
| 327 |
+
assert (continuation == C_NONE) == (goodlines[-1] == lno)
|
| 328 |
+
if goodlines[-1] != lno:
|
| 329 |
+
push_good(lno)
|
| 330 |
+
|
| 331 |
+
def get_continuation_type(self):
|
| 332 |
+
self._study1()
|
| 333 |
+
return self.continuation
|
| 334 |
+
|
| 335 |
+
def _study2(self):
|
| 336 |
+
"""
|
| 337 |
+
study1 was sufficient to determine the continuation status,
|
| 338 |
+
but doing more requires looking at every character. study2
|
| 339 |
+
does this for the last interesting statement in the block.
|
| 340 |
+
Creates:
|
| 341 |
+
self.stmt_start, stmt_end
|
| 342 |
+
slice indices of last interesting stmt
|
| 343 |
+
self.stmt_bracketing
|
| 344 |
+
the bracketing structure of the last interesting stmt; for
|
| 345 |
+
example, for the statement "say(boo) or die",
|
| 346 |
+
stmt_bracketing will be ((0, 0), (0, 1), (2, 0), (2, 1),
|
| 347 |
+
(4, 0)). Strings and comments are treated as brackets, for
|
| 348 |
+
the matter.
|
| 349 |
+
self.lastch
|
| 350 |
+
last interesting character before optional trailing comment
|
| 351 |
+
self.lastopenbracketpos
|
| 352 |
+
if continuation is C_BRACKET, index of last open bracket
|
| 353 |
+
"""
|
| 354 |
+
if self.study_level >= 2:
|
| 355 |
+
return
|
| 356 |
+
self._study1()
|
| 357 |
+
self.study_level = 2
|
| 358 |
+
|
| 359 |
+
# Set p and q to slice indices of last interesting stmt.
|
| 360 |
+
code, goodlines = self.code, self.goodlines
|
| 361 |
+
i = len(goodlines) - 1 # Index of newest line.
|
| 362 |
+
p = len(code) # End of goodlines[i]
|
| 363 |
+
while i:
|
| 364 |
+
assert p
|
| 365 |
+
# Make p be the index of the stmt at line number goodlines[i].
|
| 366 |
+
# Move p back to the stmt at line number goodlines[i-1].
|
| 367 |
+
q = p
|
| 368 |
+
for nothing in range(goodlines[i-1], goodlines[i]):
|
| 369 |
+
# tricky: sets p to 0 if no preceding newline
|
| 370 |
+
p = code.rfind('\n', 0, p-1) + 1
|
| 371 |
+
# The stmt code[p:q] isn't a continuation, but may be blank
|
| 372 |
+
# or a non-indenting comment line.
|
| 373 |
+
if _junkre(code, p):
|
| 374 |
+
i = i-1
|
| 375 |
+
else:
|
| 376 |
+
break
|
| 377 |
+
if i == 0:
|
| 378 |
+
# nothing but junk!
|
| 379 |
+
assert p == 0
|
| 380 |
+
q = p
|
| 381 |
+
self.stmt_start, self.stmt_end = p, q
|
| 382 |
+
|
| 383 |
+
# Analyze this stmt, to find the last open bracket (if any)
|
| 384 |
+
# and last interesting character (if any).
|
| 385 |
+
lastch = ""
|
| 386 |
+
stack = [] # stack of open bracket indices
|
| 387 |
+
push_stack = stack.append
|
| 388 |
+
bracketing = [(p, 0)]
|
| 389 |
+
while p < q:
|
| 390 |
+
# suck up all except ()[]{}'"#\\
|
| 391 |
+
m = _chew_ordinaryre(code, p, q)
|
| 392 |
+
if m:
|
| 393 |
+
# we skipped at least one boring char
|
| 394 |
+
newp = m.end()
|
| 395 |
+
# back up over totally boring whitespace
|
| 396 |
+
i = newp - 1 # index of last boring char
|
| 397 |
+
while i >= p and code[i] in " \t\n":
|
| 398 |
+
i = i-1
|
| 399 |
+
if i >= p:
|
| 400 |
+
lastch = code[i]
|
| 401 |
+
p = newp
|
| 402 |
+
if p >= q:
|
| 403 |
+
break
|
| 404 |
+
|
| 405 |
+
ch = code[p]
|
| 406 |
+
|
| 407 |
+
if ch in "([{":
|
| 408 |
+
push_stack(p)
|
| 409 |
+
bracketing.append((p, len(stack)))
|
| 410 |
+
lastch = ch
|
| 411 |
+
p = p+1
|
| 412 |
+
continue
|
| 413 |
+
|
| 414 |
+
if ch in ")]}":
|
| 415 |
+
if stack:
|
| 416 |
+
del stack[-1]
|
| 417 |
+
lastch = ch
|
| 418 |
+
p = p+1
|
| 419 |
+
bracketing.append((p, len(stack)))
|
| 420 |
+
continue
|
| 421 |
+
|
| 422 |
+
if ch == '"' or ch == "'":
|
| 423 |
+
# consume string
|
| 424 |
+
# Note that study1 did this with a Python loop, but
|
| 425 |
+
# we use a regexp here; the reason is speed in both
|
| 426 |
+
# cases; the string may be huge, but study1 pre-squashed
|
| 427 |
+
# strings to a couple of characters per line. study1
|
| 428 |
+
# also needed to keep track of newlines, and we don't
|
| 429 |
+
# have to.
|
| 430 |
+
bracketing.append((p, len(stack)+1))
|
| 431 |
+
lastch = ch
|
| 432 |
+
p = _match_stringre(code, p, q).end()
|
| 433 |
+
bracketing.append((p, len(stack)))
|
| 434 |
+
continue
|
| 435 |
+
|
| 436 |
+
if ch == '#':
|
| 437 |
+
# consume comment and trailing newline
|
| 438 |
+
bracketing.append((p, len(stack)+1))
|
| 439 |
+
p = code.find('\n', p, q) + 1
|
| 440 |
+
assert p > 0
|
| 441 |
+
bracketing.append((p, len(stack)))
|
| 442 |
+
continue
|
| 443 |
+
|
| 444 |
+
assert ch == '\\'
|
| 445 |
+
p = p+1 # beyond backslash
|
| 446 |
+
assert p < q
|
| 447 |
+
if code[p] != '\n':
|
| 448 |
+
# the program is invalid, but can't complain
|
| 449 |
+
lastch = ch + code[p]
|
| 450 |
+
p = p+1 # beyond escaped char
|
| 451 |
+
|
| 452 |
+
# end while p < q:
|
| 453 |
+
|
| 454 |
+
self.lastch = lastch
|
| 455 |
+
self.lastopenbracketpos = stack[-1] if stack else None
|
| 456 |
+
self.stmt_bracketing = tuple(bracketing)
|
| 457 |
+
|
| 458 |
+
def compute_bracket_indent(self):
|
| 459 |
+
"""Return number of spaces the next line should be indented.
|
| 460 |
+
|
| 461 |
+
Line continuation must be C_BRACKET.
|
| 462 |
+
"""
|
| 463 |
+
self._study2()
|
| 464 |
+
assert self.continuation == C_BRACKET
|
| 465 |
+
j = self.lastopenbracketpos
|
| 466 |
+
code = self.code
|
| 467 |
+
n = len(code)
|
| 468 |
+
origi = i = code.rfind('\n', 0, j) + 1
|
| 469 |
+
j = j+1 # one beyond open bracket
|
| 470 |
+
# find first list item; set i to start of its line
|
| 471 |
+
while j < n:
|
| 472 |
+
m = _itemre(code, j)
|
| 473 |
+
if m:
|
| 474 |
+
j = m.end() - 1 # index of first interesting char
|
| 475 |
+
extra = 0
|
| 476 |
+
break
|
| 477 |
+
else:
|
| 478 |
+
# this line is junk; advance to next line
|
| 479 |
+
i = j = code.find('\n', j) + 1
|
| 480 |
+
else:
|
| 481 |
+
# nothing interesting follows the bracket;
|
| 482 |
+
# reproduce the bracket line's indentation + a level
|
| 483 |
+
j = i = origi
|
| 484 |
+
while code[j] in " \t":
|
| 485 |
+
j = j+1
|
| 486 |
+
extra = self.indentwidth
|
| 487 |
+
return len(code[i:j].expandtabs(self.tabwidth)) + extra
|
| 488 |
+
|
| 489 |
+
def get_num_lines_in_stmt(self):
|
| 490 |
+
"""Return number of physical lines in last stmt.
|
| 491 |
+
|
| 492 |
+
The statement doesn't have to be an interesting statement. This is
|
| 493 |
+
intended to be called when continuation is C_BACKSLASH.
|
| 494 |
+
"""
|
| 495 |
+
self._study1()
|
| 496 |
+
goodlines = self.goodlines
|
| 497 |
+
return goodlines[-1] - goodlines[-2]
|
| 498 |
+
|
| 499 |
+
def compute_backslash_indent(self):
|
| 500 |
+
"""Return number of spaces the next line should be indented.
|
| 501 |
+
|
| 502 |
+
Line continuation must be C_BACKSLASH. Also assume that the new
|
| 503 |
+
line is the first one following the initial line of the stmt.
|
| 504 |
+
"""
|
| 505 |
+
self._study2()
|
| 506 |
+
assert self.continuation == C_BACKSLASH
|
| 507 |
+
code = self.code
|
| 508 |
+
i = self.stmt_start
|
| 509 |
+
while code[i] in " \t":
|
| 510 |
+
i = i+1
|
| 511 |
+
startpos = i
|
| 512 |
+
|
| 513 |
+
# See whether the initial line starts an assignment stmt; i.e.,
|
| 514 |
+
# look for an = operator
|
| 515 |
+
endpos = code.find('\n', startpos) + 1
|
| 516 |
+
found = level = 0
|
| 517 |
+
while i < endpos:
|
| 518 |
+
ch = code[i]
|
| 519 |
+
if ch in "([{":
|
| 520 |
+
level = level + 1
|
| 521 |
+
i = i+1
|
| 522 |
+
elif ch in ")]}":
|
| 523 |
+
if level:
|
| 524 |
+
level = level - 1
|
| 525 |
+
i = i+1
|
| 526 |
+
elif ch == '"' or ch == "'":
|
| 527 |
+
i = _match_stringre(code, i, endpos).end()
|
| 528 |
+
elif ch == '#':
|
| 529 |
+
# This line is unreachable because the # makes a comment of
|
| 530 |
+
# everything after it.
|
| 531 |
+
break
|
| 532 |
+
elif level == 0 and ch == '=' and \
|
| 533 |
+
(i == 0 or code[i-1] not in "=<>!") and \
|
| 534 |
+
code[i+1] != '=':
|
| 535 |
+
found = 1
|
| 536 |
+
break
|
| 537 |
+
else:
|
| 538 |
+
i = i+1
|
| 539 |
+
|
| 540 |
+
if found:
|
| 541 |
+
# found a legit =, but it may be the last interesting
|
| 542 |
+
# thing on the line
|
| 543 |
+
i = i+1 # move beyond the =
|
| 544 |
+
found = re.match(r"\s*\\", code[i:endpos]) is None
|
| 545 |
+
|
| 546 |
+
if not found:
|
| 547 |
+
# oh well ... settle for moving beyond the first chunk
|
| 548 |
+
# of non-whitespace chars
|
| 549 |
+
i = startpos
|
| 550 |
+
while code[i] not in " \t\n":
|
| 551 |
+
i = i+1
|
| 552 |
+
|
| 553 |
+
return len(code[self.stmt_start:i].expandtabs(\
|
| 554 |
+
self.tabwidth)) + 1
|
| 555 |
+
|
| 556 |
+
def get_base_indent_string(self):
|
| 557 |
+
"""Return the leading whitespace on the initial line of the last
|
| 558 |
+
interesting stmt.
|
| 559 |
+
"""
|
| 560 |
+
self._study2()
|
| 561 |
+
i, n = self.stmt_start, self.stmt_end
|
| 562 |
+
j = i
|
| 563 |
+
code = self.code
|
| 564 |
+
while j < n and code[j] in " \t":
|
| 565 |
+
j = j + 1
|
| 566 |
+
return code[i:j]
|
| 567 |
+
|
| 568 |
+
def is_block_opener(self):
|
| 569 |
+
"Return True if the last interesting statement opens a block."
|
| 570 |
+
self._study2()
|
| 571 |
+
return self.lastch == ':'
|
| 572 |
+
|
| 573 |
+
def is_block_closer(self):
|
| 574 |
+
"Return True if the last interesting statement closes a block."
|
| 575 |
+
self._study2()
|
| 576 |
+
return _closere(self.code, self.stmt_start) is not None
|
| 577 |
+
|
| 578 |
+
def get_last_stmt_bracketing(self):
|
| 579 |
+
"""Return bracketing structure of the last interesting statement.
|
| 580 |
+
|
| 581 |
+
The returned tuple is in the format defined in _study2().
|
| 582 |
+
"""
|
| 583 |
+
self._study2()
|
| 584 |
+
return self.stmt_bracketing
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
if __name__ == '__main__':
|
| 588 |
+
from unittest import main
|
| 589 |
+
main('idlelib.idle_test.test_pyparse', verbosity=2)
|
parrot/lib/python3.10/idlelib/pyshell.py
ADDED
|
@@ -0,0 +1,1713 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 == "__main__":
|
| 5 |
+
sys.modules['idlelib.pyshell'] = sys.modules['__main__']
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
from tkinter import *
|
| 9 |
+
except ImportError:
|
| 10 |
+
print("** IDLE can't import Tkinter.\n"
|
| 11 |
+
"Your Python may not be configured for Tk. **", file=sys.__stderr__)
|
| 12 |
+
raise SystemExit(1)
|
| 13 |
+
|
| 14 |
+
# Valid arguments for the ...Awareness call below are defined in the following.
|
| 15 |
+
# https://msdn.microsoft.com/en-us/library/windows/desktop/dn280512(v=vs.85).aspx
|
| 16 |
+
if sys.platform == 'win32':
|
| 17 |
+
try:
|
| 18 |
+
import ctypes
|
| 19 |
+
PROCESS_SYSTEM_DPI_AWARE = 1 # Int required.
|
| 20 |
+
ctypes.OleDLL('shcore').SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE)
|
| 21 |
+
except (ImportError, AttributeError, OSError):
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
from tkinter import messagebox
|
| 25 |
+
if TkVersion < 8.5:
|
| 26 |
+
root = Tk() # otherwise create root in main
|
| 27 |
+
root.withdraw()
|
| 28 |
+
from idlelib.run import fix_scaling
|
| 29 |
+
fix_scaling(root)
|
| 30 |
+
messagebox.showerror("Idle Cannot Start",
|
| 31 |
+
"Idle requires tcl/tk 8.5+, not %s." % TkVersion,
|
| 32 |
+
parent=root)
|
| 33 |
+
raise SystemExit(1)
|
| 34 |
+
|
| 35 |
+
from code import InteractiveInterpreter
|
| 36 |
+
import itertools
|
| 37 |
+
import linecache
|
| 38 |
+
import os
|
| 39 |
+
import os.path
|
| 40 |
+
from platform import python_version
|
| 41 |
+
import re
|
| 42 |
+
import socket
|
| 43 |
+
import subprocess
|
| 44 |
+
from textwrap import TextWrapper
|
| 45 |
+
import threading
|
| 46 |
+
import time
|
| 47 |
+
import tokenize
|
| 48 |
+
import warnings
|
| 49 |
+
|
| 50 |
+
from idlelib.colorizer import ColorDelegator
|
| 51 |
+
from idlelib.config import idleConf
|
| 52 |
+
from idlelib.delegator import Delegator
|
| 53 |
+
from idlelib import debugger
|
| 54 |
+
from idlelib import debugger_r
|
| 55 |
+
from idlelib.editor import EditorWindow, fixwordbreaks
|
| 56 |
+
from idlelib.filelist import FileList
|
| 57 |
+
from idlelib.outwin import OutputWindow
|
| 58 |
+
from idlelib import replace
|
| 59 |
+
from idlelib import rpc
|
| 60 |
+
from idlelib.run import idle_formatwarning, StdInputFile, StdOutputFile
|
| 61 |
+
from idlelib.undo import UndoDelegator
|
| 62 |
+
|
| 63 |
+
# Default for testing; defaults to True in main() for running.
|
| 64 |
+
use_subprocess = False
|
| 65 |
+
|
| 66 |
+
HOST = '127.0.0.1' # python execution server on localhost loopback
|
| 67 |
+
PORT = 0 # someday pass in host, port for remote debug capability
|
| 68 |
+
|
| 69 |
+
try: # In case IDLE started with -n.
|
| 70 |
+
eof = 'Ctrl-D (end-of-file)'
|
| 71 |
+
exit.eof = eof
|
| 72 |
+
quit.eof = eof
|
| 73 |
+
except NameError: # In case python started with -S.
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
# Override warnings module to write to warning_stream. Initialize to send IDLE
|
| 77 |
+
# internal warnings to the console. ScriptBinding.check_syntax() will
|
| 78 |
+
# temporarily redirect the stream to the shell window to display warnings when
|
| 79 |
+
# checking user's code.
|
| 80 |
+
warning_stream = sys.__stderr__ # None, at least on Windows, if no console.
|
| 81 |
+
|
| 82 |
+
def idle_showwarning(
|
| 83 |
+
message, category, filename, lineno, file=None, line=None):
|
| 84 |
+
"""Show Idle-format warning (after replacing warnings.showwarning).
|
| 85 |
+
|
| 86 |
+
The differences are the formatter called, the file=None replacement,
|
| 87 |
+
which can be None, the capture of the consequence AttributeError,
|
| 88 |
+
and the output of a hard-coded prompt.
|
| 89 |
+
"""
|
| 90 |
+
if file is None:
|
| 91 |
+
file = warning_stream
|
| 92 |
+
try:
|
| 93 |
+
file.write(idle_formatwarning(
|
| 94 |
+
message, category, filename, lineno, line=line))
|
| 95 |
+
file.write(">>> ")
|
| 96 |
+
except (AttributeError, OSError):
|
| 97 |
+
pass # if file (probably __stderr__) is invalid, skip warning.
|
| 98 |
+
|
| 99 |
+
_warnings_showwarning = None
|
| 100 |
+
|
| 101 |
+
def capture_warnings(capture):
|
| 102 |
+
"Replace warning.showwarning with idle_showwarning, or reverse."
|
| 103 |
+
|
| 104 |
+
global _warnings_showwarning
|
| 105 |
+
if capture:
|
| 106 |
+
if _warnings_showwarning is None:
|
| 107 |
+
_warnings_showwarning = warnings.showwarning
|
| 108 |
+
warnings.showwarning = idle_showwarning
|
| 109 |
+
else:
|
| 110 |
+
if _warnings_showwarning is not None:
|
| 111 |
+
warnings.showwarning = _warnings_showwarning
|
| 112 |
+
_warnings_showwarning = None
|
| 113 |
+
|
| 114 |
+
capture_warnings(True)
|
| 115 |
+
|
| 116 |
+
def extended_linecache_checkcache(filename=None,
|
| 117 |
+
orig_checkcache=linecache.checkcache):
|
| 118 |
+
"""Extend linecache.checkcache to preserve the <pyshell#...> entries
|
| 119 |
+
|
| 120 |
+
Rather than repeating the linecache code, patch it to save the
|
| 121 |
+
<pyshell#...> entries, call the original linecache.checkcache()
|
| 122 |
+
(skipping them), and then restore the saved entries.
|
| 123 |
+
|
| 124 |
+
orig_checkcache is bound at definition time to the original
|
| 125 |
+
method, allowing it to be patched.
|
| 126 |
+
"""
|
| 127 |
+
cache = linecache.cache
|
| 128 |
+
save = {}
|
| 129 |
+
for key in list(cache):
|
| 130 |
+
if key[:1] + key[-1:] == '<>':
|
| 131 |
+
save[key] = cache.pop(key)
|
| 132 |
+
orig_checkcache(filename)
|
| 133 |
+
cache.update(save)
|
| 134 |
+
|
| 135 |
+
# Patch linecache.checkcache():
|
| 136 |
+
linecache.checkcache = extended_linecache_checkcache
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class PyShellEditorWindow(EditorWindow):
|
| 140 |
+
"Regular text edit window in IDLE, supports breakpoints"
|
| 141 |
+
|
| 142 |
+
def __init__(self, *args):
|
| 143 |
+
self.breakpoints = []
|
| 144 |
+
EditorWindow.__init__(self, *args)
|
| 145 |
+
self.text.bind("<<set-breakpoint-here>>", self.set_breakpoint_here)
|
| 146 |
+
self.text.bind("<<clear-breakpoint-here>>", self.clear_breakpoint_here)
|
| 147 |
+
self.text.bind("<<open-python-shell>>", self.flist.open_shell)
|
| 148 |
+
|
| 149 |
+
#TODO: don't read/write this from/to .idlerc when testing
|
| 150 |
+
self.breakpointPath = os.path.join(
|
| 151 |
+
idleConf.userdir, 'breakpoints.lst')
|
| 152 |
+
# whenever a file is changed, restore breakpoints
|
| 153 |
+
def filename_changed_hook(old_hook=self.io.filename_change_hook,
|
| 154 |
+
self=self):
|
| 155 |
+
self.restore_file_breaks()
|
| 156 |
+
old_hook()
|
| 157 |
+
self.io.set_filename_change_hook(filename_changed_hook)
|
| 158 |
+
if self.io.filename:
|
| 159 |
+
self.restore_file_breaks()
|
| 160 |
+
self.color_breakpoint_text()
|
| 161 |
+
|
| 162 |
+
rmenu_specs = [
|
| 163 |
+
("Cut", "<<cut>>", "rmenu_check_cut"),
|
| 164 |
+
("Copy", "<<copy>>", "rmenu_check_copy"),
|
| 165 |
+
("Paste", "<<paste>>", "rmenu_check_paste"),
|
| 166 |
+
(None, None, None),
|
| 167 |
+
("Set Breakpoint", "<<set-breakpoint-here>>", None),
|
| 168 |
+
("Clear Breakpoint", "<<clear-breakpoint-here>>", None)
|
| 169 |
+
]
|
| 170 |
+
|
| 171 |
+
def color_breakpoint_text(self, color=True):
|
| 172 |
+
"Turn colorizing of breakpoint text on or off"
|
| 173 |
+
if self.io is None:
|
| 174 |
+
# possible due to update in restore_file_breaks
|
| 175 |
+
return
|
| 176 |
+
if color:
|
| 177 |
+
theme = idleConf.CurrentTheme()
|
| 178 |
+
cfg = idleConf.GetHighlight(theme, "break")
|
| 179 |
+
else:
|
| 180 |
+
cfg = {'foreground': '', 'background': ''}
|
| 181 |
+
self.text.tag_config('BREAK', cfg)
|
| 182 |
+
|
| 183 |
+
def set_breakpoint(self, lineno):
|
| 184 |
+
text = self.text
|
| 185 |
+
filename = self.io.filename
|
| 186 |
+
text.tag_add("BREAK", "%d.0" % lineno, "%d.0" % (lineno+1))
|
| 187 |
+
try:
|
| 188 |
+
self.breakpoints.index(lineno)
|
| 189 |
+
except ValueError: # only add if missing, i.e. do once
|
| 190 |
+
self.breakpoints.append(lineno)
|
| 191 |
+
try: # update the subprocess debugger
|
| 192 |
+
debug = self.flist.pyshell.interp.debugger
|
| 193 |
+
debug.set_breakpoint_here(filename, lineno)
|
| 194 |
+
except: # but debugger may not be active right now....
|
| 195 |
+
pass
|
| 196 |
+
|
| 197 |
+
def set_breakpoint_here(self, event=None):
|
| 198 |
+
text = self.text
|
| 199 |
+
filename = self.io.filename
|
| 200 |
+
if not filename:
|
| 201 |
+
text.bell()
|
| 202 |
+
return
|
| 203 |
+
lineno = int(float(text.index("insert")))
|
| 204 |
+
self.set_breakpoint(lineno)
|
| 205 |
+
|
| 206 |
+
def clear_breakpoint_here(self, event=None):
|
| 207 |
+
text = self.text
|
| 208 |
+
filename = self.io.filename
|
| 209 |
+
if not filename:
|
| 210 |
+
text.bell()
|
| 211 |
+
return
|
| 212 |
+
lineno = int(float(text.index("insert")))
|
| 213 |
+
try:
|
| 214 |
+
self.breakpoints.remove(lineno)
|
| 215 |
+
except:
|
| 216 |
+
pass
|
| 217 |
+
text.tag_remove("BREAK", "insert linestart",\
|
| 218 |
+
"insert lineend +1char")
|
| 219 |
+
try:
|
| 220 |
+
debug = self.flist.pyshell.interp.debugger
|
| 221 |
+
debug.clear_breakpoint_here(filename, lineno)
|
| 222 |
+
except:
|
| 223 |
+
pass
|
| 224 |
+
|
| 225 |
+
def clear_file_breaks(self):
|
| 226 |
+
if self.breakpoints:
|
| 227 |
+
text = self.text
|
| 228 |
+
filename = self.io.filename
|
| 229 |
+
if not filename:
|
| 230 |
+
text.bell()
|
| 231 |
+
return
|
| 232 |
+
self.breakpoints = []
|
| 233 |
+
text.tag_remove("BREAK", "1.0", END)
|
| 234 |
+
try:
|
| 235 |
+
debug = self.flist.pyshell.interp.debugger
|
| 236 |
+
debug.clear_file_breaks(filename)
|
| 237 |
+
except:
|
| 238 |
+
pass
|
| 239 |
+
|
| 240 |
+
def store_file_breaks(self):
|
| 241 |
+
"Save breakpoints when file is saved"
|
| 242 |
+
# XXX 13 Dec 2002 KBK Currently the file must be saved before it can
|
| 243 |
+
# be run. The breaks are saved at that time. If we introduce
|
| 244 |
+
# a temporary file save feature the save breaks functionality
|
| 245 |
+
# needs to be re-verified, since the breaks at the time the
|
| 246 |
+
# temp file is created may differ from the breaks at the last
|
| 247 |
+
# permanent save of the file. Currently, a break introduced
|
| 248 |
+
# after a save will be effective, but not persistent.
|
| 249 |
+
# This is necessary to keep the saved breaks synched with the
|
| 250 |
+
# saved file.
|
| 251 |
+
#
|
| 252 |
+
# Breakpoints are set as tagged ranges in the text.
|
| 253 |
+
# Since a modified file has to be saved before it is
|
| 254 |
+
# run, and since self.breakpoints (from which the subprocess
|
| 255 |
+
# debugger is loaded) is updated during the save, the visible
|
| 256 |
+
# breaks stay synched with the subprocess even if one of these
|
| 257 |
+
# unexpected breakpoint deletions occurs.
|
| 258 |
+
breaks = self.breakpoints
|
| 259 |
+
filename = self.io.filename
|
| 260 |
+
try:
|
| 261 |
+
with open(self.breakpointPath, "r") as fp:
|
| 262 |
+
lines = fp.readlines()
|
| 263 |
+
except OSError:
|
| 264 |
+
lines = []
|
| 265 |
+
try:
|
| 266 |
+
with open(self.breakpointPath, "w") as new_file:
|
| 267 |
+
for line in lines:
|
| 268 |
+
if not line.startswith(filename + '='):
|
| 269 |
+
new_file.write(line)
|
| 270 |
+
self.update_breakpoints()
|
| 271 |
+
breaks = self.breakpoints
|
| 272 |
+
if breaks:
|
| 273 |
+
new_file.write(filename + '=' + str(breaks) + '\n')
|
| 274 |
+
except OSError as err:
|
| 275 |
+
if not getattr(self.root, "breakpoint_error_displayed", False):
|
| 276 |
+
self.root.breakpoint_error_displayed = True
|
| 277 |
+
messagebox.showerror(title='IDLE Error',
|
| 278 |
+
message='Unable to update breakpoint list:\n%s'
|
| 279 |
+
% str(err),
|
| 280 |
+
parent=self.text)
|
| 281 |
+
|
| 282 |
+
def restore_file_breaks(self):
|
| 283 |
+
self.text.update() # this enables setting "BREAK" tags to be visible
|
| 284 |
+
if self.io is None:
|
| 285 |
+
# can happen if IDLE closes due to the .update() call
|
| 286 |
+
return
|
| 287 |
+
filename = self.io.filename
|
| 288 |
+
if filename is None:
|
| 289 |
+
return
|
| 290 |
+
if os.path.isfile(self.breakpointPath):
|
| 291 |
+
with open(self.breakpointPath, "r") as fp:
|
| 292 |
+
lines = fp.readlines()
|
| 293 |
+
for line in lines:
|
| 294 |
+
if line.startswith(filename + '='):
|
| 295 |
+
breakpoint_linenumbers = eval(line[len(filename)+1:])
|
| 296 |
+
for breakpoint_linenumber in breakpoint_linenumbers:
|
| 297 |
+
self.set_breakpoint(breakpoint_linenumber)
|
| 298 |
+
|
| 299 |
+
def update_breakpoints(self):
|
| 300 |
+
"Retrieves all the breakpoints in the current window"
|
| 301 |
+
text = self.text
|
| 302 |
+
ranges = text.tag_ranges("BREAK")
|
| 303 |
+
linenumber_list = self.ranges_to_linenumbers(ranges)
|
| 304 |
+
self.breakpoints = linenumber_list
|
| 305 |
+
|
| 306 |
+
def ranges_to_linenumbers(self, ranges):
|
| 307 |
+
lines = []
|
| 308 |
+
for index in range(0, len(ranges), 2):
|
| 309 |
+
lineno = int(float(ranges[index].string))
|
| 310 |
+
end = int(float(ranges[index+1].string))
|
| 311 |
+
while lineno < end:
|
| 312 |
+
lines.append(lineno)
|
| 313 |
+
lineno += 1
|
| 314 |
+
return lines
|
| 315 |
+
|
| 316 |
+
# XXX 13 Dec 2002 KBK Not used currently
|
| 317 |
+
# def saved_change_hook(self):
|
| 318 |
+
# "Extend base method - clear breaks if module is modified"
|
| 319 |
+
# if not self.get_saved():
|
| 320 |
+
# self.clear_file_breaks()
|
| 321 |
+
# EditorWindow.saved_change_hook(self)
|
| 322 |
+
|
| 323 |
+
def _close(self):
|
| 324 |
+
"Extend base method - clear breaks when module is closed"
|
| 325 |
+
self.clear_file_breaks()
|
| 326 |
+
EditorWindow._close(self)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
class PyShellFileList(FileList):
|
| 330 |
+
"Extend base class: IDLE supports a shell and breakpoints"
|
| 331 |
+
|
| 332 |
+
# override FileList's class variable, instances return PyShellEditorWindow
|
| 333 |
+
# instead of EditorWindow when new edit windows are created.
|
| 334 |
+
EditorWindow = PyShellEditorWindow
|
| 335 |
+
|
| 336 |
+
pyshell = None
|
| 337 |
+
|
| 338 |
+
def open_shell(self, event=None):
|
| 339 |
+
if self.pyshell:
|
| 340 |
+
self.pyshell.top.wakeup()
|
| 341 |
+
else:
|
| 342 |
+
self.pyshell = PyShell(self)
|
| 343 |
+
if self.pyshell:
|
| 344 |
+
if not self.pyshell.begin():
|
| 345 |
+
return None
|
| 346 |
+
return self.pyshell
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class ModifiedColorDelegator(ColorDelegator):
|
| 350 |
+
"Extend base class: colorizer for the shell window itself"
|
| 351 |
+
def recolorize_main(self):
|
| 352 |
+
self.tag_remove("TODO", "1.0", "iomark")
|
| 353 |
+
self.tag_add("SYNC", "1.0", "iomark")
|
| 354 |
+
ColorDelegator.recolorize_main(self)
|
| 355 |
+
|
| 356 |
+
def removecolors(self):
|
| 357 |
+
# Don't remove shell color tags before "iomark"
|
| 358 |
+
for tag in self.tagdefs:
|
| 359 |
+
self.tag_remove(tag, "iomark", "end")
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
class ModifiedUndoDelegator(UndoDelegator):
|
| 363 |
+
"Extend base class: forbid insert/delete before the I/O mark"
|
| 364 |
+
def insert(self, index, chars, tags=None):
|
| 365 |
+
try:
|
| 366 |
+
if self.delegate.compare(index, "<", "iomark"):
|
| 367 |
+
self.delegate.bell()
|
| 368 |
+
return
|
| 369 |
+
except TclError:
|
| 370 |
+
pass
|
| 371 |
+
UndoDelegator.insert(self, index, chars, tags)
|
| 372 |
+
|
| 373 |
+
def delete(self, index1, index2=None):
|
| 374 |
+
try:
|
| 375 |
+
if self.delegate.compare(index1, "<", "iomark"):
|
| 376 |
+
self.delegate.bell()
|
| 377 |
+
return
|
| 378 |
+
except TclError:
|
| 379 |
+
pass
|
| 380 |
+
UndoDelegator.delete(self, index1, index2)
|
| 381 |
+
|
| 382 |
+
def undo_event(self, event):
|
| 383 |
+
# Temporarily monkey-patch the delegate's .insert() method to
|
| 384 |
+
# always use the "stdin" tag. This is needed for undo-ing
|
| 385 |
+
# deletions to preserve the "stdin" tag, because UndoDelegator
|
| 386 |
+
# doesn't preserve tags for deleted text.
|
| 387 |
+
orig_insert = self.delegate.insert
|
| 388 |
+
self.delegate.insert = \
|
| 389 |
+
lambda index, chars: orig_insert(index, chars, "stdin")
|
| 390 |
+
try:
|
| 391 |
+
super().undo_event(event)
|
| 392 |
+
finally:
|
| 393 |
+
self.delegate.insert = orig_insert
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
class UserInputTaggingDelegator(Delegator):
|
| 397 |
+
"""Delegator used to tag user input with "stdin"."""
|
| 398 |
+
def insert(self, index, chars, tags=None):
|
| 399 |
+
if tags is None:
|
| 400 |
+
tags = "stdin"
|
| 401 |
+
self.delegate.insert(index, chars, tags)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class MyRPCClient(rpc.RPCClient):
|
| 405 |
+
|
| 406 |
+
def handle_EOF(self):
|
| 407 |
+
"Override the base class - just re-raise EOFError"
|
| 408 |
+
raise EOFError
|
| 409 |
+
|
| 410 |
+
def restart_line(width, filename): # See bpo-38141.
|
| 411 |
+
"""Return width long restart line formatted with filename.
|
| 412 |
+
|
| 413 |
+
Fill line with balanced '='s, with any extras and at least one at
|
| 414 |
+
the beginning. Do not end with a trailing space.
|
| 415 |
+
"""
|
| 416 |
+
tag = f"= RESTART: {filename or 'Shell'} ="
|
| 417 |
+
if width >= len(tag):
|
| 418 |
+
div, mod = divmod((width -len(tag)), 2)
|
| 419 |
+
return f"{(div+mod)*'='}{tag}{div*'='}"
|
| 420 |
+
else:
|
| 421 |
+
return tag[:-2] # Remove ' ='.
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class ModifiedInterpreter(InteractiveInterpreter):
|
| 425 |
+
|
| 426 |
+
def __init__(self, tkconsole):
|
| 427 |
+
self.tkconsole = tkconsole
|
| 428 |
+
locals = sys.modules['__main__'].__dict__
|
| 429 |
+
InteractiveInterpreter.__init__(self, locals=locals)
|
| 430 |
+
self.restarting = False
|
| 431 |
+
self.subprocess_arglist = None
|
| 432 |
+
self.port = PORT
|
| 433 |
+
self.original_compiler_flags = self.compile.compiler.flags
|
| 434 |
+
|
| 435 |
+
_afterid = None
|
| 436 |
+
rpcclt = None
|
| 437 |
+
rpcsubproc = None
|
| 438 |
+
|
| 439 |
+
def spawn_subprocess(self):
|
| 440 |
+
if self.subprocess_arglist is None:
|
| 441 |
+
self.subprocess_arglist = self.build_subprocess_arglist()
|
| 442 |
+
self.rpcsubproc = subprocess.Popen(self.subprocess_arglist)
|
| 443 |
+
|
| 444 |
+
def build_subprocess_arglist(self):
|
| 445 |
+
assert (self.port!=0), (
|
| 446 |
+
"Socket should have been assigned a port number.")
|
| 447 |
+
w = ['-W' + s for s in sys.warnoptions]
|
| 448 |
+
# Maybe IDLE is installed and is being accessed via sys.path,
|
| 449 |
+
# or maybe it's not installed and the idle.py script is being
|
| 450 |
+
# run from the IDLE source directory.
|
| 451 |
+
del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc',
|
| 452 |
+
default=False, type='bool')
|
| 453 |
+
command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,)
|
| 454 |
+
return [sys.executable] + w + ["-c", command, str(self.port)]
|
| 455 |
+
|
| 456 |
+
def start_subprocess(self):
|
| 457 |
+
addr = (HOST, self.port)
|
| 458 |
+
# GUI makes several attempts to acquire socket, listens for connection
|
| 459 |
+
for i in range(3):
|
| 460 |
+
time.sleep(i)
|
| 461 |
+
try:
|
| 462 |
+
self.rpcclt = MyRPCClient(addr)
|
| 463 |
+
break
|
| 464 |
+
except OSError:
|
| 465 |
+
pass
|
| 466 |
+
else:
|
| 467 |
+
self.display_port_binding_error()
|
| 468 |
+
return None
|
| 469 |
+
# if PORT was 0, system will assign an 'ephemeral' port. Find it out:
|
| 470 |
+
self.port = self.rpcclt.listening_sock.getsockname()[1]
|
| 471 |
+
# if PORT was not 0, probably working with a remote execution server
|
| 472 |
+
if PORT != 0:
|
| 473 |
+
# To allow reconnection within the 2MSL wait (cf. Stevens TCP
|
| 474 |
+
# V1, 18.6), set SO_REUSEADDR. Note that this can be problematic
|
| 475 |
+
# on Windows since the implementation allows two active sockets on
|
| 476 |
+
# the same address!
|
| 477 |
+
self.rpcclt.listening_sock.setsockopt(socket.SOL_SOCKET,
|
| 478 |
+
socket.SO_REUSEADDR, 1)
|
| 479 |
+
self.spawn_subprocess()
|
| 480 |
+
#time.sleep(20) # test to simulate GUI not accepting connection
|
| 481 |
+
# Accept the connection from the Python execution server
|
| 482 |
+
self.rpcclt.listening_sock.settimeout(10)
|
| 483 |
+
try:
|
| 484 |
+
self.rpcclt.accept()
|
| 485 |
+
except TimeoutError:
|
| 486 |
+
self.display_no_subprocess_error()
|
| 487 |
+
return None
|
| 488 |
+
self.rpcclt.register("console", self.tkconsole)
|
| 489 |
+
self.rpcclt.register("stdin", self.tkconsole.stdin)
|
| 490 |
+
self.rpcclt.register("stdout", self.tkconsole.stdout)
|
| 491 |
+
self.rpcclt.register("stderr", self.tkconsole.stderr)
|
| 492 |
+
self.rpcclt.register("flist", self.tkconsole.flist)
|
| 493 |
+
self.rpcclt.register("linecache", linecache)
|
| 494 |
+
self.rpcclt.register("interp", self)
|
| 495 |
+
self.transfer_path(with_cwd=True)
|
| 496 |
+
self.poll_subprocess()
|
| 497 |
+
return self.rpcclt
|
| 498 |
+
|
| 499 |
+
def restart_subprocess(self, with_cwd=False, filename=''):
|
| 500 |
+
if self.restarting:
|
| 501 |
+
return self.rpcclt
|
| 502 |
+
self.restarting = True
|
| 503 |
+
# close only the subprocess debugger
|
| 504 |
+
debug = self.getdebugger()
|
| 505 |
+
if debug:
|
| 506 |
+
try:
|
| 507 |
+
# Only close subprocess debugger, don't unregister gui_adap!
|
| 508 |
+
debugger_r.close_subprocess_debugger(self.rpcclt)
|
| 509 |
+
except:
|
| 510 |
+
pass
|
| 511 |
+
# Kill subprocess, spawn a new one, accept connection.
|
| 512 |
+
self.rpcclt.close()
|
| 513 |
+
self.terminate_subprocess()
|
| 514 |
+
console = self.tkconsole
|
| 515 |
+
was_executing = console.executing
|
| 516 |
+
console.executing = False
|
| 517 |
+
self.spawn_subprocess()
|
| 518 |
+
try:
|
| 519 |
+
self.rpcclt.accept()
|
| 520 |
+
except TimeoutError:
|
| 521 |
+
self.display_no_subprocess_error()
|
| 522 |
+
return None
|
| 523 |
+
self.transfer_path(with_cwd=with_cwd)
|
| 524 |
+
console.stop_readline()
|
| 525 |
+
# annotate restart in shell window and mark it
|
| 526 |
+
console.text.delete("iomark", "end-1c")
|
| 527 |
+
console.write('\n')
|
| 528 |
+
console.write(restart_line(console.width, filename))
|
| 529 |
+
console.text.mark_set("restart", "end-1c")
|
| 530 |
+
console.text.mark_gravity("restart", "left")
|
| 531 |
+
if not filename:
|
| 532 |
+
console.showprompt()
|
| 533 |
+
# restart subprocess debugger
|
| 534 |
+
if debug:
|
| 535 |
+
# Restarted debugger connects to current instance of debug GUI
|
| 536 |
+
debugger_r.restart_subprocess_debugger(self.rpcclt)
|
| 537 |
+
# reload remote debugger breakpoints for all PyShellEditWindows
|
| 538 |
+
debug.load_breakpoints()
|
| 539 |
+
self.compile.compiler.flags = self.original_compiler_flags
|
| 540 |
+
self.restarting = False
|
| 541 |
+
return self.rpcclt
|
| 542 |
+
|
| 543 |
+
def __request_interrupt(self):
|
| 544 |
+
self.rpcclt.remotecall("exec", "interrupt_the_server", (), {})
|
| 545 |
+
|
| 546 |
+
def interrupt_subprocess(self):
|
| 547 |
+
threading.Thread(target=self.__request_interrupt).start()
|
| 548 |
+
|
| 549 |
+
def kill_subprocess(self):
|
| 550 |
+
if self._afterid is not None:
|
| 551 |
+
self.tkconsole.text.after_cancel(self._afterid)
|
| 552 |
+
try:
|
| 553 |
+
self.rpcclt.listening_sock.close()
|
| 554 |
+
except AttributeError: # no socket
|
| 555 |
+
pass
|
| 556 |
+
try:
|
| 557 |
+
self.rpcclt.close()
|
| 558 |
+
except AttributeError: # no socket
|
| 559 |
+
pass
|
| 560 |
+
self.terminate_subprocess()
|
| 561 |
+
self.tkconsole.executing = False
|
| 562 |
+
self.rpcclt = None
|
| 563 |
+
|
| 564 |
+
def terminate_subprocess(self):
|
| 565 |
+
"Make sure subprocess is terminated"
|
| 566 |
+
try:
|
| 567 |
+
self.rpcsubproc.kill()
|
| 568 |
+
except OSError:
|
| 569 |
+
# process already terminated
|
| 570 |
+
return
|
| 571 |
+
else:
|
| 572 |
+
try:
|
| 573 |
+
self.rpcsubproc.wait()
|
| 574 |
+
except OSError:
|
| 575 |
+
return
|
| 576 |
+
|
| 577 |
+
def transfer_path(self, with_cwd=False):
|
| 578 |
+
if with_cwd: # Issue 13506
|
| 579 |
+
path = [''] # include Current Working Directory
|
| 580 |
+
path.extend(sys.path)
|
| 581 |
+
else:
|
| 582 |
+
path = sys.path
|
| 583 |
+
|
| 584 |
+
self.runcommand("""if 1:
|
| 585 |
+
import sys as _sys
|
| 586 |
+
_sys.path = %r
|
| 587 |
+
del _sys
|
| 588 |
+
\n""" % (path,))
|
| 589 |
+
|
| 590 |
+
active_seq = None
|
| 591 |
+
|
| 592 |
+
def poll_subprocess(self):
|
| 593 |
+
clt = self.rpcclt
|
| 594 |
+
if clt is None:
|
| 595 |
+
return
|
| 596 |
+
try:
|
| 597 |
+
response = clt.pollresponse(self.active_seq, wait=0.05)
|
| 598 |
+
except (EOFError, OSError, KeyboardInterrupt):
|
| 599 |
+
# lost connection or subprocess terminated itself, restart
|
| 600 |
+
# [the KBI is from rpc.SocketIO.handle_EOF()]
|
| 601 |
+
if self.tkconsole.closing:
|
| 602 |
+
return
|
| 603 |
+
response = None
|
| 604 |
+
self.restart_subprocess()
|
| 605 |
+
if response:
|
| 606 |
+
self.tkconsole.resetoutput()
|
| 607 |
+
self.active_seq = None
|
| 608 |
+
how, what = response
|
| 609 |
+
console = self.tkconsole.console
|
| 610 |
+
if how == "OK":
|
| 611 |
+
if what is not None:
|
| 612 |
+
print(repr(what), file=console)
|
| 613 |
+
elif how == "EXCEPTION":
|
| 614 |
+
if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
|
| 615 |
+
self.remote_stack_viewer()
|
| 616 |
+
elif how == "ERROR":
|
| 617 |
+
errmsg = "pyshell.ModifiedInterpreter: Subprocess ERROR:\n"
|
| 618 |
+
print(errmsg, what, file=sys.__stderr__)
|
| 619 |
+
print(errmsg, what, file=console)
|
| 620 |
+
# we received a response to the currently active seq number:
|
| 621 |
+
try:
|
| 622 |
+
self.tkconsole.endexecuting()
|
| 623 |
+
except AttributeError: # shell may have closed
|
| 624 |
+
pass
|
| 625 |
+
# Reschedule myself
|
| 626 |
+
if not self.tkconsole.closing:
|
| 627 |
+
self._afterid = self.tkconsole.text.after(
|
| 628 |
+
self.tkconsole.pollinterval, self.poll_subprocess)
|
| 629 |
+
|
| 630 |
+
debugger = None
|
| 631 |
+
|
| 632 |
+
def setdebugger(self, debugger):
|
| 633 |
+
self.debugger = debugger
|
| 634 |
+
|
| 635 |
+
def getdebugger(self):
|
| 636 |
+
return self.debugger
|
| 637 |
+
|
| 638 |
+
def open_remote_stack_viewer(self):
|
| 639 |
+
"""Initiate the remote stack viewer from a separate thread.
|
| 640 |
+
|
| 641 |
+
This method is called from the subprocess, and by returning from this
|
| 642 |
+
method we allow the subprocess to unblock. After a bit the shell
|
| 643 |
+
requests the subprocess to open the remote stack viewer which returns a
|
| 644 |
+
static object looking at the last exception. It is queried through
|
| 645 |
+
the RPC mechanism.
|
| 646 |
+
|
| 647 |
+
"""
|
| 648 |
+
self.tkconsole.text.after(300, self.remote_stack_viewer)
|
| 649 |
+
return
|
| 650 |
+
|
| 651 |
+
def remote_stack_viewer(self):
|
| 652 |
+
from idlelib import debugobj_r
|
| 653 |
+
oid = self.rpcclt.remotequeue("exec", "stackviewer", ("flist",), {})
|
| 654 |
+
if oid is None:
|
| 655 |
+
self.tkconsole.root.bell()
|
| 656 |
+
return
|
| 657 |
+
item = debugobj_r.StubObjectTreeItem(self.rpcclt, oid)
|
| 658 |
+
from idlelib.tree import ScrolledCanvas, TreeNode
|
| 659 |
+
top = Toplevel(self.tkconsole.root)
|
| 660 |
+
theme = idleConf.CurrentTheme()
|
| 661 |
+
background = idleConf.GetHighlight(theme, 'normal')['background']
|
| 662 |
+
sc = ScrolledCanvas(top, bg=background, highlightthickness=0)
|
| 663 |
+
sc.frame.pack(expand=1, fill="both")
|
| 664 |
+
node = TreeNode(sc.canvas, None, item)
|
| 665 |
+
node.expand()
|
| 666 |
+
# XXX Should GC the remote tree when closing the window
|
| 667 |
+
|
| 668 |
+
gid = 0
|
| 669 |
+
|
| 670 |
+
def execsource(self, source):
|
| 671 |
+
"Like runsource() but assumes complete exec source"
|
| 672 |
+
filename = self.stuffsource(source)
|
| 673 |
+
self.execfile(filename, source)
|
| 674 |
+
|
| 675 |
+
def execfile(self, filename, source=None):
|
| 676 |
+
"Execute an existing file"
|
| 677 |
+
if source is None:
|
| 678 |
+
with tokenize.open(filename) as fp:
|
| 679 |
+
source = fp.read()
|
| 680 |
+
if use_subprocess:
|
| 681 |
+
source = (f"__file__ = r'''{os.path.abspath(filename)}'''\n"
|
| 682 |
+
+ source + "\ndel __file__")
|
| 683 |
+
try:
|
| 684 |
+
code = compile(source, filename, "exec")
|
| 685 |
+
except (OverflowError, SyntaxError):
|
| 686 |
+
self.tkconsole.resetoutput()
|
| 687 |
+
print('*** Error in script or command!\n'
|
| 688 |
+
'Traceback (most recent call last):',
|
| 689 |
+
file=self.tkconsole.stderr)
|
| 690 |
+
InteractiveInterpreter.showsyntaxerror(self, filename)
|
| 691 |
+
self.tkconsole.showprompt()
|
| 692 |
+
else:
|
| 693 |
+
self.runcode(code)
|
| 694 |
+
|
| 695 |
+
def runsource(self, source):
|
| 696 |
+
"Extend base class method: Stuff the source in the line cache first"
|
| 697 |
+
filename = self.stuffsource(source)
|
| 698 |
+
# at the moment, InteractiveInterpreter expects str
|
| 699 |
+
assert isinstance(source, str)
|
| 700 |
+
# InteractiveInterpreter.runsource() calls its runcode() method,
|
| 701 |
+
# which is overridden (see below)
|
| 702 |
+
return InteractiveInterpreter.runsource(self, source, filename)
|
| 703 |
+
|
| 704 |
+
def stuffsource(self, source):
|
| 705 |
+
"Stuff source in the filename cache"
|
| 706 |
+
filename = "<pyshell#%d>" % self.gid
|
| 707 |
+
self.gid = self.gid + 1
|
| 708 |
+
lines = source.split("\n")
|
| 709 |
+
linecache.cache[filename] = len(source)+1, 0, lines, filename
|
| 710 |
+
return filename
|
| 711 |
+
|
| 712 |
+
def prepend_syspath(self, filename):
|
| 713 |
+
"Prepend sys.path with file's directory if not already included"
|
| 714 |
+
self.runcommand("""if 1:
|
| 715 |
+
_filename = %r
|
| 716 |
+
import sys as _sys
|
| 717 |
+
from os.path import dirname as _dirname
|
| 718 |
+
_dir = _dirname(_filename)
|
| 719 |
+
if not _dir in _sys.path:
|
| 720 |
+
_sys.path.insert(0, _dir)
|
| 721 |
+
del _filename, _sys, _dirname, _dir
|
| 722 |
+
\n""" % (filename,))
|
| 723 |
+
|
| 724 |
+
def showsyntaxerror(self, filename=None):
|
| 725 |
+
"""Override Interactive Interpreter method: Use Colorizing
|
| 726 |
+
|
| 727 |
+
Color the offending position instead of printing it and pointing at it
|
| 728 |
+
with a caret.
|
| 729 |
+
|
| 730 |
+
"""
|
| 731 |
+
tkconsole = self.tkconsole
|
| 732 |
+
text = tkconsole.text
|
| 733 |
+
text.tag_remove("ERROR", "1.0", "end")
|
| 734 |
+
type, value, tb = sys.exc_info()
|
| 735 |
+
msg = getattr(value, 'msg', '') or value or "<no detail available>"
|
| 736 |
+
lineno = getattr(value, 'lineno', '') or 1
|
| 737 |
+
offset = getattr(value, 'offset', '') or 0
|
| 738 |
+
if offset == 0:
|
| 739 |
+
lineno += 1 #mark end of offending line
|
| 740 |
+
if lineno == 1:
|
| 741 |
+
pos = "iomark + %d chars" % (offset-1)
|
| 742 |
+
else:
|
| 743 |
+
pos = "iomark linestart + %d lines + %d chars" % \
|
| 744 |
+
(lineno-1, offset-1)
|
| 745 |
+
tkconsole.colorize_syntax_error(text, pos)
|
| 746 |
+
tkconsole.resetoutput()
|
| 747 |
+
self.write("SyntaxError: %s\n" % msg)
|
| 748 |
+
tkconsole.showprompt()
|
| 749 |
+
|
| 750 |
+
def showtraceback(self):
|
| 751 |
+
"Extend base class method to reset output properly"
|
| 752 |
+
self.tkconsole.resetoutput()
|
| 753 |
+
self.checklinecache()
|
| 754 |
+
InteractiveInterpreter.showtraceback(self)
|
| 755 |
+
if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
|
| 756 |
+
self.tkconsole.open_stack_viewer()
|
| 757 |
+
|
| 758 |
+
def checklinecache(self):
|
| 759 |
+
c = linecache.cache
|
| 760 |
+
for key in list(c.keys()):
|
| 761 |
+
if key[:1] + key[-1:] != "<>":
|
| 762 |
+
del c[key]
|
| 763 |
+
|
| 764 |
+
def runcommand(self, code):
|
| 765 |
+
"Run the code without invoking the debugger"
|
| 766 |
+
# The code better not raise an exception!
|
| 767 |
+
if self.tkconsole.executing:
|
| 768 |
+
self.display_executing_dialog()
|
| 769 |
+
return 0
|
| 770 |
+
if self.rpcclt:
|
| 771 |
+
self.rpcclt.remotequeue("exec", "runcode", (code,), {})
|
| 772 |
+
else:
|
| 773 |
+
exec(code, self.locals)
|
| 774 |
+
return 1
|
| 775 |
+
|
| 776 |
+
def runcode(self, code):
|
| 777 |
+
"Override base class method"
|
| 778 |
+
if self.tkconsole.executing:
|
| 779 |
+
self.restart_subprocess()
|
| 780 |
+
self.checklinecache()
|
| 781 |
+
debugger = self.debugger
|
| 782 |
+
try:
|
| 783 |
+
self.tkconsole.beginexecuting()
|
| 784 |
+
if not debugger and self.rpcclt is not None:
|
| 785 |
+
self.active_seq = self.rpcclt.asyncqueue("exec", "runcode",
|
| 786 |
+
(code,), {})
|
| 787 |
+
elif debugger:
|
| 788 |
+
debugger.run(code, self.locals)
|
| 789 |
+
else:
|
| 790 |
+
exec(code, self.locals)
|
| 791 |
+
except SystemExit:
|
| 792 |
+
if not self.tkconsole.closing:
|
| 793 |
+
if messagebox.askyesno(
|
| 794 |
+
"Exit?",
|
| 795 |
+
"Do you want to exit altogether?",
|
| 796 |
+
default="yes",
|
| 797 |
+
parent=self.tkconsole.text):
|
| 798 |
+
raise
|
| 799 |
+
else:
|
| 800 |
+
self.showtraceback()
|
| 801 |
+
else:
|
| 802 |
+
raise
|
| 803 |
+
except:
|
| 804 |
+
if use_subprocess:
|
| 805 |
+
print("IDLE internal error in runcode()",
|
| 806 |
+
file=self.tkconsole.stderr)
|
| 807 |
+
self.showtraceback()
|
| 808 |
+
self.tkconsole.endexecuting()
|
| 809 |
+
else:
|
| 810 |
+
if self.tkconsole.canceled:
|
| 811 |
+
self.tkconsole.canceled = False
|
| 812 |
+
print("KeyboardInterrupt", file=self.tkconsole.stderr)
|
| 813 |
+
else:
|
| 814 |
+
self.showtraceback()
|
| 815 |
+
finally:
|
| 816 |
+
if not use_subprocess:
|
| 817 |
+
try:
|
| 818 |
+
self.tkconsole.endexecuting()
|
| 819 |
+
except AttributeError: # shell may have closed
|
| 820 |
+
pass
|
| 821 |
+
|
| 822 |
+
def write(self, s):
|
| 823 |
+
"Override base class method"
|
| 824 |
+
return self.tkconsole.stderr.write(s)
|
| 825 |
+
|
| 826 |
+
def display_port_binding_error(self):
|
| 827 |
+
messagebox.showerror(
|
| 828 |
+
"Port Binding Error",
|
| 829 |
+
"IDLE can't bind to a TCP/IP port, which is necessary to "
|
| 830 |
+
"communicate with its Python execution server. This might be "
|
| 831 |
+
"because no networking is installed on this computer. "
|
| 832 |
+
"Run IDLE with the -n command line switch to start without a "
|
| 833 |
+
"subprocess and refer to Help/IDLE Help 'Running without a "
|
| 834 |
+
"subprocess' for further details.",
|
| 835 |
+
parent=self.tkconsole.text)
|
| 836 |
+
|
| 837 |
+
def display_no_subprocess_error(self):
|
| 838 |
+
messagebox.showerror(
|
| 839 |
+
"Subprocess Connection Error",
|
| 840 |
+
"IDLE's subprocess didn't make connection.\n"
|
| 841 |
+
"See the 'Startup failure' section of the IDLE doc, online at\n"
|
| 842 |
+
"https://docs.python.org/3/library/idle.html#startup-failure",
|
| 843 |
+
parent=self.tkconsole.text)
|
| 844 |
+
|
| 845 |
+
def display_executing_dialog(self):
|
| 846 |
+
messagebox.showerror(
|
| 847 |
+
"Already executing",
|
| 848 |
+
"The Python Shell window is already executing a command; "
|
| 849 |
+
"please wait until it is finished.",
|
| 850 |
+
parent=self.tkconsole.text)
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
class PyShell(OutputWindow):
|
| 854 |
+
from idlelib.squeezer import Squeezer
|
| 855 |
+
|
| 856 |
+
shell_title = "IDLE Shell " + python_version()
|
| 857 |
+
|
| 858 |
+
# Override classes
|
| 859 |
+
ColorDelegator = ModifiedColorDelegator
|
| 860 |
+
UndoDelegator = ModifiedUndoDelegator
|
| 861 |
+
|
| 862 |
+
# Override menus
|
| 863 |
+
menu_specs = [
|
| 864 |
+
("file", "_File"),
|
| 865 |
+
("edit", "_Edit"),
|
| 866 |
+
("debug", "_Debug"),
|
| 867 |
+
("options", "_Options"),
|
| 868 |
+
("window", "_Window"),
|
| 869 |
+
("help", "_Help"),
|
| 870 |
+
]
|
| 871 |
+
|
| 872 |
+
# Extend right-click context menu
|
| 873 |
+
rmenu_specs = OutputWindow.rmenu_specs + [
|
| 874 |
+
("Squeeze", "<<squeeze-current-text>>"),
|
| 875 |
+
]
|
| 876 |
+
_idx = 1 + len(list(itertools.takewhile(
|
| 877 |
+
lambda rmenu_item: rmenu_item[0] != "Copy", rmenu_specs)
|
| 878 |
+
))
|
| 879 |
+
rmenu_specs.insert(_idx, ("Copy with prompts",
|
| 880 |
+
"<<copy-with-prompts>>",
|
| 881 |
+
"rmenu_check_copy"))
|
| 882 |
+
del _idx
|
| 883 |
+
|
| 884 |
+
allow_line_numbers = False
|
| 885 |
+
user_input_insert_tags = "stdin"
|
| 886 |
+
|
| 887 |
+
# New classes
|
| 888 |
+
from idlelib.history import History
|
| 889 |
+
from idlelib.sidebar import ShellSidebar
|
| 890 |
+
|
| 891 |
+
def __init__(self, flist=None):
|
| 892 |
+
if use_subprocess:
|
| 893 |
+
ms = self.menu_specs
|
| 894 |
+
if ms[2][0] != "shell":
|
| 895 |
+
ms.insert(2, ("shell", "She_ll"))
|
| 896 |
+
self.interp = ModifiedInterpreter(self)
|
| 897 |
+
if flist is None:
|
| 898 |
+
root = Tk()
|
| 899 |
+
fixwordbreaks(root)
|
| 900 |
+
root.withdraw()
|
| 901 |
+
flist = PyShellFileList(root)
|
| 902 |
+
|
| 903 |
+
self.shell_sidebar = None # initialized below
|
| 904 |
+
|
| 905 |
+
OutputWindow.__init__(self, flist, None, None)
|
| 906 |
+
|
| 907 |
+
self.usetabs = False
|
| 908 |
+
# indentwidth must be 8 when using tabs. See note in EditorWindow:
|
| 909 |
+
self.indentwidth = 4
|
| 910 |
+
|
| 911 |
+
self.sys_ps1 = sys.ps1 if hasattr(sys, 'ps1') else '>>>\n'
|
| 912 |
+
self.prompt_last_line = self.sys_ps1.split('\n')[-1]
|
| 913 |
+
self.prompt = self.sys_ps1 # Changes when debug active
|
| 914 |
+
|
| 915 |
+
text = self.text
|
| 916 |
+
text.configure(wrap="char")
|
| 917 |
+
text.bind("<<newline-and-indent>>", self.enter_callback)
|
| 918 |
+
text.bind("<<plain-newline-and-indent>>", self.linefeed_callback)
|
| 919 |
+
text.bind("<<interrupt-execution>>", self.cancel_callback)
|
| 920 |
+
text.bind("<<end-of-file>>", self.eof_callback)
|
| 921 |
+
text.bind("<<open-stack-viewer>>", self.open_stack_viewer)
|
| 922 |
+
text.bind("<<toggle-debugger>>", self.toggle_debugger)
|
| 923 |
+
text.bind("<<toggle-jit-stack-viewer>>", self.toggle_jit_stack_viewer)
|
| 924 |
+
text.bind("<<copy-with-prompts>>", self.copy_with_prompts_callback)
|
| 925 |
+
if use_subprocess:
|
| 926 |
+
text.bind("<<view-restart>>", self.view_restart_mark)
|
| 927 |
+
text.bind("<<restart-shell>>", self.restart_shell)
|
| 928 |
+
self.squeezer = self.Squeezer(self)
|
| 929 |
+
text.bind("<<squeeze-current-text>>",
|
| 930 |
+
self.squeeze_current_text_event)
|
| 931 |
+
|
| 932 |
+
self.save_stdout = sys.stdout
|
| 933 |
+
self.save_stderr = sys.stderr
|
| 934 |
+
self.save_stdin = sys.stdin
|
| 935 |
+
from idlelib import iomenu
|
| 936 |
+
self.stdin = StdInputFile(self, "stdin",
|
| 937 |
+
iomenu.encoding, iomenu.errors)
|
| 938 |
+
self.stdout = StdOutputFile(self, "stdout",
|
| 939 |
+
iomenu.encoding, iomenu.errors)
|
| 940 |
+
self.stderr = StdOutputFile(self, "stderr",
|
| 941 |
+
iomenu.encoding, "backslashreplace")
|
| 942 |
+
self.console = StdOutputFile(self, "console",
|
| 943 |
+
iomenu.encoding, iomenu.errors)
|
| 944 |
+
if not use_subprocess:
|
| 945 |
+
sys.stdout = self.stdout
|
| 946 |
+
sys.stderr = self.stderr
|
| 947 |
+
sys.stdin = self.stdin
|
| 948 |
+
try:
|
| 949 |
+
# page help() text to shell.
|
| 950 |
+
import pydoc # import must be done here to capture i/o rebinding.
|
| 951 |
+
# XXX KBK 27Dec07 use text viewer someday, but must work w/o subproc
|
| 952 |
+
pydoc.pager = pydoc.plainpager
|
| 953 |
+
except:
|
| 954 |
+
sys.stderr = sys.__stderr__
|
| 955 |
+
raise
|
| 956 |
+
#
|
| 957 |
+
self.history = self.History(self.text)
|
| 958 |
+
#
|
| 959 |
+
self.pollinterval = 50 # millisec
|
| 960 |
+
|
| 961 |
+
self.shell_sidebar = self.ShellSidebar(self)
|
| 962 |
+
|
| 963 |
+
# Insert UserInputTaggingDelegator at the top of the percolator,
|
| 964 |
+
# but make calls to text.insert() skip it. This causes only insert
|
| 965 |
+
# events generated in Tcl/Tk to go through this delegator.
|
| 966 |
+
self.text.insert = self.per.top.insert
|
| 967 |
+
self.per.insertfilter(UserInputTaggingDelegator())
|
| 968 |
+
|
| 969 |
+
def ResetFont(self):
|
| 970 |
+
super().ResetFont()
|
| 971 |
+
|
| 972 |
+
if self.shell_sidebar is not None:
|
| 973 |
+
self.shell_sidebar.update_font()
|
| 974 |
+
|
| 975 |
+
def ResetColorizer(self):
|
| 976 |
+
super().ResetColorizer()
|
| 977 |
+
|
| 978 |
+
theme = idleConf.CurrentTheme()
|
| 979 |
+
tag_colors = {
|
| 980 |
+
"stdin": {'background': None, 'foreground': None},
|
| 981 |
+
"stdout": idleConf.GetHighlight(theme, "stdout"),
|
| 982 |
+
"stderr": idleConf.GetHighlight(theme, "stderr"),
|
| 983 |
+
"console": idleConf.GetHighlight(theme, "normal"),
|
| 984 |
+
}
|
| 985 |
+
for tag, tag_colors_config in tag_colors.items():
|
| 986 |
+
self.text.tag_configure(tag, **tag_colors_config)
|
| 987 |
+
|
| 988 |
+
if self.shell_sidebar is not None:
|
| 989 |
+
self.shell_sidebar.update_colors()
|
| 990 |
+
|
| 991 |
+
def replace_event(self, event):
|
| 992 |
+
replace.replace(self.text, insert_tags="stdin")
|
| 993 |
+
return "break"
|
| 994 |
+
|
| 995 |
+
def get_standard_extension_names(self):
|
| 996 |
+
return idleConf.GetExtensions(shell_only=True)
|
| 997 |
+
|
| 998 |
+
def get_prompt_text(self, first, last):
|
| 999 |
+
"""Return text between first and last with prompts added."""
|
| 1000 |
+
text = self.text.get(first, last)
|
| 1001 |
+
lineno_range = range(
|
| 1002 |
+
int(float(first)),
|
| 1003 |
+
int(float(last))
|
| 1004 |
+
)
|
| 1005 |
+
prompts = [
|
| 1006 |
+
self.shell_sidebar.line_prompts.get(lineno)
|
| 1007 |
+
for lineno in lineno_range
|
| 1008 |
+
]
|
| 1009 |
+
return "\n".join(
|
| 1010 |
+
line if prompt is None else f"{prompt} {line}"
|
| 1011 |
+
for prompt, line in zip(prompts, text.splitlines())
|
| 1012 |
+
) + "\n"
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
def copy_with_prompts_callback(self, event=None):
|
| 1016 |
+
"""Copy selected lines to the clipboard, with prompts.
|
| 1017 |
+
|
| 1018 |
+
This makes the copied text useful for doc-tests and interactive
|
| 1019 |
+
shell code examples.
|
| 1020 |
+
|
| 1021 |
+
This always copies entire lines, even if only part of the first
|
| 1022 |
+
and/or last lines is selected.
|
| 1023 |
+
"""
|
| 1024 |
+
text = self.text
|
| 1025 |
+
selfirst = text.index('sel.first linestart')
|
| 1026 |
+
if selfirst is None: # Should not be possible.
|
| 1027 |
+
return # No selection, do nothing.
|
| 1028 |
+
sellast = text.index('sel.last')
|
| 1029 |
+
if sellast[-1] != '0':
|
| 1030 |
+
sellast = text.index("sel.last+1line linestart")
|
| 1031 |
+
text.clipboard_clear()
|
| 1032 |
+
prompt_text = self.get_prompt_text(selfirst, sellast)
|
| 1033 |
+
text.clipboard_append(prompt_text)
|
| 1034 |
+
|
| 1035 |
+
reading = False
|
| 1036 |
+
executing = False
|
| 1037 |
+
canceled = False
|
| 1038 |
+
endoffile = False
|
| 1039 |
+
closing = False
|
| 1040 |
+
_stop_readline_flag = False
|
| 1041 |
+
|
| 1042 |
+
def set_warning_stream(self, stream):
|
| 1043 |
+
global warning_stream
|
| 1044 |
+
warning_stream = stream
|
| 1045 |
+
|
| 1046 |
+
def get_warning_stream(self):
|
| 1047 |
+
return warning_stream
|
| 1048 |
+
|
| 1049 |
+
def toggle_debugger(self, event=None):
|
| 1050 |
+
if self.executing:
|
| 1051 |
+
messagebox.showerror("Don't debug now",
|
| 1052 |
+
"You can only toggle the debugger when idle",
|
| 1053 |
+
parent=self.text)
|
| 1054 |
+
self.set_debugger_indicator()
|
| 1055 |
+
return "break"
|
| 1056 |
+
else:
|
| 1057 |
+
db = self.interp.getdebugger()
|
| 1058 |
+
if db:
|
| 1059 |
+
self.close_debugger()
|
| 1060 |
+
else:
|
| 1061 |
+
self.open_debugger()
|
| 1062 |
+
|
| 1063 |
+
def set_debugger_indicator(self):
|
| 1064 |
+
db = self.interp.getdebugger()
|
| 1065 |
+
self.setvar("<<toggle-debugger>>", not not db)
|
| 1066 |
+
|
| 1067 |
+
def toggle_jit_stack_viewer(self, event=None):
|
| 1068 |
+
pass # All we need is the variable
|
| 1069 |
+
|
| 1070 |
+
def close_debugger(self):
|
| 1071 |
+
db = self.interp.getdebugger()
|
| 1072 |
+
if db:
|
| 1073 |
+
self.interp.setdebugger(None)
|
| 1074 |
+
db.close()
|
| 1075 |
+
if self.interp.rpcclt:
|
| 1076 |
+
debugger_r.close_remote_debugger(self.interp.rpcclt)
|
| 1077 |
+
self.resetoutput()
|
| 1078 |
+
self.console.write("[DEBUG OFF]\n")
|
| 1079 |
+
self.prompt = self.sys_ps1
|
| 1080 |
+
self.showprompt()
|
| 1081 |
+
self.set_debugger_indicator()
|
| 1082 |
+
|
| 1083 |
+
def open_debugger(self):
|
| 1084 |
+
if self.interp.rpcclt:
|
| 1085 |
+
dbg_gui = debugger_r.start_remote_debugger(self.interp.rpcclt,
|
| 1086 |
+
self)
|
| 1087 |
+
else:
|
| 1088 |
+
dbg_gui = debugger.Debugger(self)
|
| 1089 |
+
self.interp.setdebugger(dbg_gui)
|
| 1090 |
+
dbg_gui.load_breakpoints()
|
| 1091 |
+
self.prompt = "[DEBUG ON]\n" + self.sys_ps1
|
| 1092 |
+
self.showprompt()
|
| 1093 |
+
self.set_debugger_indicator()
|
| 1094 |
+
|
| 1095 |
+
def debug_menu_postcommand(self):
|
| 1096 |
+
state = 'disabled' if self.executing else 'normal'
|
| 1097 |
+
self.update_menu_state('debug', '*tack*iewer', state)
|
| 1098 |
+
|
| 1099 |
+
def beginexecuting(self):
|
| 1100 |
+
"Helper for ModifiedInterpreter"
|
| 1101 |
+
self.resetoutput()
|
| 1102 |
+
self.executing = True
|
| 1103 |
+
|
| 1104 |
+
def endexecuting(self):
|
| 1105 |
+
"Helper for ModifiedInterpreter"
|
| 1106 |
+
self.executing = False
|
| 1107 |
+
self.canceled = False
|
| 1108 |
+
self.showprompt()
|
| 1109 |
+
|
| 1110 |
+
def close(self):
|
| 1111 |
+
"Extend EditorWindow.close()"
|
| 1112 |
+
if self.executing:
|
| 1113 |
+
response = messagebox.askokcancel(
|
| 1114 |
+
"Kill?",
|
| 1115 |
+
"Your program is still running!\n Do you want to kill it?",
|
| 1116 |
+
default="ok",
|
| 1117 |
+
parent=self.text)
|
| 1118 |
+
if response is False:
|
| 1119 |
+
return "cancel"
|
| 1120 |
+
self.stop_readline()
|
| 1121 |
+
self.canceled = True
|
| 1122 |
+
self.closing = True
|
| 1123 |
+
return EditorWindow.close(self)
|
| 1124 |
+
|
| 1125 |
+
def _close(self):
|
| 1126 |
+
"Extend EditorWindow._close(), shut down debugger and execution server"
|
| 1127 |
+
self.close_debugger()
|
| 1128 |
+
if use_subprocess:
|
| 1129 |
+
self.interp.kill_subprocess()
|
| 1130 |
+
# Restore std streams
|
| 1131 |
+
sys.stdout = self.save_stdout
|
| 1132 |
+
sys.stderr = self.save_stderr
|
| 1133 |
+
sys.stdin = self.save_stdin
|
| 1134 |
+
# Break cycles
|
| 1135 |
+
self.interp = None
|
| 1136 |
+
self.console = None
|
| 1137 |
+
self.flist.pyshell = None
|
| 1138 |
+
self.history = None
|
| 1139 |
+
EditorWindow._close(self)
|
| 1140 |
+
|
| 1141 |
+
def ispythonsource(self, filename):
|
| 1142 |
+
"Override EditorWindow method: never remove the colorizer"
|
| 1143 |
+
return True
|
| 1144 |
+
|
| 1145 |
+
def short_title(self):
|
| 1146 |
+
return self.shell_title
|
| 1147 |
+
|
| 1148 |
+
COPYRIGHT = \
|
| 1149 |
+
'Type "help", "copyright", "credits" or "license()" for more information.'
|
| 1150 |
+
|
| 1151 |
+
def begin(self):
|
| 1152 |
+
self.text.mark_set("iomark", "insert")
|
| 1153 |
+
self.resetoutput()
|
| 1154 |
+
if use_subprocess:
|
| 1155 |
+
nosub = ''
|
| 1156 |
+
client = self.interp.start_subprocess()
|
| 1157 |
+
if not client:
|
| 1158 |
+
self.close()
|
| 1159 |
+
return False
|
| 1160 |
+
else:
|
| 1161 |
+
nosub = ("==== No Subprocess ====\n\n" +
|
| 1162 |
+
"WARNING: Running IDLE without a Subprocess is deprecated\n" +
|
| 1163 |
+
"and will be removed in a later version. See Help/IDLE Help\n" +
|
| 1164 |
+
"for details.\n\n")
|
| 1165 |
+
sys.displayhook = rpc.displayhook
|
| 1166 |
+
|
| 1167 |
+
self.write("Python %s on %s\n%s\n%s" %
|
| 1168 |
+
(sys.version, sys.platform, self.COPYRIGHT, nosub))
|
| 1169 |
+
self.text.focus_force()
|
| 1170 |
+
self.showprompt()
|
| 1171 |
+
# User code should use separate default Tk root window
|
| 1172 |
+
import tkinter
|
| 1173 |
+
tkinter._support_default_root = True
|
| 1174 |
+
tkinter._default_root = None
|
| 1175 |
+
return True
|
| 1176 |
+
|
| 1177 |
+
def stop_readline(self):
|
| 1178 |
+
if not self.reading: # no nested mainloop to exit.
|
| 1179 |
+
return
|
| 1180 |
+
self._stop_readline_flag = True
|
| 1181 |
+
self.top.quit()
|
| 1182 |
+
|
| 1183 |
+
def readline(self):
|
| 1184 |
+
save = self.reading
|
| 1185 |
+
try:
|
| 1186 |
+
self.reading = True
|
| 1187 |
+
self.top.mainloop() # nested mainloop()
|
| 1188 |
+
finally:
|
| 1189 |
+
self.reading = save
|
| 1190 |
+
if self._stop_readline_flag:
|
| 1191 |
+
self._stop_readline_flag = False
|
| 1192 |
+
return ""
|
| 1193 |
+
line = self.text.get("iomark", "end-1c")
|
| 1194 |
+
if len(line) == 0: # may be EOF if we quit our mainloop with Ctrl-C
|
| 1195 |
+
line = "\n"
|
| 1196 |
+
self.resetoutput()
|
| 1197 |
+
if self.canceled:
|
| 1198 |
+
self.canceled = False
|
| 1199 |
+
if not use_subprocess:
|
| 1200 |
+
raise KeyboardInterrupt
|
| 1201 |
+
if self.endoffile:
|
| 1202 |
+
self.endoffile = False
|
| 1203 |
+
line = ""
|
| 1204 |
+
return line
|
| 1205 |
+
|
| 1206 |
+
def isatty(self):
|
| 1207 |
+
return True
|
| 1208 |
+
|
| 1209 |
+
def cancel_callback(self, event=None):
|
| 1210 |
+
try:
|
| 1211 |
+
if self.text.compare("sel.first", "!=", "sel.last"):
|
| 1212 |
+
return # Active selection -- always use default binding
|
| 1213 |
+
except:
|
| 1214 |
+
pass
|
| 1215 |
+
if not (self.executing or self.reading):
|
| 1216 |
+
self.resetoutput()
|
| 1217 |
+
self.interp.write("KeyboardInterrupt\n")
|
| 1218 |
+
self.showprompt()
|
| 1219 |
+
return "break"
|
| 1220 |
+
self.endoffile = False
|
| 1221 |
+
self.canceled = True
|
| 1222 |
+
if (self.executing and self.interp.rpcclt):
|
| 1223 |
+
if self.interp.getdebugger():
|
| 1224 |
+
self.interp.restart_subprocess()
|
| 1225 |
+
else:
|
| 1226 |
+
self.interp.interrupt_subprocess()
|
| 1227 |
+
if self.reading:
|
| 1228 |
+
self.top.quit() # exit the nested mainloop() in readline()
|
| 1229 |
+
return "break"
|
| 1230 |
+
|
| 1231 |
+
def eof_callback(self, event):
|
| 1232 |
+
if self.executing and not self.reading:
|
| 1233 |
+
return # Let the default binding (delete next char) take over
|
| 1234 |
+
if not (self.text.compare("iomark", "==", "insert") and
|
| 1235 |
+
self.text.compare("insert", "==", "end-1c")):
|
| 1236 |
+
return # Let the default binding (delete next char) take over
|
| 1237 |
+
if not self.executing:
|
| 1238 |
+
self.resetoutput()
|
| 1239 |
+
self.close()
|
| 1240 |
+
else:
|
| 1241 |
+
self.canceled = False
|
| 1242 |
+
self.endoffile = True
|
| 1243 |
+
self.top.quit()
|
| 1244 |
+
return "break"
|
| 1245 |
+
|
| 1246 |
+
def linefeed_callback(self, event):
|
| 1247 |
+
# Insert a linefeed without entering anything (still autoindented)
|
| 1248 |
+
if self.reading:
|
| 1249 |
+
self.text.insert("insert", "\n")
|
| 1250 |
+
self.text.see("insert")
|
| 1251 |
+
else:
|
| 1252 |
+
self.newline_and_indent_event(event)
|
| 1253 |
+
return "break"
|
| 1254 |
+
|
| 1255 |
+
def enter_callback(self, event):
|
| 1256 |
+
if self.executing and not self.reading:
|
| 1257 |
+
return # Let the default binding (insert '\n') take over
|
| 1258 |
+
# If some text is selected, recall the selection
|
| 1259 |
+
# (but only if this before the I/O mark)
|
| 1260 |
+
try:
|
| 1261 |
+
sel = self.text.get("sel.first", "sel.last")
|
| 1262 |
+
if sel:
|
| 1263 |
+
if self.text.compare("sel.last", "<=", "iomark"):
|
| 1264 |
+
self.recall(sel, event)
|
| 1265 |
+
return "break"
|
| 1266 |
+
except:
|
| 1267 |
+
pass
|
| 1268 |
+
# If we're strictly before the line containing iomark, recall
|
| 1269 |
+
# the current line, less a leading prompt, less leading or
|
| 1270 |
+
# trailing whitespace
|
| 1271 |
+
if self.text.compare("insert", "<", "iomark linestart"):
|
| 1272 |
+
# Check if there's a relevant stdin range -- if so, use it.
|
| 1273 |
+
# Note: "stdin" blocks may include several successive statements,
|
| 1274 |
+
# so look for "console" tags on the newline before each statement
|
| 1275 |
+
# (and possibly on prompts).
|
| 1276 |
+
prev = self.text.tag_prevrange("stdin", "insert")
|
| 1277 |
+
if (
|
| 1278 |
+
prev and
|
| 1279 |
+
self.text.compare("insert", "<", prev[1]) and
|
| 1280 |
+
# The following is needed to handle empty statements.
|
| 1281 |
+
"console" not in self.text.tag_names("insert")
|
| 1282 |
+
):
|
| 1283 |
+
prev_cons = self.text.tag_prevrange("console", "insert")
|
| 1284 |
+
if prev_cons and self.text.compare(prev_cons[1], ">=", prev[0]):
|
| 1285 |
+
prev = (prev_cons[1], prev[1])
|
| 1286 |
+
next_cons = self.text.tag_nextrange("console", "insert")
|
| 1287 |
+
if next_cons and self.text.compare(next_cons[0], "<", prev[1]):
|
| 1288 |
+
prev = (prev[0], self.text.index(next_cons[0] + "+1c"))
|
| 1289 |
+
self.recall(self.text.get(prev[0], prev[1]), event)
|
| 1290 |
+
return "break"
|
| 1291 |
+
next = self.text.tag_nextrange("stdin", "insert")
|
| 1292 |
+
if next and self.text.compare("insert lineend", ">=", next[0]):
|
| 1293 |
+
next_cons = self.text.tag_nextrange("console", "insert lineend")
|
| 1294 |
+
if next_cons and self.text.compare(next_cons[0], "<", next[1]):
|
| 1295 |
+
next = (next[0], self.text.index(next_cons[0] + "+1c"))
|
| 1296 |
+
self.recall(self.text.get(next[0], next[1]), event)
|
| 1297 |
+
return "break"
|
| 1298 |
+
# No stdin mark -- just get the current line, less any prompt
|
| 1299 |
+
indices = self.text.tag_nextrange("console", "insert linestart")
|
| 1300 |
+
if indices and \
|
| 1301 |
+
self.text.compare(indices[0], "<=", "insert linestart"):
|
| 1302 |
+
self.recall(self.text.get(indices[1], "insert lineend"), event)
|
| 1303 |
+
else:
|
| 1304 |
+
self.recall(self.text.get("insert linestart", "insert lineend"), event)
|
| 1305 |
+
return "break"
|
| 1306 |
+
# If we're between the beginning of the line and the iomark, i.e.
|
| 1307 |
+
# in the prompt area, move to the end of the prompt
|
| 1308 |
+
if self.text.compare("insert", "<", "iomark"):
|
| 1309 |
+
self.text.mark_set("insert", "iomark")
|
| 1310 |
+
# If we're in the current input and there's only whitespace
|
| 1311 |
+
# beyond the cursor, erase that whitespace first
|
| 1312 |
+
s = self.text.get("insert", "end-1c")
|
| 1313 |
+
if s and not s.strip():
|
| 1314 |
+
self.text.delete("insert", "end-1c")
|
| 1315 |
+
# If we're in the current input before its last line,
|
| 1316 |
+
# insert a newline right at the insert point
|
| 1317 |
+
if self.text.compare("insert", "<", "end-1c linestart"):
|
| 1318 |
+
self.newline_and_indent_event(event)
|
| 1319 |
+
return "break"
|
| 1320 |
+
# We're in the last line; append a newline and submit it
|
| 1321 |
+
self.text.mark_set("insert", "end-1c")
|
| 1322 |
+
if self.reading:
|
| 1323 |
+
self.text.insert("insert", "\n")
|
| 1324 |
+
self.text.see("insert")
|
| 1325 |
+
else:
|
| 1326 |
+
self.newline_and_indent_event(event)
|
| 1327 |
+
self.text.update_idletasks()
|
| 1328 |
+
if self.reading:
|
| 1329 |
+
self.top.quit() # Break out of recursive mainloop()
|
| 1330 |
+
else:
|
| 1331 |
+
self.runit()
|
| 1332 |
+
return "break"
|
| 1333 |
+
|
| 1334 |
+
def recall(self, s, event):
|
| 1335 |
+
# remove leading and trailing empty or whitespace lines
|
| 1336 |
+
s = re.sub(r'^\s*\n', '', s)
|
| 1337 |
+
s = re.sub(r'\n\s*$', '', s)
|
| 1338 |
+
lines = s.split('\n')
|
| 1339 |
+
self.text.undo_block_start()
|
| 1340 |
+
try:
|
| 1341 |
+
self.text.tag_remove("sel", "1.0", "end")
|
| 1342 |
+
self.text.mark_set("insert", "end-1c")
|
| 1343 |
+
prefix = self.text.get("insert linestart", "insert")
|
| 1344 |
+
if prefix.rstrip().endswith(':'):
|
| 1345 |
+
self.newline_and_indent_event(event)
|
| 1346 |
+
prefix = self.text.get("insert linestart", "insert")
|
| 1347 |
+
self.text.insert("insert", lines[0].strip(),
|
| 1348 |
+
self.user_input_insert_tags)
|
| 1349 |
+
if len(lines) > 1:
|
| 1350 |
+
orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0)
|
| 1351 |
+
new_base_indent = re.search(r'^([ \t]*)', prefix).group(0)
|
| 1352 |
+
for line in lines[1:]:
|
| 1353 |
+
if line.startswith(orig_base_indent):
|
| 1354 |
+
# replace orig base indentation with new indentation
|
| 1355 |
+
line = new_base_indent + line[len(orig_base_indent):]
|
| 1356 |
+
self.text.insert('insert', '\n' + line.rstrip(),
|
| 1357 |
+
self.user_input_insert_tags)
|
| 1358 |
+
finally:
|
| 1359 |
+
self.text.see("insert")
|
| 1360 |
+
self.text.undo_block_stop()
|
| 1361 |
+
|
| 1362 |
+
_last_newline_re = re.compile(r"[ \t]*(\n[ \t]*)?\Z")
|
| 1363 |
+
def runit(self):
|
| 1364 |
+
index_before = self.text.index("end-2c")
|
| 1365 |
+
line = self.text.get("iomark", "end-1c")
|
| 1366 |
+
# Strip off last newline and surrounding whitespace.
|
| 1367 |
+
# (To allow you to hit return twice to end a statement.)
|
| 1368 |
+
line = self._last_newline_re.sub("", line)
|
| 1369 |
+
input_is_complete = self.interp.runsource(line)
|
| 1370 |
+
if not input_is_complete:
|
| 1371 |
+
if self.text.get(index_before) == '\n':
|
| 1372 |
+
self.text.tag_remove(self.user_input_insert_tags, index_before)
|
| 1373 |
+
self.shell_sidebar.update_sidebar()
|
| 1374 |
+
|
| 1375 |
+
def open_stack_viewer(self, event=None):
|
| 1376 |
+
if self.interp.rpcclt:
|
| 1377 |
+
return self.interp.remote_stack_viewer()
|
| 1378 |
+
try:
|
| 1379 |
+
sys.last_traceback
|
| 1380 |
+
except:
|
| 1381 |
+
messagebox.showerror("No stack trace",
|
| 1382 |
+
"There is no stack trace yet.\n"
|
| 1383 |
+
"(sys.last_traceback is not defined)",
|
| 1384 |
+
parent=self.text)
|
| 1385 |
+
return
|
| 1386 |
+
from idlelib.stackviewer import StackBrowser
|
| 1387 |
+
StackBrowser(self.root, self.flist)
|
| 1388 |
+
|
| 1389 |
+
def view_restart_mark(self, event=None):
|
| 1390 |
+
self.text.see("iomark")
|
| 1391 |
+
self.text.see("restart")
|
| 1392 |
+
|
| 1393 |
+
def restart_shell(self, event=None):
|
| 1394 |
+
"Callback for Run/Restart Shell Cntl-F6"
|
| 1395 |
+
self.interp.restart_subprocess(with_cwd=True)
|
| 1396 |
+
|
| 1397 |
+
def showprompt(self):
|
| 1398 |
+
self.resetoutput()
|
| 1399 |
+
|
| 1400 |
+
prompt = self.prompt
|
| 1401 |
+
if self.sys_ps1 and prompt.endswith(self.sys_ps1):
|
| 1402 |
+
prompt = prompt[:-len(self.sys_ps1)]
|
| 1403 |
+
self.text.tag_add("console", "iomark-1c")
|
| 1404 |
+
self.console.write(prompt)
|
| 1405 |
+
|
| 1406 |
+
self.shell_sidebar.update_sidebar()
|
| 1407 |
+
self.text.mark_set("insert", "end-1c")
|
| 1408 |
+
self.set_line_and_column()
|
| 1409 |
+
self.io.reset_undo()
|
| 1410 |
+
|
| 1411 |
+
def show_warning(self, msg):
|
| 1412 |
+
width = self.interp.tkconsole.width
|
| 1413 |
+
wrapper = TextWrapper(width=width, tabsize=8, expand_tabs=True)
|
| 1414 |
+
wrapped_msg = '\n'.join(wrapper.wrap(msg))
|
| 1415 |
+
if not wrapped_msg.endswith('\n'):
|
| 1416 |
+
wrapped_msg += '\n'
|
| 1417 |
+
self.per.bottom.insert("iomark linestart", wrapped_msg, "stderr")
|
| 1418 |
+
|
| 1419 |
+
def resetoutput(self):
|
| 1420 |
+
source = self.text.get("iomark", "end-1c")
|
| 1421 |
+
if self.history:
|
| 1422 |
+
self.history.store(source)
|
| 1423 |
+
if self.text.get("end-2c") != "\n":
|
| 1424 |
+
self.text.insert("end-1c", "\n")
|
| 1425 |
+
self.text.mark_set("iomark", "end-1c")
|
| 1426 |
+
self.set_line_and_column()
|
| 1427 |
+
self.ctip.remove_calltip_window()
|
| 1428 |
+
|
| 1429 |
+
def write(self, s, tags=()):
|
| 1430 |
+
try:
|
| 1431 |
+
self.text.mark_gravity("iomark", "right")
|
| 1432 |
+
count = OutputWindow.write(self, s, tags, "iomark")
|
| 1433 |
+
self.text.mark_gravity("iomark", "left")
|
| 1434 |
+
except:
|
| 1435 |
+
raise ###pass # ### 11Aug07 KBK if we are expecting exceptions
|
| 1436 |
+
# let's find out what they are and be specific.
|
| 1437 |
+
if self.canceled:
|
| 1438 |
+
self.canceled = False
|
| 1439 |
+
if not use_subprocess:
|
| 1440 |
+
raise KeyboardInterrupt
|
| 1441 |
+
return count
|
| 1442 |
+
|
| 1443 |
+
def rmenu_check_cut(self):
|
| 1444 |
+
try:
|
| 1445 |
+
if self.text.compare('sel.first', '<', 'iomark'):
|
| 1446 |
+
return 'disabled'
|
| 1447 |
+
except TclError: # no selection, so the index 'sel.first' doesn't exist
|
| 1448 |
+
return 'disabled'
|
| 1449 |
+
return super().rmenu_check_cut()
|
| 1450 |
+
|
| 1451 |
+
def rmenu_check_paste(self):
|
| 1452 |
+
if self.text.compare('insert','<','iomark'):
|
| 1453 |
+
return 'disabled'
|
| 1454 |
+
return super().rmenu_check_paste()
|
| 1455 |
+
|
| 1456 |
+
def squeeze_current_text_event(self, event=None):
|
| 1457 |
+
self.squeezer.squeeze_current_text()
|
| 1458 |
+
self.shell_sidebar.update_sidebar()
|
| 1459 |
+
|
| 1460 |
+
def on_squeezed_expand(self, index, text, tags):
|
| 1461 |
+
self.shell_sidebar.update_sidebar()
|
| 1462 |
+
|
| 1463 |
+
|
| 1464 |
+
def fix_x11_paste(root):
|
| 1465 |
+
"Make paste replace selection on x11. See issue #5124."
|
| 1466 |
+
if root._windowingsystem == 'x11':
|
| 1467 |
+
for cls in 'Text', 'Entry', 'Spinbox':
|
| 1468 |
+
root.bind_class(
|
| 1469 |
+
cls,
|
| 1470 |
+
'<<Paste>>',
|
| 1471 |
+
'catch {%W delete sel.first sel.last}\n' +
|
| 1472 |
+
root.bind_class(cls, '<<Paste>>'))
|
| 1473 |
+
|
| 1474 |
+
|
| 1475 |
+
usage_msg = """\
|
| 1476 |
+
|
| 1477 |
+
USAGE: idle [-deins] [-t title] [file]*
|
| 1478 |
+
idle [-dns] [-t title] (-c cmd | -r file) [arg]*
|
| 1479 |
+
idle [-dns] [-t title] - [arg]*
|
| 1480 |
+
|
| 1481 |
+
-h print this help message and exit
|
| 1482 |
+
-n run IDLE without a subprocess (DEPRECATED,
|
| 1483 |
+
see Help/IDLE Help for details)
|
| 1484 |
+
|
| 1485 |
+
The following options will override the IDLE 'settings' configuration:
|
| 1486 |
+
|
| 1487 |
+
-e open an edit window
|
| 1488 |
+
-i open a shell window
|
| 1489 |
+
|
| 1490 |
+
The following options imply -i and will open a shell:
|
| 1491 |
+
|
| 1492 |
+
-c cmd run the command in a shell, or
|
| 1493 |
+
-r file run script from file
|
| 1494 |
+
|
| 1495 |
+
-d enable the debugger
|
| 1496 |
+
-s run $IDLESTARTUP or $PYTHONSTARTUP before anything else
|
| 1497 |
+
-t title set title of shell window
|
| 1498 |
+
|
| 1499 |
+
A default edit window will be bypassed when -c, -r, or - are used.
|
| 1500 |
+
|
| 1501 |
+
[arg]* are passed to the command (-c) or script (-r) in sys.argv[1:].
|
| 1502 |
+
|
| 1503 |
+
Examples:
|
| 1504 |
+
|
| 1505 |
+
idle
|
| 1506 |
+
Open an edit window or shell depending on IDLE's configuration.
|
| 1507 |
+
|
| 1508 |
+
idle foo.py foobar.py
|
| 1509 |
+
Edit the files, also open a shell if configured to start with shell.
|
| 1510 |
+
|
| 1511 |
+
idle -est "Baz" foo.py
|
| 1512 |
+
Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell
|
| 1513 |
+
window with the title "Baz".
|
| 1514 |
+
|
| 1515 |
+
idle -c "import sys; print(sys.argv)" "foo"
|
| 1516 |
+
Open a shell window and run the command, passing "-c" in sys.argv[0]
|
| 1517 |
+
and "foo" in sys.argv[1].
|
| 1518 |
+
|
| 1519 |
+
idle -d -s -r foo.py "Hello World"
|
| 1520 |
+
Open a shell window, run a startup script, enable the debugger, and
|
| 1521 |
+
run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in
|
| 1522 |
+
sys.argv[1].
|
| 1523 |
+
|
| 1524 |
+
echo "import sys; print(sys.argv)" | idle - "foobar"
|
| 1525 |
+
Open a shell window, run the script piped in, passing '' in sys.argv[0]
|
| 1526 |
+
and "foobar" in sys.argv[1].
|
| 1527 |
+
"""
|
| 1528 |
+
|
| 1529 |
+
def main():
|
| 1530 |
+
import getopt
|
| 1531 |
+
from platform import system
|
| 1532 |
+
from idlelib import testing # bool value
|
| 1533 |
+
from idlelib import macosx
|
| 1534 |
+
|
| 1535 |
+
global flist, root, use_subprocess
|
| 1536 |
+
|
| 1537 |
+
capture_warnings(True)
|
| 1538 |
+
use_subprocess = True
|
| 1539 |
+
enable_shell = False
|
| 1540 |
+
enable_edit = False
|
| 1541 |
+
debug = False
|
| 1542 |
+
cmd = None
|
| 1543 |
+
script = None
|
| 1544 |
+
startup = False
|
| 1545 |
+
try:
|
| 1546 |
+
opts, args = getopt.getopt(sys.argv[1:], "c:deihnr:st:")
|
| 1547 |
+
except getopt.error as msg:
|
| 1548 |
+
print("Error: %s\n%s" % (msg, usage_msg), file=sys.stderr)
|
| 1549 |
+
sys.exit(2)
|
| 1550 |
+
for o, a in opts:
|
| 1551 |
+
if o == '-c':
|
| 1552 |
+
cmd = a
|
| 1553 |
+
enable_shell = True
|
| 1554 |
+
if o == '-d':
|
| 1555 |
+
debug = True
|
| 1556 |
+
enable_shell = True
|
| 1557 |
+
if o == '-e':
|
| 1558 |
+
enable_edit = True
|
| 1559 |
+
if o == '-h':
|
| 1560 |
+
sys.stdout.write(usage_msg)
|
| 1561 |
+
sys.exit()
|
| 1562 |
+
if o == '-i':
|
| 1563 |
+
enable_shell = True
|
| 1564 |
+
if o == '-n':
|
| 1565 |
+
print(" Warning: running IDLE without a subprocess is deprecated.",
|
| 1566 |
+
file=sys.stderr)
|
| 1567 |
+
use_subprocess = False
|
| 1568 |
+
if o == '-r':
|
| 1569 |
+
script = a
|
| 1570 |
+
if os.path.isfile(script):
|
| 1571 |
+
pass
|
| 1572 |
+
else:
|
| 1573 |
+
print("No script file: ", script)
|
| 1574 |
+
sys.exit()
|
| 1575 |
+
enable_shell = True
|
| 1576 |
+
if o == '-s':
|
| 1577 |
+
startup = True
|
| 1578 |
+
enable_shell = True
|
| 1579 |
+
if o == '-t':
|
| 1580 |
+
PyShell.shell_title = a
|
| 1581 |
+
enable_shell = True
|
| 1582 |
+
if args and args[0] == '-':
|
| 1583 |
+
cmd = sys.stdin.read()
|
| 1584 |
+
enable_shell = True
|
| 1585 |
+
# process sys.argv and sys.path:
|
| 1586 |
+
for i in range(len(sys.path)):
|
| 1587 |
+
sys.path[i] = os.path.abspath(sys.path[i])
|
| 1588 |
+
if args and args[0] == '-':
|
| 1589 |
+
sys.argv = [''] + args[1:]
|
| 1590 |
+
elif cmd:
|
| 1591 |
+
sys.argv = ['-c'] + args
|
| 1592 |
+
elif script:
|
| 1593 |
+
sys.argv = [script] + args
|
| 1594 |
+
elif args:
|
| 1595 |
+
enable_edit = True
|
| 1596 |
+
pathx = []
|
| 1597 |
+
for filename in args:
|
| 1598 |
+
pathx.append(os.path.dirname(filename))
|
| 1599 |
+
for dir in pathx:
|
| 1600 |
+
dir = os.path.abspath(dir)
|
| 1601 |
+
if not dir in sys.path:
|
| 1602 |
+
sys.path.insert(0, dir)
|
| 1603 |
+
else:
|
| 1604 |
+
dir = os.getcwd()
|
| 1605 |
+
if dir not in sys.path:
|
| 1606 |
+
sys.path.insert(0, dir)
|
| 1607 |
+
# check the IDLE settings configuration (but command line overrides)
|
| 1608 |
+
edit_start = idleConf.GetOption('main', 'General',
|
| 1609 |
+
'editor-on-startup', type='bool')
|
| 1610 |
+
enable_edit = enable_edit or edit_start
|
| 1611 |
+
enable_shell = enable_shell or not enable_edit
|
| 1612 |
+
|
| 1613 |
+
# Setup root. Don't break user code run in IDLE process.
|
| 1614 |
+
# Don't change environment when testing.
|
| 1615 |
+
if use_subprocess and not testing:
|
| 1616 |
+
NoDefaultRoot()
|
| 1617 |
+
root = Tk(className="Idle")
|
| 1618 |
+
root.withdraw()
|
| 1619 |
+
from idlelib.run import fix_scaling
|
| 1620 |
+
fix_scaling(root)
|
| 1621 |
+
|
| 1622 |
+
# set application icon
|
| 1623 |
+
icondir = os.path.join(os.path.dirname(__file__), 'Icons')
|
| 1624 |
+
if system() == 'Windows':
|
| 1625 |
+
iconfile = os.path.join(icondir, 'idle.ico')
|
| 1626 |
+
root.wm_iconbitmap(default=iconfile)
|
| 1627 |
+
elif not macosx.isAquaTk():
|
| 1628 |
+
if TkVersion >= 8.6:
|
| 1629 |
+
ext = '.png'
|
| 1630 |
+
sizes = (16, 32, 48, 256)
|
| 1631 |
+
else:
|
| 1632 |
+
ext = '.gif'
|
| 1633 |
+
sizes = (16, 32, 48)
|
| 1634 |
+
iconfiles = [os.path.join(icondir, 'idle_%d%s' % (size, ext))
|
| 1635 |
+
for size in sizes]
|
| 1636 |
+
icons = [PhotoImage(master=root, file=iconfile)
|
| 1637 |
+
for iconfile in iconfiles]
|
| 1638 |
+
root.wm_iconphoto(True, *icons)
|
| 1639 |
+
|
| 1640 |
+
# start editor and/or shell windows:
|
| 1641 |
+
fixwordbreaks(root)
|
| 1642 |
+
fix_x11_paste(root)
|
| 1643 |
+
flist = PyShellFileList(root)
|
| 1644 |
+
macosx.setupApp(root, flist)
|
| 1645 |
+
|
| 1646 |
+
if enable_edit:
|
| 1647 |
+
if not (cmd or script):
|
| 1648 |
+
for filename in args[:]:
|
| 1649 |
+
if flist.open(filename) is None:
|
| 1650 |
+
# filename is a directory actually, disconsider it
|
| 1651 |
+
args.remove(filename)
|
| 1652 |
+
if not args:
|
| 1653 |
+
flist.new()
|
| 1654 |
+
|
| 1655 |
+
if enable_shell:
|
| 1656 |
+
shell = flist.open_shell()
|
| 1657 |
+
if not shell:
|
| 1658 |
+
return # couldn't open shell
|
| 1659 |
+
if macosx.isAquaTk() and flist.dict:
|
| 1660 |
+
# On OSX: when the user has double-clicked on a file that causes
|
| 1661 |
+
# IDLE to be launched the shell window will open just in front of
|
| 1662 |
+
# the file she wants to see. Lower the interpreter window when
|
| 1663 |
+
# there are open files.
|
| 1664 |
+
shell.top.lower()
|
| 1665 |
+
else:
|
| 1666 |
+
shell = flist.pyshell
|
| 1667 |
+
|
| 1668 |
+
# Handle remaining options. If any of these are set, enable_shell
|
| 1669 |
+
# was set also, so shell must be true to reach here.
|
| 1670 |
+
if debug:
|
| 1671 |
+
shell.open_debugger()
|
| 1672 |
+
if startup:
|
| 1673 |
+
filename = os.environ.get("IDLESTARTUP") or \
|
| 1674 |
+
os.environ.get("PYTHONSTARTUP")
|
| 1675 |
+
if filename and os.path.isfile(filename):
|
| 1676 |
+
shell.interp.execfile(filename)
|
| 1677 |
+
if cmd or script:
|
| 1678 |
+
shell.interp.runcommand("""if 1:
|
| 1679 |
+
import sys as _sys
|
| 1680 |
+
_sys.argv = %r
|
| 1681 |
+
del _sys
|
| 1682 |
+
\n""" % (sys.argv,))
|
| 1683 |
+
if cmd:
|
| 1684 |
+
shell.interp.execsource(cmd)
|
| 1685 |
+
elif script:
|
| 1686 |
+
shell.interp.prepend_syspath(script)
|
| 1687 |
+
shell.interp.execfile(script)
|
| 1688 |
+
elif shell:
|
| 1689 |
+
# If there is a shell window and no cmd or script in progress,
|
| 1690 |
+
# check for problematic issues and print warning message(s) in
|
| 1691 |
+
# the IDLE shell window; this is less intrusive than always
|
| 1692 |
+
# opening a separate window.
|
| 1693 |
+
|
| 1694 |
+
# Warn if using a problematic OS X Tk version.
|
| 1695 |
+
tkversionwarning = macosx.tkVersionWarning(root)
|
| 1696 |
+
if tkversionwarning:
|
| 1697 |
+
shell.show_warning(tkversionwarning)
|
| 1698 |
+
|
| 1699 |
+
# Warn if the "Prefer tabs when opening documents" system
|
| 1700 |
+
# preference is set to "Always".
|
| 1701 |
+
prefer_tabs_preference_warning = macosx.preferTabsPreferenceWarning()
|
| 1702 |
+
if prefer_tabs_preference_warning:
|
| 1703 |
+
shell.show_warning(prefer_tabs_preference_warning)
|
| 1704 |
+
|
| 1705 |
+
while flist.inversedict: # keep IDLE running while files are open.
|
| 1706 |
+
root.mainloop()
|
| 1707 |
+
root.destroy()
|
| 1708 |
+
capture_warnings(False)
|
| 1709 |
+
|
| 1710 |
+
if __name__ == "__main__":
|
| 1711 |
+
main()
|
| 1712 |
+
|
| 1713 |
+
capture_warnings(False) # Make sure turned off; see issue 18081
|
parrot/lib/python3.10/idlelib/redirector.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
| 1 |
+
from tkinter import TclError
|
| 2 |
+
|
| 3 |
+
class WidgetRedirector:
|
| 4 |
+
"""Support for redirecting arbitrary widget subcommands.
|
| 5 |
+
|
| 6 |
+
Some Tk operations don't normally pass through tkinter. For example, if a
|
| 7 |
+
character is inserted into a Text widget by pressing a key, a default Tk
|
| 8 |
+
binding to the widget's 'insert' operation is activated, and the Tk library
|
| 9 |
+
processes the insert without calling back into tkinter.
|
| 10 |
+
|
| 11 |
+
Although a binding to <Key> could be made via tkinter, what we really want
|
| 12 |
+
to do is to hook the Tk 'insert' operation itself. For one thing, we want
|
| 13 |
+
a text.insert call in idle code to have the same effect as a key press.
|
| 14 |
+
|
| 15 |
+
When a widget is instantiated, a Tcl command is created whose name is the
|
| 16 |
+
same as the pathname widget._w. This command is used to invoke the various
|
| 17 |
+
widget operations, e.g. insert (for a Text widget). We are going to hook
|
| 18 |
+
this command and provide a facility ('register') to intercept the widget
|
| 19 |
+
operation. We will also intercept method calls on the tkinter class
|
| 20 |
+
instance that represents the tk widget.
|
| 21 |
+
|
| 22 |
+
In IDLE, WidgetRedirector is used in Percolator to intercept Text
|
| 23 |
+
commands. The function being registered provides access to the top
|
| 24 |
+
of a Percolator chain. At the bottom of the chain is a call to the
|
| 25 |
+
original Tk widget operation.
|
| 26 |
+
"""
|
| 27 |
+
def __init__(self, widget):
|
| 28 |
+
'''Initialize attributes and setup redirection.
|
| 29 |
+
|
| 30 |
+
_operations: dict mapping operation name to new function.
|
| 31 |
+
widget: the widget whose tcl command is to be intercepted.
|
| 32 |
+
tk: widget.tk, a convenience attribute, probably not needed.
|
| 33 |
+
orig: new name of the original tcl command.
|
| 34 |
+
|
| 35 |
+
Since renaming to orig fails with TclError when orig already
|
| 36 |
+
exists, only one WidgetDirector can exist for a given widget.
|
| 37 |
+
'''
|
| 38 |
+
self._operations = {}
|
| 39 |
+
self.widget = widget # widget instance
|
| 40 |
+
self.tk = tk = widget.tk # widget's root
|
| 41 |
+
w = widget._w # widget's (full) Tk pathname
|
| 42 |
+
self.orig = w + "_orig"
|
| 43 |
+
# Rename the Tcl command within Tcl:
|
| 44 |
+
tk.call("rename", w, self.orig)
|
| 45 |
+
# Create a new Tcl command whose name is the widget's pathname, and
|
| 46 |
+
# whose action is to dispatch on the operation passed to the widget:
|
| 47 |
+
tk.createcommand(w, self.dispatch)
|
| 48 |
+
|
| 49 |
+
def __repr__(self):
|
| 50 |
+
return "%s(%s<%s>)" % (self.__class__.__name__,
|
| 51 |
+
self.widget.__class__.__name__,
|
| 52 |
+
self.widget._w)
|
| 53 |
+
|
| 54 |
+
def close(self):
|
| 55 |
+
"Unregister operations and revert redirection created by .__init__."
|
| 56 |
+
for operation in list(self._operations):
|
| 57 |
+
self.unregister(operation)
|
| 58 |
+
widget = self.widget
|
| 59 |
+
tk = widget.tk
|
| 60 |
+
w = widget._w
|
| 61 |
+
# Restore the original widget Tcl command.
|
| 62 |
+
tk.deletecommand(w)
|
| 63 |
+
tk.call("rename", self.orig, w)
|
| 64 |
+
del self.widget, self.tk # Should not be needed
|
| 65 |
+
# if instance is deleted after close, as in Percolator.
|
| 66 |
+
|
| 67 |
+
def register(self, operation, function):
|
| 68 |
+
'''Return OriginalCommand(operation) after registering function.
|
| 69 |
+
|
| 70 |
+
Registration adds an operation: function pair to ._operations.
|
| 71 |
+
It also adds a widget function attribute that masks the tkinter
|
| 72 |
+
class instance method. Method masking operates independently
|
| 73 |
+
from command dispatch.
|
| 74 |
+
|
| 75 |
+
If a second function is registered for the same operation, the
|
| 76 |
+
first function is replaced in both places.
|
| 77 |
+
'''
|
| 78 |
+
self._operations[operation] = function
|
| 79 |
+
setattr(self.widget, operation, function)
|
| 80 |
+
return OriginalCommand(self, operation)
|
| 81 |
+
|
| 82 |
+
def unregister(self, operation):
|
| 83 |
+
'''Return the function for the operation, or None.
|
| 84 |
+
|
| 85 |
+
Deleting the instance attribute unmasks the class attribute.
|
| 86 |
+
'''
|
| 87 |
+
if operation in self._operations:
|
| 88 |
+
function = self._operations[operation]
|
| 89 |
+
del self._operations[operation]
|
| 90 |
+
try:
|
| 91 |
+
delattr(self.widget, operation)
|
| 92 |
+
except AttributeError:
|
| 93 |
+
pass
|
| 94 |
+
return function
|
| 95 |
+
else:
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
def dispatch(self, operation, *args):
|
| 99 |
+
'''Callback from Tcl which runs when the widget is referenced.
|
| 100 |
+
|
| 101 |
+
If an operation has been registered in self._operations, apply the
|
| 102 |
+
associated function to the args passed into Tcl. Otherwise, pass the
|
| 103 |
+
operation through to Tk via the original Tcl function.
|
| 104 |
+
|
| 105 |
+
Note that if a registered function is called, the operation is not
|
| 106 |
+
passed through to Tk. Apply the function returned by self.register()
|
| 107 |
+
to *args to accomplish that. For an example, see colorizer.py.
|
| 108 |
+
|
| 109 |
+
'''
|
| 110 |
+
m = self._operations.get(operation)
|
| 111 |
+
try:
|
| 112 |
+
if m:
|
| 113 |
+
return m(*args)
|
| 114 |
+
else:
|
| 115 |
+
return self.tk.call((self.orig, operation) + args)
|
| 116 |
+
except TclError:
|
| 117 |
+
return ""
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class OriginalCommand:
|
| 121 |
+
'''Callable for original tk command that has been redirected.
|
| 122 |
+
|
| 123 |
+
Returned by .register; can be used in the function registered.
|
| 124 |
+
redir = WidgetRedirector(text)
|
| 125 |
+
def my_insert(*args):
|
| 126 |
+
print("insert", args)
|
| 127 |
+
original_insert(*args)
|
| 128 |
+
original_insert = redir.register("insert", my_insert)
|
| 129 |
+
'''
|
| 130 |
+
|
| 131 |
+
def __init__(self, redir, operation):
|
| 132 |
+
'''Create .tk_call and .orig_and_operation for .__call__ method.
|
| 133 |
+
|
| 134 |
+
.redir and .operation store the input args for __repr__.
|
| 135 |
+
.tk and .orig copy attributes of .redir (probably not needed).
|
| 136 |
+
'''
|
| 137 |
+
self.redir = redir
|
| 138 |
+
self.operation = operation
|
| 139 |
+
self.tk = redir.tk # redundant with self.redir
|
| 140 |
+
self.orig = redir.orig # redundant with self.redir
|
| 141 |
+
# These two could be deleted after checking recipient code.
|
| 142 |
+
self.tk_call = redir.tk.call
|
| 143 |
+
self.orig_and_operation = (redir.orig, operation)
|
| 144 |
+
|
| 145 |
+
def __repr__(self):
|
| 146 |
+
return "%s(%r, %r)" % (self.__class__.__name__,
|
| 147 |
+
self.redir, self.operation)
|
| 148 |
+
|
| 149 |
+
def __call__(self, *args):
|
| 150 |
+
return self.tk_call(self.orig_and_operation + args)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _widget_redirector(parent): # htest #
|
| 154 |
+
from tkinter import Toplevel, Text
|
| 155 |
+
|
| 156 |
+
top = Toplevel(parent)
|
| 157 |
+
top.title("Test WidgetRedirector")
|
| 158 |
+
x, y = map(int, parent.geometry().split('+')[1:])
|
| 159 |
+
top.geometry("+%d+%d" % (x, y + 175))
|
| 160 |
+
text = Text(top)
|
| 161 |
+
text.pack()
|
| 162 |
+
text.focus_set()
|
| 163 |
+
redir = WidgetRedirector(text)
|
| 164 |
+
def my_insert(*args):
|
| 165 |
+
print("insert", args)
|
| 166 |
+
original_insert(*args)
|
| 167 |
+
original_insert = redir.register("insert", my_insert)
|
| 168 |
+
|
| 169 |
+
if __name__ == "__main__":
|
| 170 |
+
from unittest import main
|
| 171 |
+
main('idlelib.idle_test.test_redirector', verbosity=2, exit=False)
|
| 172 |
+
|
| 173 |
+
from idlelib.idle_test.htest import run
|
| 174 |
+
run(_widget_redirector)
|
parrot/lib/python3.10/idlelib/rpc.py
ADDED
|
@@ -0,0 +1,635 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RPC Implementation, originally written for the Python Idle IDE
|
| 2 |
+
|
| 3 |
+
For security reasons, GvR requested that Idle's Python execution server process
|
| 4 |
+
connect to the Idle process, which listens for the connection. Since Idle has
|
| 5 |
+
only one client per server, this was not a limitation.
|
| 6 |
+
|
| 7 |
+
+---------------------------------+ +-------------+
|
| 8 |
+
| socketserver.BaseRequestHandler | | SocketIO |
|
| 9 |
+
+---------------------------------+ +-------------+
|
| 10 |
+
^ | register() |
|
| 11 |
+
| | unregister()|
|
| 12 |
+
| +-------------+
|
| 13 |
+
| ^ ^
|
| 14 |
+
| | |
|
| 15 |
+
| + -------------------+ |
|
| 16 |
+
| | |
|
| 17 |
+
+-------------------------+ +-----------------+
|
| 18 |
+
| RPCHandler | | RPCClient |
|
| 19 |
+
| [attribute of RPCServer]| | |
|
| 20 |
+
+-------------------------+ +-----------------+
|
| 21 |
+
|
| 22 |
+
The RPCServer handler class is expected to provide register/unregister methods.
|
| 23 |
+
RPCHandler inherits the mix-in class SocketIO, which provides these methods.
|
| 24 |
+
|
| 25 |
+
See the Idle run.main() docstring for further information on how this was
|
| 26 |
+
accomplished in Idle.
|
| 27 |
+
|
| 28 |
+
"""
|
| 29 |
+
import builtins
|
| 30 |
+
import copyreg
|
| 31 |
+
import io
|
| 32 |
+
import marshal
|
| 33 |
+
import os
|
| 34 |
+
import pickle
|
| 35 |
+
import queue
|
| 36 |
+
import select
|
| 37 |
+
import socket
|
| 38 |
+
import socketserver
|
| 39 |
+
import struct
|
| 40 |
+
import sys
|
| 41 |
+
import threading
|
| 42 |
+
import traceback
|
| 43 |
+
import types
|
| 44 |
+
|
| 45 |
+
def unpickle_code(ms):
|
| 46 |
+
"Return code object from marshal string ms."
|
| 47 |
+
co = marshal.loads(ms)
|
| 48 |
+
assert isinstance(co, types.CodeType)
|
| 49 |
+
return co
|
| 50 |
+
|
| 51 |
+
def pickle_code(co):
|
| 52 |
+
"Return unpickle function and tuple with marshalled co code object."
|
| 53 |
+
assert isinstance(co, types.CodeType)
|
| 54 |
+
ms = marshal.dumps(co)
|
| 55 |
+
return unpickle_code, (ms,)
|
| 56 |
+
|
| 57 |
+
def dumps(obj, protocol=None):
|
| 58 |
+
"Return pickled (or marshalled) string for obj."
|
| 59 |
+
# IDLE passes 'None' to select pickle.DEFAULT_PROTOCOL.
|
| 60 |
+
f = io.BytesIO()
|
| 61 |
+
p = CodePickler(f, protocol)
|
| 62 |
+
p.dump(obj)
|
| 63 |
+
return f.getvalue()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class CodePickler(pickle.Pickler):
|
| 67 |
+
dispatch_table = {types.CodeType: pickle_code, **copyreg.dispatch_table}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
BUFSIZE = 8*1024
|
| 71 |
+
LOCALHOST = '127.0.0.1'
|
| 72 |
+
|
| 73 |
+
class RPCServer(socketserver.TCPServer):
|
| 74 |
+
|
| 75 |
+
def __init__(self, addr, handlerclass=None):
|
| 76 |
+
if handlerclass is None:
|
| 77 |
+
handlerclass = RPCHandler
|
| 78 |
+
socketserver.TCPServer.__init__(self, addr, handlerclass)
|
| 79 |
+
|
| 80 |
+
def server_bind(self):
|
| 81 |
+
"Override TCPServer method, no bind() phase for connecting entity"
|
| 82 |
+
pass
|
| 83 |
+
|
| 84 |
+
def server_activate(self):
|
| 85 |
+
"""Override TCPServer method, connect() instead of listen()
|
| 86 |
+
|
| 87 |
+
Due to the reversed connection, self.server_address is actually the
|
| 88 |
+
address of the Idle Client to which we are connecting.
|
| 89 |
+
|
| 90 |
+
"""
|
| 91 |
+
self.socket.connect(self.server_address)
|
| 92 |
+
|
| 93 |
+
def get_request(self):
|
| 94 |
+
"Override TCPServer method, return already connected socket"
|
| 95 |
+
return self.socket, self.server_address
|
| 96 |
+
|
| 97 |
+
def handle_error(self, request, client_address):
|
| 98 |
+
"""Override TCPServer method
|
| 99 |
+
|
| 100 |
+
Error message goes to __stderr__. No error message if exiting
|
| 101 |
+
normally or socket raised EOF. Other exceptions not handled in
|
| 102 |
+
server code will cause os._exit.
|
| 103 |
+
|
| 104 |
+
"""
|
| 105 |
+
try:
|
| 106 |
+
raise
|
| 107 |
+
except SystemExit:
|
| 108 |
+
raise
|
| 109 |
+
except:
|
| 110 |
+
erf = sys.__stderr__
|
| 111 |
+
print('\n' + '-'*40, file=erf)
|
| 112 |
+
print('Unhandled server exception!', file=erf)
|
| 113 |
+
print('Thread: %s' % threading.current_thread().name, file=erf)
|
| 114 |
+
print('Client Address: ', client_address, file=erf)
|
| 115 |
+
print('Request: ', repr(request), file=erf)
|
| 116 |
+
traceback.print_exc(file=erf)
|
| 117 |
+
print('\n*** Unrecoverable, server exiting!', file=erf)
|
| 118 |
+
print('-'*40, file=erf)
|
| 119 |
+
os._exit(0)
|
| 120 |
+
|
| 121 |
+
#----------------- end class RPCServer --------------------
|
| 122 |
+
|
| 123 |
+
objecttable = {}
|
| 124 |
+
request_queue = queue.Queue(0)
|
| 125 |
+
response_queue = queue.Queue(0)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class SocketIO:
|
| 129 |
+
|
| 130 |
+
nextseq = 0
|
| 131 |
+
|
| 132 |
+
def __init__(self, sock, objtable=None, debugging=None):
|
| 133 |
+
self.sockthread = threading.current_thread()
|
| 134 |
+
if debugging is not None:
|
| 135 |
+
self.debugging = debugging
|
| 136 |
+
self.sock = sock
|
| 137 |
+
if objtable is None:
|
| 138 |
+
objtable = objecttable
|
| 139 |
+
self.objtable = objtable
|
| 140 |
+
self.responses = {}
|
| 141 |
+
self.cvars = {}
|
| 142 |
+
|
| 143 |
+
def close(self):
|
| 144 |
+
sock = self.sock
|
| 145 |
+
self.sock = None
|
| 146 |
+
if sock is not None:
|
| 147 |
+
sock.close()
|
| 148 |
+
|
| 149 |
+
def exithook(self):
|
| 150 |
+
"override for specific exit action"
|
| 151 |
+
os._exit(0)
|
| 152 |
+
|
| 153 |
+
def debug(self, *args):
|
| 154 |
+
if not self.debugging:
|
| 155 |
+
return
|
| 156 |
+
s = self.location + " " + str(threading.current_thread().name)
|
| 157 |
+
for a in args:
|
| 158 |
+
s = s + " " + str(a)
|
| 159 |
+
print(s, file=sys.__stderr__)
|
| 160 |
+
|
| 161 |
+
def register(self, oid, object):
|
| 162 |
+
self.objtable[oid] = object
|
| 163 |
+
|
| 164 |
+
def unregister(self, oid):
|
| 165 |
+
try:
|
| 166 |
+
del self.objtable[oid]
|
| 167 |
+
except KeyError:
|
| 168 |
+
pass
|
| 169 |
+
|
| 170 |
+
def localcall(self, seq, request):
|
| 171 |
+
self.debug("localcall:", request)
|
| 172 |
+
try:
|
| 173 |
+
how, (oid, methodname, args, kwargs) = request
|
| 174 |
+
except TypeError:
|
| 175 |
+
return ("ERROR", "Bad request format")
|
| 176 |
+
if oid not in self.objtable:
|
| 177 |
+
return ("ERROR", "Unknown object id: %r" % (oid,))
|
| 178 |
+
obj = self.objtable[oid]
|
| 179 |
+
if methodname == "__methods__":
|
| 180 |
+
methods = {}
|
| 181 |
+
_getmethods(obj, methods)
|
| 182 |
+
return ("OK", methods)
|
| 183 |
+
if methodname == "__attributes__":
|
| 184 |
+
attributes = {}
|
| 185 |
+
_getattributes(obj, attributes)
|
| 186 |
+
return ("OK", attributes)
|
| 187 |
+
if not hasattr(obj, methodname):
|
| 188 |
+
return ("ERROR", "Unsupported method name: %r" % (methodname,))
|
| 189 |
+
method = getattr(obj, methodname)
|
| 190 |
+
try:
|
| 191 |
+
if how == 'CALL':
|
| 192 |
+
ret = method(*args, **kwargs)
|
| 193 |
+
if isinstance(ret, RemoteObject):
|
| 194 |
+
ret = remoteref(ret)
|
| 195 |
+
return ("OK", ret)
|
| 196 |
+
elif how == 'QUEUE':
|
| 197 |
+
request_queue.put((seq, (method, args, kwargs)))
|
| 198 |
+
return("QUEUED", None)
|
| 199 |
+
else:
|
| 200 |
+
return ("ERROR", "Unsupported message type: %s" % how)
|
| 201 |
+
except SystemExit:
|
| 202 |
+
raise
|
| 203 |
+
except KeyboardInterrupt:
|
| 204 |
+
raise
|
| 205 |
+
except OSError:
|
| 206 |
+
raise
|
| 207 |
+
except Exception as ex:
|
| 208 |
+
return ("CALLEXC", ex)
|
| 209 |
+
except:
|
| 210 |
+
msg = "*** Internal Error: rpc.py:SocketIO.localcall()\n\n"\
|
| 211 |
+
" Object: %s \n Method: %s \n Args: %s\n"
|
| 212 |
+
print(msg % (oid, method, args), file=sys.__stderr__)
|
| 213 |
+
traceback.print_exc(file=sys.__stderr__)
|
| 214 |
+
return ("EXCEPTION", None)
|
| 215 |
+
|
| 216 |
+
def remotecall(self, oid, methodname, args, kwargs):
|
| 217 |
+
self.debug("remotecall:asynccall: ", oid, methodname)
|
| 218 |
+
seq = self.asynccall(oid, methodname, args, kwargs)
|
| 219 |
+
return self.asyncreturn(seq)
|
| 220 |
+
|
| 221 |
+
def remotequeue(self, oid, methodname, args, kwargs):
|
| 222 |
+
self.debug("remotequeue:asyncqueue: ", oid, methodname)
|
| 223 |
+
seq = self.asyncqueue(oid, methodname, args, kwargs)
|
| 224 |
+
return self.asyncreturn(seq)
|
| 225 |
+
|
| 226 |
+
def asynccall(self, oid, methodname, args, kwargs):
|
| 227 |
+
request = ("CALL", (oid, methodname, args, kwargs))
|
| 228 |
+
seq = self.newseq()
|
| 229 |
+
if threading.current_thread() != self.sockthread:
|
| 230 |
+
cvar = threading.Condition()
|
| 231 |
+
self.cvars[seq] = cvar
|
| 232 |
+
self.debug(("asynccall:%d:" % seq), oid, methodname, args, kwargs)
|
| 233 |
+
self.putmessage((seq, request))
|
| 234 |
+
return seq
|
| 235 |
+
|
| 236 |
+
def asyncqueue(self, oid, methodname, args, kwargs):
|
| 237 |
+
request = ("QUEUE", (oid, methodname, args, kwargs))
|
| 238 |
+
seq = self.newseq()
|
| 239 |
+
if threading.current_thread() != self.sockthread:
|
| 240 |
+
cvar = threading.Condition()
|
| 241 |
+
self.cvars[seq] = cvar
|
| 242 |
+
self.debug(("asyncqueue:%d:" % seq), oid, methodname, args, kwargs)
|
| 243 |
+
self.putmessage((seq, request))
|
| 244 |
+
return seq
|
| 245 |
+
|
| 246 |
+
def asyncreturn(self, seq):
|
| 247 |
+
self.debug("asyncreturn:%d:call getresponse(): " % seq)
|
| 248 |
+
response = self.getresponse(seq, wait=0.05)
|
| 249 |
+
self.debug(("asyncreturn:%d:response: " % seq), response)
|
| 250 |
+
return self.decoderesponse(response)
|
| 251 |
+
|
| 252 |
+
def decoderesponse(self, response):
|
| 253 |
+
how, what = response
|
| 254 |
+
if how == "OK":
|
| 255 |
+
return what
|
| 256 |
+
if how == "QUEUED":
|
| 257 |
+
return None
|
| 258 |
+
if how == "EXCEPTION":
|
| 259 |
+
self.debug("decoderesponse: EXCEPTION")
|
| 260 |
+
return None
|
| 261 |
+
if how == "EOF":
|
| 262 |
+
self.debug("decoderesponse: EOF")
|
| 263 |
+
self.decode_interrupthook()
|
| 264 |
+
return None
|
| 265 |
+
if how == "ERROR":
|
| 266 |
+
self.debug("decoderesponse: Internal ERROR:", what)
|
| 267 |
+
raise RuntimeError(what)
|
| 268 |
+
if how == "CALLEXC":
|
| 269 |
+
self.debug("decoderesponse: Call Exception:", what)
|
| 270 |
+
raise what
|
| 271 |
+
raise SystemError(how, what)
|
| 272 |
+
|
| 273 |
+
def decode_interrupthook(self):
|
| 274 |
+
""
|
| 275 |
+
raise EOFError
|
| 276 |
+
|
| 277 |
+
def mainloop(self):
|
| 278 |
+
"""Listen on socket until I/O not ready or EOF
|
| 279 |
+
|
| 280 |
+
pollresponse() will loop looking for seq number None, which
|
| 281 |
+
never comes, and exit on EOFError.
|
| 282 |
+
|
| 283 |
+
"""
|
| 284 |
+
try:
|
| 285 |
+
self.getresponse(myseq=None, wait=0.05)
|
| 286 |
+
except EOFError:
|
| 287 |
+
self.debug("mainloop:return")
|
| 288 |
+
return
|
| 289 |
+
|
| 290 |
+
def getresponse(self, myseq, wait):
|
| 291 |
+
response = self._getresponse(myseq, wait)
|
| 292 |
+
if response is not None:
|
| 293 |
+
how, what = response
|
| 294 |
+
if how == "OK":
|
| 295 |
+
response = how, self._proxify(what)
|
| 296 |
+
return response
|
| 297 |
+
|
| 298 |
+
def _proxify(self, obj):
|
| 299 |
+
if isinstance(obj, RemoteProxy):
|
| 300 |
+
return RPCProxy(self, obj.oid)
|
| 301 |
+
if isinstance(obj, list):
|
| 302 |
+
return list(map(self._proxify, obj))
|
| 303 |
+
# XXX Check for other types -- not currently needed
|
| 304 |
+
return obj
|
| 305 |
+
|
| 306 |
+
def _getresponse(self, myseq, wait):
|
| 307 |
+
self.debug("_getresponse:myseq:", myseq)
|
| 308 |
+
if threading.current_thread() is self.sockthread:
|
| 309 |
+
# this thread does all reading of requests or responses
|
| 310 |
+
while True:
|
| 311 |
+
response = self.pollresponse(myseq, wait)
|
| 312 |
+
if response is not None:
|
| 313 |
+
return response
|
| 314 |
+
else:
|
| 315 |
+
# wait for notification from socket handling thread
|
| 316 |
+
cvar = self.cvars[myseq]
|
| 317 |
+
cvar.acquire()
|
| 318 |
+
while myseq not in self.responses:
|
| 319 |
+
cvar.wait()
|
| 320 |
+
response = self.responses[myseq]
|
| 321 |
+
self.debug("_getresponse:%s: thread woke up: response: %s" %
|
| 322 |
+
(myseq, response))
|
| 323 |
+
del self.responses[myseq]
|
| 324 |
+
del self.cvars[myseq]
|
| 325 |
+
cvar.release()
|
| 326 |
+
return response
|
| 327 |
+
|
| 328 |
+
def newseq(self):
|
| 329 |
+
self.nextseq = seq = self.nextseq + 2
|
| 330 |
+
return seq
|
| 331 |
+
|
| 332 |
+
def putmessage(self, message):
|
| 333 |
+
self.debug("putmessage:%d:" % message[0])
|
| 334 |
+
try:
|
| 335 |
+
s = dumps(message)
|
| 336 |
+
except pickle.PicklingError:
|
| 337 |
+
print("Cannot pickle:", repr(message), file=sys.__stderr__)
|
| 338 |
+
raise
|
| 339 |
+
s = struct.pack("<i", len(s)) + s
|
| 340 |
+
while len(s) > 0:
|
| 341 |
+
try:
|
| 342 |
+
r, w, x = select.select([], [self.sock], [])
|
| 343 |
+
n = self.sock.send(s[:BUFSIZE])
|
| 344 |
+
except (AttributeError, TypeError):
|
| 345 |
+
raise OSError("socket no longer exists")
|
| 346 |
+
s = s[n:]
|
| 347 |
+
|
| 348 |
+
buff = b''
|
| 349 |
+
bufneed = 4
|
| 350 |
+
bufstate = 0 # meaning: 0 => reading count; 1 => reading data
|
| 351 |
+
|
| 352 |
+
def pollpacket(self, wait):
|
| 353 |
+
self._stage0()
|
| 354 |
+
if len(self.buff) < self.bufneed:
|
| 355 |
+
r, w, x = select.select([self.sock.fileno()], [], [], wait)
|
| 356 |
+
if len(r) == 0:
|
| 357 |
+
return None
|
| 358 |
+
try:
|
| 359 |
+
s = self.sock.recv(BUFSIZE)
|
| 360 |
+
except OSError:
|
| 361 |
+
raise EOFError
|
| 362 |
+
if len(s) == 0:
|
| 363 |
+
raise EOFError
|
| 364 |
+
self.buff += s
|
| 365 |
+
self._stage0()
|
| 366 |
+
return self._stage1()
|
| 367 |
+
|
| 368 |
+
def _stage0(self):
|
| 369 |
+
if self.bufstate == 0 and len(self.buff) >= 4:
|
| 370 |
+
s = self.buff[:4]
|
| 371 |
+
self.buff = self.buff[4:]
|
| 372 |
+
self.bufneed = struct.unpack("<i", s)[0]
|
| 373 |
+
self.bufstate = 1
|
| 374 |
+
|
| 375 |
+
def _stage1(self):
|
| 376 |
+
if self.bufstate == 1 and len(self.buff) >= self.bufneed:
|
| 377 |
+
packet = self.buff[:self.bufneed]
|
| 378 |
+
self.buff = self.buff[self.bufneed:]
|
| 379 |
+
self.bufneed = 4
|
| 380 |
+
self.bufstate = 0
|
| 381 |
+
return packet
|
| 382 |
+
|
| 383 |
+
def pollmessage(self, wait):
|
| 384 |
+
packet = self.pollpacket(wait)
|
| 385 |
+
if packet is None:
|
| 386 |
+
return None
|
| 387 |
+
try:
|
| 388 |
+
message = pickle.loads(packet)
|
| 389 |
+
except pickle.UnpicklingError:
|
| 390 |
+
print("-----------------------", file=sys.__stderr__)
|
| 391 |
+
print("cannot unpickle packet:", repr(packet), file=sys.__stderr__)
|
| 392 |
+
traceback.print_stack(file=sys.__stderr__)
|
| 393 |
+
print("-----------------------", file=sys.__stderr__)
|
| 394 |
+
raise
|
| 395 |
+
return message
|
| 396 |
+
|
| 397 |
+
def pollresponse(self, myseq, wait):
|
| 398 |
+
"""Handle messages received on the socket.
|
| 399 |
+
|
| 400 |
+
Some messages received may be asynchronous 'call' or 'queue' requests,
|
| 401 |
+
and some may be responses for other threads.
|
| 402 |
+
|
| 403 |
+
'call' requests are passed to self.localcall() with the expectation of
|
| 404 |
+
immediate execution, during which time the socket is not serviced.
|
| 405 |
+
|
| 406 |
+
'queue' requests are used for tasks (which may block or hang) to be
|
| 407 |
+
processed in a different thread. These requests are fed into
|
| 408 |
+
request_queue by self.localcall(). Responses to queued requests are
|
| 409 |
+
taken from response_queue and sent across the link with the associated
|
| 410 |
+
sequence numbers. Messages in the queues are (sequence_number,
|
| 411 |
+
request/response) tuples and code using this module removing messages
|
| 412 |
+
from the request_queue is responsible for returning the correct
|
| 413 |
+
sequence number in the response_queue.
|
| 414 |
+
|
| 415 |
+
pollresponse() will loop until a response message with the myseq
|
| 416 |
+
sequence number is received, and will save other responses in
|
| 417 |
+
self.responses and notify the owning thread.
|
| 418 |
+
|
| 419 |
+
"""
|
| 420 |
+
while True:
|
| 421 |
+
# send queued response if there is one available
|
| 422 |
+
try:
|
| 423 |
+
qmsg = response_queue.get(0)
|
| 424 |
+
except queue.Empty:
|
| 425 |
+
pass
|
| 426 |
+
else:
|
| 427 |
+
seq, response = qmsg
|
| 428 |
+
message = (seq, ('OK', response))
|
| 429 |
+
self.putmessage(message)
|
| 430 |
+
# poll for message on link
|
| 431 |
+
try:
|
| 432 |
+
message = self.pollmessage(wait)
|
| 433 |
+
if message is None: # socket not ready
|
| 434 |
+
return None
|
| 435 |
+
except EOFError:
|
| 436 |
+
self.handle_EOF()
|
| 437 |
+
return None
|
| 438 |
+
except AttributeError:
|
| 439 |
+
return None
|
| 440 |
+
seq, resq = message
|
| 441 |
+
how = resq[0]
|
| 442 |
+
self.debug("pollresponse:%d:myseq:%s" % (seq, myseq))
|
| 443 |
+
# process or queue a request
|
| 444 |
+
if how in ("CALL", "QUEUE"):
|
| 445 |
+
self.debug("pollresponse:%d:localcall:call:" % seq)
|
| 446 |
+
response = self.localcall(seq, resq)
|
| 447 |
+
self.debug("pollresponse:%d:localcall:response:%s"
|
| 448 |
+
% (seq, response))
|
| 449 |
+
if how == "CALL":
|
| 450 |
+
self.putmessage((seq, response))
|
| 451 |
+
elif how == "QUEUE":
|
| 452 |
+
# don't acknowledge the 'queue' request!
|
| 453 |
+
pass
|
| 454 |
+
continue
|
| 455 |
+
# return if completed message transaction
|
| 456 |
+
elif seq == myseq:
|
| 457 |
+
return resq
|
| 458 |
+
# must be a response for a different thread:
|
| 459 |
+
else:
|
| 460 |
+
cv = self.cvars.get(seq, None)
|
| 461 |
+
# response involving unknown sequence number is discarded,
|
| 462 |
+
# probably intended for prior incarnation of server
|
| 463 |
+
if cv is not None:
|
| 464 |
+
cv.acquire()
|
| 465 |
+
self.responses[seq] = resq
|
| 466 |
+
cv.notify()
|
| 467 |
+
cv.release()
|
| 468 |
+
continue
|
| 469 |
+
|
| 470 |
+
def handle_EOF(self):
|
| 471 |
+
"action taken upon link being closed by peer"
|
| 472 |
+
self.EOFhook()
|
| 473 |
+
self.debug("handle_EOF")
|
| 474 |
+
for key in self.cvars:
|
| 475 |
+
cv = self.cvars[key]
|
| 476 |
+
cv.acquire()
|
| 477 |
+
self.responses[key] = ('EOF', None)
|
| 478 |
+
cv.notify()
|
| 479 |
+
cv.release()
|
| 480 |
+
# call our (possibly overridden) exit function
|
| 481 |
+
self.exithook()
|
| 482 |
+
|
| 483 |
+
def EOFhook(self):
|
| 484 |
+
"Classes using rpc client/server can override to augment EOF action"
|
| 485 |
+
pass
|
| 486 |
+
|
| 487 |
+
#----------------- end class SocketIO --------------------
|
| 488 |
+
|
| 489 |
+
class RemoteObject:
|
| 490 |
+
# Token mix-in class
|
| 491 |
+
pass
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def remoteref(obj):
|
| 495 |
+
oid = id(obj)
|
| 496 |
+
objecttable[oid] = obj
|
| 497 |
+
return RemoteProxy(oid)
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
class RemoteProxy:
|
| 501 |
+
|
| 502 |
+
def __init__(self, oid):
|
| 503 |
+
self.oid = oid
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
class RPCHandler(socketserver.BaseRequestHandler, SocketIO):
|
| 507 |
+
|
| 508 |
+
debugging = False
|
| 509 |
+
location = "#S" # Server
|
| 510 |
+
|
| 511 |
+
def __init__(self, sock, addr, svr):
|
| 512 |
+
svr.current_handler = self ## cgt xxx
|
| 513 |
+
SocketIO.__init__(self, sock)
|
| 514 |
+
socketserver.BaseRequestHandler.__init__(self, sock, addr, svr)
|
| 515 |
+
|
| 516 |
+
def handle(self):
|
| 517 |
+
"handle() method required by socketserver"
|
| 518 |
+
self.mainloop()
|
| 519 |
+
|
| 520 |
+
def get_remote_proxy(self, oid):
|
| 521 |
+
return RPCProxy(self, oid)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
class RPCClient(SocketIO):
|
| 525 |
+
|
| 526 |
+
debugging = False
|
| 527 |
+
location = "#C" # Client
|
| 528 |
+
|
| 529 |
+
nextseq = 1 # Requests coming from the client are odd numbered
|
| 530 |
+
|
| 531 |
+
def __init__(self, address, family=socket.AF_INET, type=socket.SOCK_STREAM):
|
| 532 |
+
self.listening_sock = socket.socket(family, type)
|
| 533 |
+
self.listening_sock.bind(address)
|
| 534 |
+
self.listening_sock.listen(1)
|
| 535 |
+
|
| 536 |
+
def accept(self):
|
| 537 |
+
working_sock, address = self.listening_sock.accept()
|
| 538 |
+
if self.debugging:
|
| 539 |
+
print("****** Connection request from ", address, file=sys.__stderr__)
|
| 540 |
+
if address[0] == LOCALHOST:
|
| 541 |
+
SocketIO.__init__(self, working_sock)
|
| 542 |
+
else:
|
| 543 |
+
print("** Invalid host: ", address, file=sys.__stderr__)
|
| 544 |
+
raise OSError
|
| 545 |
+
|
| 546 |
+
def get_remote_proxy(self, oid):
|
| 547 |
+
return RPCProxy(self, oid)
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
class RPCProxy:
|
| 551 |
+
|
| 552 |
+
__methods = None
|
| 553 |
+
__attributes = None
|
| 554 |
+
|
| 555 |
+
def __init__(self, sockio, oid):
|
| 556 |
+
self.sockio = sockio
|
| 557 |
+
self.oid = oid
|
| 558 |
+
|
| 559 |
+
def __getattr__(self, name):
|
| 560 |
+
if self.__methods is None:
|
| 561 |
+
self.__getmethods()
|
| 562 |
+
if self.__methods.get(name):
|
| 563 |
+
return MethodProxy(self.sockio, self.oid, name)
|
| 564 |
+
if self.__attributes is None:
|
| 565 |
+
self.__getattributes()
|
| 566 |
+
if name in self.__attributes:
|
| 567 |
+
value = self.sockio.remotecall(self.oid, '__getattribute__',
|
| 568 |
+
(name,), {})
|
| 569 |
+
return value
|
| 570 |
+
else:
|
| 571 |
+
raise AttributeError(name)
|
| 572 |
+
|
| 573 |
+
def __getattributes(self):
|
| 574 |
+
self.__attributes = self.sockio.remotecall(self.oid,
|
| 575 |
+
"__attributes__", (), {})
|
| 576 |
+
|
| 577 |
+
def __getmethods(self):
|
| 578 |
+
self.__methods = self.sockio.remotecall(self.oid,
|
| 579 |
+
"__methods__", (), {})
|
| 580 |
+
|
| 581 |
+
def _getmethods(obj, methods):
|
| 582 |
+
# Helper to get a list of methods from an object
|
| 583 |
+
# Adds names to dictionary argument 'methods'
|
| 584 |
+
for name in dir(obj):
|
| 585 |
+
attr = getattr(obj, name)
|
| 586 |
+
if callable(attr):
|
| 587 |
+
methods[name] = 1
|
| 588 |
+
if isinstance(obj, type):
|
| 589 |
+
for super in obj.__bases__:
|
| 590 |
+
_getmethods(super, methods)
|
| 591 |
+
|
| 592 |
+
def _getattributes(obj, attributes):
|
| 593 |
+
for name in dir(obj):
|
| 594 |
+
attr = getattr(obj, name)
|
| 595 |
+
if not callable(attr):
|
| 596 |
+
attributes[name] = 1
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
class MethodProxy:
|
| 600 |
+
|
| 601 |
+
def __init__(self, sockio, oid, name):
|
| 602 |
+
self.sockio = sockio
|
| 603 |
+
self.oid = oid
|
| 604 |
+
self.name = name
|
| 605 |
+
|
| 606 |
+
def __call__(self, /, *args, **kwargs):
|
| 607 |
+
value = self.sockio.remotecall(self.oid, self.name, args, kwargs)
|
| 608 |
+
return value
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
# XXX KBK 09Sep03 We need a proper unit test for this module. Previously
|
| 612 |
+
# existing test code was removed at Rev 1.27 (r34098).
|
| 613 |
+
|
| 614 |
+
def displayhook(value):
|
| 615 |
+
"""Override standard display hook to use non-locale encoding"""
|
| 616 |
+
if value is None:
|
| 617 |
+
return
|
| 618 |
+
# Set '_' to None to avoid recursion
|
| 619 |
+
builtins._ = None
|
| 620 |
+
text = repr(value)
|
| 621 |
+
try:
|
| 622 |
+
sys.stdout.write(text)
|
| 623 |
+
except UnicodeEncodeError:
|
| 624 |
+
# let's use ascii while utf8-bmp codec doesn't present
|
| 625 |
+
encoding = 'ascii'
|
| 626 |
+
bytes = text.encode(encoding, 'backslashreplace')
|
| 627 |
+
text = bytes.decode(encoding, 'strict')
|
| 628 |
+
sys.stdout.write(text)
|
| 629 |
+
sys.stdout.write("\n")
|
| 630 |
+
builtins._ = value
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
if __name__ == '__main__':
|
| 634 |
+
from unittest import main
|
| 635 |
+
main('idlelib.idle_test.test_rpc', verbosity=2,)
|
parrot/lib/python3.10/idlelib/run.py
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" idlelib.run
|
| 2 |
+
|
| 3 |
+
Simplified, pyshell.ModifiedInterpreter spawns a subprocess with
|
| 4 |
+
f'''{sys.executable} -c "__import__('idlelib.run').run.main()"'''
|
| 5 |
+
'.run' is needed because __import__ returns idlelib, not idlelib.run.
|
| 6 |
+
"""
|
| 7 |
+
import contextlib
|
| 8 |
+
import functools
|
| 9 |
+
import io
|
| 10 |
+
import linecache
|
| 11 |
+
import queue
|
| 12 |
+
import sys
|
| 13 |
+
import textwrap
|
| 14 |
+
import time
|
| 15 |
+
import traceback
|
| 16 |
+
import _thread as thread
|
| 17 |
+
import threading
|
| 18 |
+
import warnings
|
| 19 |
+
|
| 20 |
+
import idlelib # testing
|
| 21 |
+
from idlelib import autocomplete # AutoComplete, fetch_encodings
|
| 22 |
+
from idlelib import calltip # Calltip
|
| 23 |
+
from idlelib import debugger_r # start_debugger
|
| 24 |
+
from idlelib import debugobj_r # remote_object_tree_item
|
| 25 |
+
from idlelib import iomenu # encoding
|
| 26 |
+
from idlelib import rpc # multiple objects
|
| 27 |
+
from idlelib import stackviewer # StackTreeItem
|
| 28 |
+
import __main__
|
| 29 |
+
|
| 30 |
+
import tkinter # Use tcl and, if startup fails, messagebox.
|
| 31 |
+
if not hasattr(sys.modules['idlelib.run'], 'firstrun'):
|
| 32 |
+
# Undo modifications of tkinter by idlelib imports; see bpo-25507.
|
| 33 |
+
for mod in ('simpledialog', 'messagebox', 'font',
|
| 34 |
+
'dialog', 'filedialog', 'commondialog',
|
| 35 |
+
'ttk'):
|
| 36 |
+
delattr(tkinter, mod)
|
| 37 |
+
del sys.modules['tkinter.' + mod]
|
| 38 |
+
# Avoid AttributeError if run again; see bpo-37038.
|
| 39 |
+
sys.modules['idlelib.run'].firstrun = False
|
| 40 |
+
|
| 41 |
+
LOCALHOST = '127.0.0.1'
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
eof = 'Ctrl-D (end-of-file)'
|
| 45 |
+
exit.eof = eof
|
| 46 |
+
quit.eof = eof
|
| 47 |
+
except NameError: # In case subprocess started with -S (maybe in future).
|
| 48 |
+
pass
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def idle_formatwarning(message, category, filename, lineno, line=None):
|
| 52 |
+
"""Format warnings the IDLE way."""
|
| 53 |
+
|
| 54 |
+
s = "\nWarning (from warnings module):\n"
|
| 55 |
+
s += ' File \"%s\", line %s\n' % (filename, lineno)
|
| 56 |
+
if line is None:
|
| 57 |
+
line = linecache.getline(filename, lineno)
|
| 58 |
+
line = line.strip()
|
| 59 |
+
if line:
|
| 60 |
+
s += " %s\n" % line
|
| 61 |
+
s += "%s: %s\n" % (category.__name__, message)
|
| 62 |
+
return s
|
| 63 |
+
|
| 64 |
+
def idle_showwarning_subproc(
|
| 65 |
+
message, category, filename, lineno, file=None, line=None):
|
| 66 |
+
"""Show Idle-format warning after replacing warnings.showwarning.
|
| 67 |
+
|
| 68 |
+
The only difference is the formatter called.
|
| 69 |
+
"""
|
| 70 |
+
if file is None:
|
| 71 |
+
file = sys.stderr
|
| 72 |
+
try:
|
| 73 |
+
file.write(idle_formatwarning(
|
| 74 |
+
message, category, filename, lineno, line))
|
| 75 |
+
except OSError:
|
| 76 |
+
pass # the file (probably stderr) is invalid - this warning gets lost.
|
| 77 |
+
|
| 78 |
+
_warnings_showwarning = None
|
| 79 |
+
|
| 80 |
+
def capture_warnings(capture):
|
| 81 |
+
"Replace warning.showwarning with idle_showwarning_subproc, or reverse."
|
| 82 |
+
|
| 83 |
+
global _warnings_showwarning
|
| 84 |
+
if capture:
|
| 85 |
+
if _warnings_showwarning is None:
|
| 86 |
+
_warnings_showwarning = warnings.showwarning
|
| 87 |
+
warnings.showwarning = idle_showwarning_subproc
|
| 88 |
+
else:
|
| 89 |
+
if _warnings_showwarning is not None:
|
| 90 |
+
warnings.showwarning = _warnings_showwarning
|
| 91 |
+
_warnings_showwarning = None
|
| 92 |
+
|
| 93 |
+
capture_warnings(True)
|
| 94 |
+
tcl = tkinter.Tcl()
|
| 95 |
+
|
| 96 |
+
def handle_tk_events(tcl=tcl):
|
| 97 |
+
"""Process any tk events that are ready to be dispatched if tkinter
|
| 98 |
+
has been imported, a tcl interpreter has been created and tk has been
|
| 99 |
+
loaded."""
|
| 100 |
+
tcl.eval("update")
|
| 101 |
+
|
| 102 |
+
# Thread shared globals: Establish a queue between a subthread (which handles
|
| 103 |
+
# the socket) and the main thread (which runs user code), plus global
|
| 104 |
+
# completion, exit and interruptable (the main thread) flags:
|
| 105 |
+
|
| 106 |
+
exit_now = False
|
| 107 |
+
quitting = False
|
| 108 |
+
interruptable = False
|
| 109 |
+
|
| 110 |
+
def main(del_exitfunc=False):
|
| 111 |
+
"""Start the Python execution server in a subprocess
|
| 112 |
+
|
| 113 |
+
In the Python subprocess, RPCServer is instantiated with handlerclass
|
| 114 |
+
MyHandler, which inherits register/unregister methods from RPCHandler via
|
| 115 |
+
the mix-in class SocketIO.
|
| 116 |
+
|
| 117 |
+
When the RPCServer 'server' is instantiated, the TCPServer initialization
|
| 118 |
+
creates an instance of run.MyHandler and calls its handle() method.
|
| 119 |
+
handle() instantiates a run.Executive object, passing it a reference to the
|
| 120 |
+
MyHandler object. That reference is saved as attribute rpchandler of the
|
| 121 |
+
Executive instance. The Executive methods have access to the reference and
|
| 122 |
+
can pass it on to entities that they command
|
| 123 |
+
(e.g. debugger_r.Debugger.start_debugger()). The latter, in turn, can
|
| 124 |
+
call MyHandler(SocketIO) register/unregister methods via the reference to
|
| 125 |
+
register and unregister themselves.
|
| 126 |
+
|
| 127 |
+
"""
|
| 128 |
+
global exit_now
|
| 129 |
+
global quitting
|
| 130 |
+
global no_exitfunc
|
| 131 |
+
no_exitfunc = del_exitfunc
|
| 132 |
+
#time.sleep(15) # test subprocess not responding
|
| 133 |
+
try:
|
| 134 |
+
assert(len(sys.argv) > 1)
|
| 135 |
+
port = int(sys.argv[-1])
|
| 136 |
+
except:
|
| 137 |
+
print("IDLE Subprocess: no IP port passed in sys.argv.",
|
| 138 |
+
file=sys.__stderr__)
|
| 139 |
+
return
|
| 140 |
+
|
| 141 |
+
capture_warnings(True)
|
| 142 |
+
sys.argv[:] = [""]
|
| 143 |
+
sockthread = threading.Thread(target=manage_socket,
|
| 144 |
+
name='SockThread',
|
| 145 |
+
args=((LOCALHOST, port),))
|
| 146 |
+
sockthread.daemon = True
|
| 147 |
+
sockthread.start()
|
| 148 |
+
while True:
|
| 149 |
+
try:
|
| 150 |
+
if exit_now:
|
| 151 |
+
try:
|
| 152 |
+
exit()
|
| 153 |
+
except KeyboardInterrupt:
|
| 154 |
+
# exiting but got an extra KBI? Try again!
|
| 155 |
+
continue
|
| 156 |
+
try:
|
| 157 |
+
request = rpc.request_queue.get(block=True, timeout=0.05)
|
| 158 |
+
except queue.Empty:
|
| 159 |
+
request = None
|
| 160 |
+
# Issue 32207: calling handle_tk_events here adds spurious
|
| 161 |
+
# queue.Empty traceback to event handling exceptions.
|
| 162 |
+
if request:
|
| 163 |
+
seq, (method, args, kwargs) = request
|
| 164 |
+
ret = method(*args, **kwargs)
|
| 165 |
+
rpc.response_queue.put((seq, ret))
|
| 166 |
+
else:
|
| 167 |
+
handle_tk_events()
|
| 168 |
+
except KeyboardInterrupt:
|
| 169 |
+
if quitting:
|
| 170 |
+
exit_now = True
|
| 171 |
+
continue
|
| 172 |
+
except SystemExit:
|
| 173 |
+
capture_warnings(False)
|
| 174 |
+
raise
|
| 175 |
+
except:
|
| 176 |
+
type, value, tb = sys.exc_info()
|
| 177 |
+
try:
|
| 178 |
+
print_exception()
|
| 179 |
+
rpc.response_queue.put((seq, None))
|
| 180 |
+
except:
|
| 181 |
+
# Link didn't work, print same exception to __stderr__
|
| 182 |
+
traceback.print_exception(type, value, tb, file=sys.__stderr__)
|
| 183 |
+
exit()
|
| 184 |
+
else:
|
| 185 |
+
continue
|
| 186 |
+
|
| 187 |
+
def manage_socket(address):
|
| 188 |
+
for i in range(3):
|
| 189 |
+
time.sleep(i)
|
| 190 |
+
try:
|
| 191 |
+
server = MyRPCServer(address, MyHandler)
|
| 192 |
+
break
|
| 193 |
+
except OSError as err:
|
| 194 |
+
print("IDLE Subprocess: OSError: " + err.args[1] +
|
| 195 |
+
", retrying....", file=sys.__stderr__)
|
| 196 |
+
socket_error = err
|
| 197 |
+
else:
|
| 198 |
+
print("IDLE Subprocess: Connection to "
|
| 199 |
+
"IDLE GUI failed, exiting.", file=sys.__stderr__)
|
| 200 |
+
show_socket_error(socket_error, address)
|
| 201 |
+
global exit_now
|
| 202 |
+
exit_now = True
|
| 203 |
+
return
|
| 204 |
+
server.handle_request() # A single request only
|
| 205 |
+
|
| 206 |
+
def show_socket_error(err, address):
|
| 207 |
+
"Display socket error from manage_socket."
|
| 208 |
+
import tkinter
|
| 209 |
+
from tkinter.messagebox import showerror
|
| 210 |
+
root = tkinter.Tk()
|
| 211 |
+
fix_scaling(root)
|
| 212 |
+
root.withdraw()
|
| 213 |
+
showerror(
|
| 214 |
+
"Subprocess Connection Error",
|
| 215 |
+
f"IDLE's subprocess can't connect to {address[0]}:{address[1]}.\n"
|
| 216 |
+
f"Fatal OSError #{err.errno}: {err.strerror}.\n"
|
| 217 |
+
"See the 'Startup failure' section of the IDLE doc, online at\n"
|
| 218 |
+
"https://docs.python.org/3/library/idle.html#startup-failure",
|
| 219 |
+
parent=root)
|
| 220 |
+
root.destroy()
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def get_message_lines(typ, exc, tb):
|
| 224 |
+
"Return line composing the exception message."
|
| 225 |
+
if typ in (AttributeError, NameError):
|
| 226 |
+
# 3.10+ hints are not directly accessible from python (#44026).
|
| 227 |
+
err = io.StringIO()
|
| 228 |
+
with contextlib.redirect_stderr(err):
|
| 229 |
+
sys.__excepthook__(typ, exc, tb)
|
| 230 |
+
return [err.getvalue().split("\n")[-2] + "\n"]
|
| 231 |
+
else:
|
| 232 |
+
return traceback.format_exception_only(typ, exc)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def print_exception():
|
| 236 |
+
import linecache
|
| 237 |
+
linecache.checkcache()
|
| 238 |
+
flush_stdout()
|
| 239 |
+
efile = sys.stderr
|
| 240 |
+
typ, val, tb = excinfo = sys.exc_info()
|
| 241 |
+
sys.last_type, sys.last_value, sys.last_traceback = excinfo
|
| 242 |
+
seen = set()
|
| 243 |
+
|
| 244 |
+
def print_exc(typ, exc, tb):
|
| 245 |
+
seen.add(id(exc))
|
| 246 |
+
context = exc.__context__
|
| 247 |
+
cause = exc.__cause__
|
| 248 |
+
if cause is not None and id(cause) not in seen:
|
| 249 |
+
print_exc(type(cause), cause, cause.__traceback__)
|
| 250 |
+
print("\nThe above exception was the direct cause "
|
| 251 |
+
"of the following exception:\n", file=efile)
|
| 252 |
+
elif (context is not None and
|
| 253 |
+
not exc.__suppress_context__ and
|
| 254 |
+
id(context) not in seen):
|
| 255 |
+
print_exc(type(context), context, context.__traceback__)
|
| 256 |
+
print("\nDuring handling of the above exception, "
|
| 257 |
+
"another exception occurred:\n", file=efile)
|
| 258 |
+
if tb:
|
| 259 |
+
tbe = traceback.extract_tb(tb)
|
| 260 |
+
print('Traceback (most recent call last):', file=efile)
|
| 261 |
+
exclude = ("run.py", "rpc.py", "threading.py", "queue.py",
|
| 262 |
+
"debugger_r.py", "bdb.py")
|
| 263 |
+
cleanup_traceback(tbe, exclude)
|
| 264 |
+
traceback.print_list(tbe, file=efile)
|
| 265 |
+
lines = get_message_lines(typ, exc, tb)
|
| 266 |
+
for line in lines:
|
| 267 |
+
print(line, end='', file=efile)
|
| 268 |
+
|
| 269 |
+
print_exc(typ, val, tb)
|
| 270 |
+
|
| 271 |
+
def cleanup_traceback(tb, exclude):
|
| 272 |
+
"Remove excluded traces from beginning/end of tb; get cached lines"
|
| 273 |
+
orig_tb = tb[:]
|
| 274 |
+
while tb:
|
| 275 |
+
for rpcfile in exclude:
|
| 276 |
+
if tb[0][0].count(rpcfile):
|
| 277 |
+
break # found an exclude, break for: and delete tb[0]
|
| 278 |
+
else:
|
| 279 |
+
break # no excludes, have left RPC code, break while:
|
| 280 |
+
del tb[0]
|
| 281 |
+
while tb:
|
| 282 |
+
for rpcfile in exclude:
|
| 283 |
+
if tb[-1][0].count(rpcfile):
|
| 284 |
+
break
|
| 285 |
+
else:
|
| 286 |
+
break
|
| 287 |
+
del tb[-1]
|
| 288 |
+
if len(tb) == 0:
|
| 289 |
+
# exception was in IDLE internals, don't prune!
|
| 290 |
+
tb[:] = orig_tb[:]
|
| 291 |
+
print("** IDLE Internal Exception: ", file=sys.stderr)
|
| 292 |
+
rpchandler = rpc.objecttable['exec'].rpchandler
|
| 293 |
+
for i in range(len(tb)):
|
| 294 |
+
fn, ln, nm, line = tb[i]
|
| 295 |
+
if nm == '?':
|
| 296 |
+
nm = "-toplevel-"
|
| 297 |
+
if not line and fn.startswith("<pyshell#"):
|
| 298 |
+
line = rpchandler.remotecall('linecache', 'getline',
|
| 299 |
+
(fn, ln), {})
|
| 300 |
+
tb[i] = fn, ln, nm, line
|
| 301 |
+
|
| 302 |
+
def flush_stdout():
|
| 303 |
+
"""XXX How to do this now?"""
|
| 304 |
+
|
| 305 |
+
def exit():
|
| 306 |
+
"""Exit subprocess, possibly after first clearing exit functions.
|
| 307 |
+
|
| 308 |
+
If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any
|
| 309 |
+
functions registered with atexit will be removed before exiting.
|
| 310 |
+
(VPython support)
|
| 311 |
+
|
| 312 |
+
"""
|
| 313 |
+
if no_exitfunc:
|
| 314 |
+
import atexit
|
| 315 |
+
atexit._clear()
|
| 316 |
+
capture_warnings(False)
|
| 317 |
+
sys.exit(0)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def fix_scaling(root):
|
| 321 |
+
"""Scale fonts on HiDPI displays."""
|
| 322 |
+
import tkinter.font
|
| 323 |
+
scaling = float(root.tk.call('tk', 'scaling'))
|
| 324 |
+
if scaling > 1.4:
|
| 325 |
+
for name in tkinter.font.names(root):
|
| 326 |
+
font = tkinter.font.Font(root=root, name=name, exists=True)
|
| 327 |
+
size = int(font['size'])
|
| 328 |
+
if size < 0:
|
| 329 |
+
font['size'] = round(-0.75*size)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def fixdoc(fun, text):
|
| 333 |
+
tem = (fun.__doc__ + '\n\n') if fun.__doc__ is not None else ''
|
| 334 |
+
fun.__doc__ = tem + textwrap.fill(textwrap.dedent(text))
|
| 335 |
+
|
| 336 |
+
RECURSIONLIMIT_DELTA = 30
|
| 337 |
+
|
| 338 |
+
def install_recursionlimit_wrappers():
|
| 339 |
+
"""Install wrappers to always add 30 to the recursion limit."""
|
| 340 |
+
# see: bpo-26806
|
| 341 |
+
|
| 342 |
+
@functools.wraps(sys.setrecursionlimit)
|
| 343 |
+
def setrecursionlimit(*args, **kwargs):
|
| 344 |
+
# mimic the original sys.setrecursionlimit()'s input handling
|
| 345 |
+
if kwargs:
|
| 346 |
+
raise TypeError(
|
| 347 |
+
"setrecursionlimit() takes no keyword arguments")
|
| 348 |
+
try:
|
| 349 |
+
limit, = args
|
| 350 |
+
except ValueError:
|
| 351 |
+
raise TypeError(f"setrecursionlimit() takes exactly one "
|
| 352 |
+
f"argument ({len(args)} given)")
|
| 353 |
+
if not limit > 0:
|
| 354 |
+
raise ValueError(
|
| 355 |
+
"recursion limit must be greater or equal than 1")
|
| 356 |
+
|
| 357 |
+
return setrecursionlimit.__wrapped__(limit + RECURSIONLIMIT_DELTA)
|
| 358 |
+
|
| 359 |
+
fixdoc(setrecursionlimit, f"""\
|
| 360 |
+
This IDLE wrapper adds {RECURSIONLIMIT_DELTA} to prevent possible
|
| 361 |
+
uninterruptible loops.""")
|
| 362 |
+
|
| 363 |
+
@functools.wraps(sys.getrecursionlimit)
|
| 364 |
+
def getrecursionlimit():
|
| 365 |
+
return getrecursionlimit.__wrapped__() - RECURSIONLIMIT_DELTA
|
| 366 |
+
|
| 367 |
+
fixdoc(getrecursionlimit, f"""\
|
| 368 |
+
This IDLE wrapper subtracts {RECURSIONLIMIT_DELTA} to compensate
|
| 369 |
+
for the {RECURSIONLIMIT_DELTA} IDLE adds when setting the limit.""")
|
| 370 |
+
|
| 371 |
+
# add the delta to the default recursion limit, to compensate
|
| 372 |
+
sys.setrecursionlimit(sys.getrecursionlimit() + RECURSIONLIMIT_DELTA)
|
| 373 |
+
|
| 374 |
+
sys.setrecursionlimit = setrecursionlimit
|
| 375 |
+
sys.getrecursionlimit = getrecursionlimit
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def uninstall_recursionlimit_wrappers():
|
| 379 |
+
"""Uninstall the recursion limit wrappers from the sys module.
|
| 380 |
+
|
| 381 |
+
IDLE only uses this for tests. Users can import run and call
|
| 382 |
+
this to remove the wrapping.
|
| 383 |
+
"""
|
| 384 |
+
if (
|
| 385 |
+
getattr(sys.setrecursionlimit, '__wrapped__', None) and
|
| 386 |
+
getattr(sys.getrecursionlimit, '__wrapped__', None)
|
| 387 |
+
):
|
| 388 |
+
sys.setrecursionlimit = sys.setrecursionlimit.__wrapped__
|
| 389 |
+
sys.getrecursionlimit = sys.getrecursionlimit.__wrapped__
|
| 390 |
+
sys.setrecursionlimit(sys.getrecursionlimit() - RECURSIONLIMIT_DELTA)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class MyRPCServer(rpc.RPCServer):
|
| 394 |
+
|
| 395 |
+
def handle_error(self, request, client_address):
|
| 396 |
+
"""Override RPCServer method for IDLE
|
| 397 |
+
|
| 398 |
+
Interrupt the MainThread and exit server if link is dropped.
|
| 399 |
+
|
| 400 |
+
"""
|
| 401 |
+
global quitting
|
| 402 |
+
try:
|
| 403 |
+
raise
|
| 404 |
+
except SystemExit:
|
| 405 |
+
raise
|
| 406 |
+
except EOFError:
|
| 407 |
+
global exit_now
|
| 408 |
+
exit_now = True
|
| 409 |
+
thread.interrupt_main()
|
| 410 |
+
except:
|
| 411 |
+
erf = sys.__stderr__
|
| 412 |
+
print(textwrap.dedent(f"""
|
| 413 |
+
{'-'*40}
|
| 414 |
+
Unhandled exception in user code execution server!'
|
| 415 |
+
Thread: {threading.current_thread().name}
|
| 416 |
+
IDLE Client Address: {client_address}
|
| 417 |
+
Request: {request!r}
|
| 418 |
+
"""), file=erf)
|
| 419 |
+
traceback.print_exc(limit=-20, file=erf)
|
| 420 |
+
print(textwrap.dedent(f"""
|
| 421 |
+
*** Unrecoverable, server exiting!
|
| 422 |
+
|
| 423 |
+
Users should never see this message; it is likely transient.
|
| 424 |
+
If this recurs, report this with a copy of the message
|
| 425 |
+
and an explanation of how to make it repeat.
|
| 426 |
+
{'-'*40}"""), file=erf)
|
| 427 |
+
quitting = True
|
| 428 |
+
thread.interrupt_main()
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
# Pseudofiles for shell-remote communication (also used in pyshell)
|
| 432 |
+
|
| 433 |
+
class StdioFile(io.TextIOBase):
|
| 434 |
+
|
| 435 |
+
def __init__(self, shell, tags, encoding='utf-8', errors='strict'):
|
| 436 |
+
self.shell = shell
|
| 437 |
+
self.tags = tags
|
| 438 |
+
self._encoding = encoding
|
| 439 |
+
self._errors = errors
|
| 440 |
+
|
| 441 |
+
@property
|
| 442 |
+
def encoding(self):
|
| 443 |
+
return self._encoding
|
| 444 |
+
|
| 445 |
+
@property
|
| 446 |
+
def errors(self):
|
| 447 |
+
return self._errors
|
| 448 |
+
|
| 449 |
+
@property
|
| 450 |
+
def name(self):
|
| 451 |
+
return '<%s>' % self.tags
|
| 452 |
+
|
| 453 |
+
def isatty(self):
|
| 454 |
+
return True
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
class StdOutputFile(StdioFile):
|
| 458 |
+
|
| 459 |
+
def writable(self):
|
| 460 |
+
return True
|
| 461 |
+
|
| 462 |
+
def write(self, s):
|
| 463 |
+
if self.closed:
|
| 464 |
+
raise ValueError("write to closed file")
|
| 465 |
+
s = str.encode(s, self.encoding, self.errors).decode(self.encoding, self.errors)
|
| 466 |
+
return self.shell.write(s, self.tags)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
class StdInputFile(StdioFile):
|
| 470 |
+
_line_buffer = ''
|
| 471 |
+
|
| 472 |
+
def readable(self):
|
| 473 |
+
return True
|
| 474 |
+
|
| 475 |
+
def read(self, size=-1):
|
| 476 |
+
if self.closed:
|
| 477 |
+
raise ValueError("read from closed file")
|
| 478 |
+
if size is None:
|
| 479 |
+
size = -1
|
| 480 |
+
elif not isinstance(size, int):
|
| 481 |
+
raise TypeError('must be int, not ' + type(size).__name__)
|
| 482 |
+
result = self._line_buffer
|
| 483 |
+
self._line_buffer = ''
|
| 484 |
+
if size < 0:
|
| 485 |
+
while line := self.shell.readline():
|
| 486 |
+
result += line
|
| 487 |
+
else:
|
| 488 |
+
while len(result) < size:
|
| 489 |
+
line = self.shell.readline()
|
| 490 |
+
if not line: break
|
| 491 |
+
result += line
|
| 492 |
+
self._line_buffer = result[size:]
|
| 493 |
+
result = result[:size]
|
| 494 |
+
return result
|
| 495 |
+
|
| 496 |
+
def readline(self, size=-1):
|
| 497 |
+
if self.closed:
|
| 498 |
+
raise ValueError("read from closed file")
|
| 499 |
+
if size is None:
|
| 500 |
+
size = -1
|
| 501 |
+
elif not isinstance(size, int):
|
| 502 |
+
raise TypeError('must be int, not ' + type(size).__name__)
|
| 503 |
+
line = self._line_buffer or self.shell.readline()
|
| 504 |
+
if size < 0:
|
| 505 |
+
size = len(line)
|
| 506 |
+
eol = line.find('\n', 0, size)
|
| 507 |
+
if eol >= 0:
|
| 508 |
+
size = eol + 1
|
| 509 |
+
self._line_buffer = line[size:]
|
| 510 |
+
return line[:size]
|
| 511 |
+
|
| 512 |
+
def close(self):
|
| 513 |
+
self.shell.close()
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
class MyHandler(rpc.RPCHandler):
|
| 517 |
+
|
| 518 |
+
def handle(self):
|
| 519 |
+
"""Override base method"""
|
| 520 |
+
executive = Executive(self)
|
| 521 |
+
self.register("exec", executive)
|
| 522 |
+
self.console = self.get_remote_proxy("console")
|
| 523 |
+
sys.stdin = StdInputFile(self.console, "stdin",
|
| 524 |
+
iomenu.encoding, iomenu.errors)
|
| 525 |
+
sys.stdout = StdOutputFile(self.console, "stdout",
|
| 526 |
+
iomenu.encoding, iomenu.errors)
|
| 527 |
+
sys.stderr = StdOutputFile(self.console, "stderr",
|
| 528 |
+
iomenu.encoding, "backslashreplace")
|
| 529 |
+
|
| 530 |
+
sys.displayhook = rpc.displayhook
|
| 531 |
+
# page help() text to shell.
|
| 532 |
+
import pydoc # import must be done here to capture i/o binding
|
| 533 |
+
pydoc.pager = pydoc.plainpager
|
| 534 |
+
|
| 535 |
+
# Keep a reference to stdin so that it won't try to exit IDLE if
|
| 536 |
+
# sys.stdin gets changed from within IDLE's shell. See issue17838.
|
| 537 |
+
self._keep_stdin = sys.stdin
|
| 538 |
+
|
| 539 |
+
install_recursionlimit_wrappers()
|
| 540 |
+
|
| 541 |
+
self.interp = self.get_remote_proxy("interp")
|
| 542 |
+
rpc.RPCHandler.getresponse(self, myseq=None, wait=0.05)
|
| 543 |
+
|
| 544 |
+
def exithook(self):
|
| 545 |
+
"override SocketIO method - wait for MainThread to shut us down"
|
| 546 |
+
time.sleep(10)
|
| 547 |
+
|
| 548 |
+
def EOFhook(self):
|
| 549 |
+
"Override SocketIO method - terminate wait on callback and exit thread"
|
| 550 |
+
global quitting
|
| 551 |
+
quitting = True
|
| 552 |
+
thread.interrupt_main()
|
| 553 |
+
|
| 554 |
+
def decode_interrupthook(self):
|
| 555 |
+
"interrupt awakened thread"
|
| 556 |
+
global quitting
|
| 557 |
+
quitting = True
|
| 558 |
+
thread.interrupt_main()
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
class Executive:
|
| 562 |
+
|
| 563 |
+
def __init__(self, rpchandler):
|
| 564 |
+
self.rpchandler = rpchandler
|
| 565 |
+
if idlelib.testing is False:
|
| 566 |
+
self.locals = __main__.__dict__
|
| 567 |
+
self.calltip = calltip.Calltip()
|
| 568 |
+
self.autocomplete = autocomplete.AutoComplete()
|
| 569 |
+
else:
|
| 570 |
+
self.locals = {}
|
| 571 |
+
|
| 572 |
+
def runcode(self, code):
|
| 573 |
+
global interruptable
|
| 574 |
+
try:
|
| 575 |
+
self.user_exc_info = None
|
| 576 |
+
interruptable = True
|
| 577 |
+
try:
|
| 578 |
+
exec(code, self.locals)
|
| 579 |
+
finally:
|
| 580 |
+
interruptable = False
|
| 581 |
+
except SystemExit as e:
|
| 582 |
+
if e.args: # SystemExit called with an argument.
|
| 583 |
+
ob = e.args[0]
|
| 584 |
+
if not isinstance(ob, (type(None), int)):
|
| 585 |
+
print('SystemExit: ' + str(ob), file=sys.stderr)
|
| 586 |
+
# Return to the interactive prompt.
|
| 587 |
+
except:
|
| 588 |
+
self.user_exc_info = sys.exc_info() # For testing, hook, viewer.
|
| 589 |
+
if quitting:
|
| 590 |
+
exit()
|
| 591 |
+
if sys.excepthook is sys.__excepthook__:
|
| 592 |
+
print_exception()
|
| 593 |
+
else:
|
| 594 |
+
try:
|
| 595 |
+
sys.excepthook(*self.user_exc_info)
|
| 596 |
+
except:
|
| 597 |
+
self.user_exc_info = sys.exc_info() # For testing.
|
| 598 |
+
print_exception()
|
| 599 |
+
jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>")
|
| 600 |
+
if jit:
|
| 601 |
+
self.rpchandler.interp.open_remote_stack_viewer()
|
| 602 |
+
else:
|
| 603 |
+
flush_stdout()
|
| 604 |
+
|
| 605 |
+
def interrupt_the_server(self):
|
| 606 |
+
if interruptable:
|
| 607 |
+
thread.interrupt_main()
|
| 608 |
+
|
| 609 |
+
def start_the_debugger(self, gui_adap_oid):
|
| 610 |
+
return debugger_r.start_debugger(self.rpchandler, gui_adap_oid)
|
| 611 |
+
|
| 612 |
+
def stop_the_debugger(self, idb_adap_oid):
|
| 613 |
+
"Unregister the Idb Adapter. Link objects and Idb then subject to GC"
|
| 614 |
+
self.rpchandler.unregister(idb_adap_oid)
|
| 615 |
+
|
| 616 |
+
def get_the_calltip(self, name):
|
| 617 |
+
return self.calltip.fetch_tip(name)
|
| 618 |
+
|
| 619 |
+
def get_the_completion_list(self, what, mode):
|
| 620 |
+
return self.autocomplete.fetch_completions(what, mode)
|
| 621 |
+
|
| 622 |
+
def stackviewer(self, flist_oid=None):
|
| 623 |
+
if self.user_exc_info:
|
| 624 |
+
typ, val, tb = self.user_exc_info
|
| 625 |
+
else:
|
| 626 |
+
return None
|
| 627 |
+
flist = None
|
| 628 |
+
if flist_oid is not None:
|
| 629 |
+
flist = self.rpchandler.get_remote_proxy(flist_oid)
|
| 630 |
+
while tb and tb.tb_frame.f_globals["__name__"] in ["rpc", "run"]:
|
| 631 |
+
tb = tb.tb_next
|
| 632 |
+
sys.last_type = typ
|
| 633 |
+
sys.last_value = val
|
| 634 |
+
item = stackviewer.StackTreeItem(flist, tb)
|
| 635 |
+
return debugobj_r.remote_object_tree_item(item)
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
if __name__ == '__main__':
|
| 639 |
+
from unittest import main
|
| 640 |
+
main('idlelib.idle_test.test_run', verbosity=2)
|
| 641 |
+
|
| 642 |
+
capture_warnings(False) # Make sure turned off; see bpo-18081.
|