diff --git a/.gitignore b/.gitignore index 583abf7..703b7bc 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,7 @@ _build docs/man/*.gz docs/source/api/generated docs/gh-pages -IPython/frontend/html/notebook/static/mathjax +IPython/html/notebook/static/mathjax *.py[co] __pycache__ build diff --git a/.gitmodules b/.gitmodules index b32380c..1eaa243 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "components"] - path = IPython/frontend/html/notebook/static/components + path = IPython/html/static/components url = https://github.com/ipython/ipython-components.git diff --git a/IPython/__init__.py b/IPython/__init__.py index d553587..c804cd4 100644 --- a/IPython/__init__.py +++ b/IPython/__init__.py @@ -44,7 +44,7 @@ from .config.loader import Config from .core.getipython import get_ipython from .core import release from .core.application import Application -from .frontend.terminal.embed import embed +from .terminal.embed import embed from .core.error import TryNext from .core.interactiveshell import InteractiveShell diff --git a/IPython/__main__.py b/IPython/__main__.py index 66af32a..1e2ee07 100644 --- a/IPython/__main__.py +++ b/IPython/__main__.py @@ -9,6 +9,6 @@ # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- -from IPython.frontend.terminal.ipapp import launch_new_instance +from IPython.terminal.ipapp import launch_new_instance launch_new_instance() diff --git a/IPython/frontend/consoleapp.py b/IPython/consoleapp.py similarity index 99% rename from IPython/frontend/consoleapp.py rename to IPython/consoleapp.py index 67148f7..8813d83 100644 --- a/IPython/frontend/consoleapp.py +++ b/IPython/consoleapp.py @@ -2,7 +2,7 @@ This is not a complete console app, as subprocess will not be able to receive input, there is no real readline support, among other limitations. This is a -refactoring of what used to be the IPython/frontend/qt/console/qtconsoleapp.py +refactoring of what used to be the IPython/qt/console/qtconsoleapp.py Authors: diff --git a/IPython/core/profileapp.py b/IPython/core/profileapp.py index 39479cd..9c6a529 100644 --- a/IPython/core/profileapp.py +++ b/IPython/core/profileapp.py @@ -238,10 +238,10 @@ class ProfileCreate(BaseIPythonApplication): def init_config_files(self): super(ProfileCreate, self).init_config_files() # use local imports, since these classes may import from here - from IPython.frontend.terminal.ipapp import TerminalIPythonApp + from IPython.terminal.ipapp import TerminalIPythonApp apps = [TerminalIPythonApp] try: - from IPython.frontend.qt.console.qtconsoleapp import IPythonQtConsoleApp + from IPython.qt.console.qtconsoleapp import IPythonQtConsoleApp except Exception: # this should be ImportError, but under weird circumstances # this might be an AttributeError, or possibly others @@ -250,7 +250,7 @@ class ProfileCreate(BaseIPythonApplication): else: apps.append(IPythonQtConsoleApp) try: - from IPython.frontend.html.notebook.notebookapp import NotebookApp + from IPython.html.notebookapp import NotebookApp except ImportError: pass except Exception: diff --git a/IPython/core/tests/test_display.py b/IPython/core/tests/test_display.py index c34674d..785bdd8 100644 --- a/IPython/core/tests/test_display.py +++ b/IPython/core/tests/test_display.py @@ -29,7 +29,7 @@ def test_image_filename_defaults(): embed=True) nt.assert_raises(ValueError, display.Image) nt.assert_raises(ValueError, display.Image, data='this is not an image', format='badformat', embed=True) - imgfile = os.path.join(tpath, 'frontend/html/notebook/static/base/images/ipynblogo.png') + imgfile = os.path.join(tpath, 'html/static/base/images/ipynblogo.png') img = display.Image(filename=imgfile) nt.assert_equal('png', img.format) nt.assert_is_not_none(img._repr_png_()) diff --git a/IPython/deathrow/Gnuplot2.py b/IPython/deathrow/Gnuplot2.py deleted file mode 100644 index b75fe20..0000000 --- a/IPython/deathrow/Gnuplot2.py +++ /dev/null @@ -1,665 +0,0 @@ -# -*- coding: utf-8 -*- -"""Improved replacement for the Gnuplot.Gnuplot class. - -This module imports Gnuplot and replaces some of its functionality with -improved versions. They add better handling of arrays for plotting and more -convenient PostScript generation, plus some fixes for hardcopy(). - -It also adds a convenient plot2 method for plotting dictionaries and -lists/tuples of arrays. - -This module is meant to be used as a drop-in replacement to the original -Gnuplot, so it should be safe to do: - -import IPython.Gnuplot2 as Gnuplot -""" - -import cStringIO -import os -import string -import sys -import tempfile -import time -import types - -import Gnuplot as Gnuplot_ori -import Numeric - -from IPython.utils.genutils import popkey,xsys - -# needed by hardcopy(): -gp = Gnuplot_ori.gp - -# Patch for Gnuplot.py 1.6 compatibility. -# Thanks to Hayden Callow <h.callow@elec.canterbury.ac.nz> -try: - OptionException = Gnuplot_ori.PlotItems.OptionException -except AttributeError: - OptionException = Gnuplot_ori.Errors.OptionError - -# exhibit a similar interface to Gnuplot so it can be somewhat drop-in -Data = Gnuplot_ori.Data -Func = Gnuplot_ori.Func -GridData = Gnuplot_ori.GridData -PlotItem = Gnuplot_ori.PlotItem -PlotItems = Gnuplot_ori.PlotItems - -# Modify some of Gnuplot's functions with improved versions (or bugfixed, in -# hardcopy's case). In order to preserve the docstrings at runtime, I've -# copied them from the original code. - -# After some significant changes in v 1.7 of Gnuplot.py, we need to do a bit -# of version checking. - -if Gnuplot_ori.__version__ <= '1.6': - _BaseFileItem = PlotItems.File - _BaseTempFileItem = PlotItems.TempFile - - # Fix the File class to add the 'index' option for Gnuplot versions < 1.7 - class File(_BaseFileItem): - - _option_list = _BaseFileItem._option_list.copy() - _option_list.update({ - 'index' : lambda self, index: self.set_option_index(index), - }) - - # A new initializer is needed b/c we want to add a modified - # _option_sequence list which includes 'index' in the right place. - def __init__(self,*args,**kw): - self._option_sequence = ['binary', 'index', 'using', 'smooth', 'axes', - 'title', 'with'] - - _BaseFileItem.__init__(self,*args,**kw) - - # Let's fix the constructor docstring - __newdoc = \ - """Additional Keyword arguments added by IPython: - - 'index=<int>' -- similar to the `index` keyword in Gnuplot. - This allows only some of the datasets in a file to be - plotted. Datasets within a file are assumed to be separated - by _pairs_ of blank lines, and the first one is numbered as - 0 (similar to C/Python usage).""" - __init__.__doc__ = PlotItems.File.__init__.__doc__ + __newdoc - - def set_option_index(self, index): - if index is None: - self.clear_option('index') - elif type(index) in [type(''), type(1)]: - self._options['index'] = (index, 'index %s' % index) - elif type(index) is type(()): - self._options['index'] = (index,'index %s' % - string.join(map(repr, index), ':')) - else: - raise OptionException('index=%s' % (index,)) - - # We need a FileClass with a different name from 'File', which is a - # factory function in 1.7, so that our String class can subclass FileClass - # in any version. - _FileClass = File - -elif Gnuplot_ori.__version__ =='1.7': - _FileClass = _BaseFileItem = PlotItems._FileItem - _BaseTempFileItem = PlotItems._TempFileItem - File = PlotItems.File - -else: # changes in the newer version (svn as of March'06) - _FileClass = _BaseFileItem = PlotItems._FileItem - _BaseTempFileItem = PlotItems._NewFileItem - File = PlotItems.File - - -# Now, we can add our generic code which is version independent - -# First some useful utilities -def eps_fix_bbox(fname): - """Fix the bounding box of an eps file by running ps2eps on it. - - If its name ends in .eps, the original file is removed. - - This is particularly useful for plots made by Gnuplot with square aspect - ratio: there is a bug in Gnuplot which makes it generate a bounding box - which is far wider than the actual plot. - - This function assumes that ps2eps is installed in your system.""" - - # note: ps2ps and eps2eps do NOT work, ONLY ps2eps works correctly. The - # others make output with bitmapped fonts, which looks horrible. - print 'Fixing eps file: <%s>' % fname - xsys('ps2eps -f -q -l %s' % fname) - if fname.endswith('.eps'): - os.rename(fname+'.eps',fname) - -def is_list1d(x,containers = [types.ListType,types.TupleType]): - """Returns true if x appears to be a 1d list/tuple/array. - - The heuristics are: identify Numeric arrays, or lists/tuples whose first - element is not itself a list/tuple. This way zipped lists should work like - the original Gnuplot. There's no inexpensive way to know if a list doesn't - have a composite object after its first element, so that kind of input - will produce an error. But it should work well in most cases. - """ - x_type = type(x) - - return x_type == Numeric.ArrayType and len(x.shape)==1 or \ - (x_type in containers and - type(x[0]) not in containers + [Numeric.ArrayType]) - -def zip_items(items,titles=None): - """zip together neighboring 1-d arrays, and zip standalone ones - with their index. Leave other plot items alone.""" - - class StandaloneItem(Exception): pass - - def get_titles(titles): - """Return the next title and the input titles array. - - The input array may be changed to None when no titles are left to - prevent extra unnecessary calls to this function.""" - - try: - title = titles[tit_ct[0]] # tit_ct[0] is in zip_items'scope - except IndexError: - titles = None # so we don't enter again - title = None - else: - tit_ct[0] += 1 - return title,titles - - new_items = [] - - if titles: - # Initialize counter. It was put in a list as a hack to allow the - # nested get_titles to modify it without raising a NameError. - tit_ct = [0] - - n = 0 # this loop needs to be done by hand - while n < len(items): - item = items[n] - try: - if is_list1d(item): - if n==len(items)-1: # last in list - raise StandaloneItem - else: # check the next item and zip together if needed - next_item = items[n+1] - if next_item is None: - n += 1 - raise StandaloneItem - elif is_list1d(next_item): - # this would be best done with an iterator - if titles: - title,titles = get_titles(titles) - else: - title = None - new_items.append(Data(zip(item,next_item), - title=title)) - n += 1 # avoid double-inclusion of next item - else: # can't zip with next, zip with own index list - raise StandaloneItem - else: # not 1-d array - new_items.append(item) - except StandaloneItem: - if titles: - title,titles = get_titles(titles) - else: - title = None - new_items.append(Data(zip(range(len(item)),item),title=title)) - except AttributeError: - new_items.append(item) - n+=1 - - return new_items - -# And some classes with enhanced functionality. -class String(_FileClass): - """Make a PlotItem from data in a string with the same format as a File. - - This allows writing data directly inside python scripts using the exact - same format and manipulation options which would be used for external - files.""" - - def __init__(self, data_str, **keyw): - """Construct a String object. - - <data_str> is a string formatted exactly like a valid Gnuplot data - file would be. All options from the File constructor are valid here. - - Warning: when used for interactive plotting in scripts which exit - immediately, you may get an error because the temporary file used to - hold the string data was deleted before Gnuplot had a chance to see - it. You can work around this problem by putting a raw_input() call at - the end of the script. - - This problem does not appear when generating PostScript output, only - with Gnuplot windows.""" - - self.tmpfile = _BaseTempFileItem() - tmpfile = file(self.tmpfile.filename,'w') - tmpfile.write(data_str) - _BaseFileItem.__init__(self,self.tmpfile,**keyw) - - -class Gnuplot(Gnuplot_ori.Gnuplot): - """Improved Gnuplot class. - - Enhancements: better plot,replot and hardcopy methods. New methods for - quick range setting. - """ - - def xrange(self,min='*',max='*'): - """Set xrange. If min/max is omitted, it is set to '*' (auto). - - Note that this is different from the regular Gnuplot behavior, where - an unspecified limit means no change. Here any unspecified limit is - set to autoscaling, allowing these functions to be used for full - autoscaling when called with no arguments. - - To preserve one limit's current value while changing the other, an - explicit '' argument must be given as the limit to be kept. - - Similar functions exist for [y{2}z{2}rtuv]range.""" - - self('set xrange [%s:%s]' % (min,max)) - - def yrange(self,min='*',max='*'): - self('set yrange [%s:%s]' % (min,max)) - - def zrange(self,min='*',max='*'): - self('set zrange [%s:%s]' % (min,max)) - - def x2range(self,min='*',max='*'): - self('set xrange [%s:%s]' % (min,max)) - - def y2range(self,min='*',max='*'): - self('set yrange [%s:%s]' % (min,max)) - - def z2range(self,min='*',max='*'): - self('set zrange [%s:%s]' % (min,max)) - - def rrange(self,min='*',max='*'): - self('set rrange [%s:%s]' % (min,max)) - - def trange(self,min='*',max='*'): - self('set trange [%s:%s]' % (min,max)) - - def urange(self,min='*',max='*'): - self('set urange [%s:%s]' % (min,max)) - - def vrange(self,min='*',max='*'): - self('set vrange [%s:%s]' % (min,max)) - - def set_ps(self,option): - """Set an option for the PostScript terminal and reset default term.""" - - self('set terminal postscript %s ' % option) - self('set terminal %s' % gp.GnuplotOpts.default_term) - - def __plot_ps(self, plot_method,*items, **keyw): - """Wrapper for plot/splot/replot, with processing of hardcopy options. - - For internal use only.""" - - # Filter out PostScript options which will crash the normal plot/replot - psargs = {'filename':None, - 'mode':None, - 'eps':None, - 'enhanced':None, - 'color':None, - 'solid':None, - 'duplexing':None, - 'fontname':None, - 'fontsize':None, - 'debug':0 } - - for k in psargs.keys(): - if keyw.has_key(k): - psargs[k] = keyw[k] - del keyw[k] - - # Filter out other options the original plot doesn't know - hardcopy = popkey(keyw,'hardcopy',psargs['filename'] is not None) - titles = popkey(keyw,'titles',0) - - # the filename keyword should control hardcopy generation, this is an - # override switch only which needs to be explicitly set to zero - if hardcopy: - if psargs['filename'] is None: - raise ValueError, \ - 'If you request hardcopy, you must give a filename.' - - # set null output so nothing goes to screen. hardcopy() restores output - self('set term dumb') - # I don't know how to prevent screen output in Windows - if os.name == 'posix': - self('set output "/dev/null"') - - new_items = zip_items(items,titles) - # plot_method is either plot or replot from the original Gnuplot class: - plot_method(self,*new_items,**keyw) - - # Do hardcopy if requested - if hardcopy: - if psargs['filename'].endswith('.eps'): - psargs['eps'] = 1 - self.hardcopy(**psargs) - - def plot(self, *items, **keyw): - """Draw a new plot. - - Clear the current plot and create a new 2-d plot containing - the specified items. Each arguments should be of the - following types: - - 'PlotItem' (e.g., 'Data', 'File', 'Func') -- This is the most - flexible way to call plot because the PlotItems can - contain suboptions. Moreover, PlotItems can be saved to - variables so that their lifetime is longer than one plot - command; thus they can be replotted with minimal overhead. - - 'string' (e.g., 'sin(x)') -- The string is interpreted as - 'Func(string)' (a function that is computed by gnuplot). - - Anything else -- The object, which should be convertible to an - array, is passed to the 'Data' constructor, and thus - plotted as data. If the conversion fails, an exception is - raised. - - - This is a modified version of plot(). Compared to the original in - Gnuplot.py, this version has several enhancements, listed below. - - - Modifications to the input arguments - ------------------------------------ - - (1-d array means Numeric array, list or tuple): - - (i) Any 1-d array which is NOT followed by another 1-d array, is - automatically zipped with range(len(array_1d)). Typing g.plot(y) will - plot y against its indices. - - (ii) If two 1-d arrays are contiguous in the argument list, they are - automatically zipped together. So g.plot(x,y) plots y vs. x, and - g.plot(x1,y1,x2,y2) plots y1 vs. x1 and y2 vs. x2. - - (iii) Any 1-d array which is followed by None is automatically zipped - with range(len(array_1d)). In this form, typing g.plot(y1,None,y2) - will plot both y1 and y2 against their respective indices (and NOT - versus one another). The None prevents zipping y1 and y2 together, and - since y2 is unpaired it is automatically zipped to its indices by (i) - - (iv) Any other arguments which don't match these cases are left alone and - passed to the code below. - - For lists or tuples, the heuristics used to determine whether they are - in fact 1-d is fairly simplistic: their first element is checked, and - if it is not a list or tuple itself, it is assumed that the whole - object is one-dimensional. - - An additional optional keyword 'titles' has been added: it must be a - list of strings to be used as labels for the individual plots which - are NOT PlotItem objects (since those objects carry their own labels - within). - - - PostScript generation - --------------------- - - This version of plot() also handles automatically the production of - PostScript output. The main options are (given as keyword arguments): - - - filename: a string, typically ending in .eps. If given, the plot is - sent to this file in PostScript format. - - - hardcopy: this can be set to 0 to override 'filename'. It does not - need to be given to produce PostScript, its purpose is to allow - switching PostScript output off globally in scripts without having to - manually change 'filename' values in multiple calls. - - All other keywords accepted by Gnuplot.hardcopy() are transparently - passed, and safely ignored if output is sent to the screen instead of - PostScript. - - For example: - - In [1]: x=frange(0,2*pi,npts=100) - - Generate a plot in file 'sin.eps': - - In [2]: plot(x,sin(x),filename = 'sin.eps') - - Plot to screen instead, without having to change the filename: - - In [3]: plot(x,sin(x),filename = 'sin.eps',hardcopy=0) - - Pass the 'color=0' option to hardcopy for monochrome output: - - In [4]: plot(x,sin(x),filename = 'sin.eps',color=0) - - PostScript generation through plot() is useful mainly for scripting - uses where you are not interested in interactive plotting. For - interactive use, the hardcopy() function is typically more convenient: - - In [5]: plot(x,sin(x)) - - In [6]: hardcopy('sin.eps') """ - - self.__plot_ps(Gnuplot_ori.Gnuplot.plot,*items,**keyw) - - def plot2(self,arg,**kw): - """Plot the entries of a dictionary or a list/tuple of arrays. - - This simple utility calls plot() with a list of Gnuplot.Data objects - constructed either from the values of the input dictionary, or the entries - in it if it is a tuple or list. Each item gets labeled with the key/index - in the Gnuplot legend. - - Each item is plotted by zipping it with a list of its indices. - - Any keywords are passed directly to plot().""" - - if hasattr(arg,'keys'): - keys = arg.keys() - keys.sort() - else: - keys = range(len(arg)) - - pitems = [Data(zip(range(len(arg[k])),arg[k]),title=`k`) for k in keys] - self.plot(*pitems,**kw) - - def splot(self, *items, **keyw): - """Draw a new three-dimensional plot. - - Clear the current plot and create a new 3-d plot containing - the specified items. Arguments can be of the following types: - - 'PlotItem' (e.g., 'Data', 'File', 'Func', 'GridData' ) -- This - is the most flexible way to call plot because the - PlotItems can contain suboptions. Moreover, PlotItems can - be saved to variables so that their lifetime is longer - than one plot command--thus they can be replotted with - minimal overhead. - - 'string' (e.g., 'sin(x*y)') -- The string is interpreted as a - 'Func()' (a function that is computed by gnuplot). - - Anything else -- The object is converted to a Data() item, and - thus plotted as data. Note that each data point should - normally have at least three values associated with it - (i.e., x, y, and z). If the conversion fails, an - exception is raised. - - This is a modified version of splot(). Compared to the original in - Gnuplot.py, this version has several enhancements, listed in the - plot() documentation. - """ - - self.__plot_ps(Gnuplot_ori.Gnuplot.splot,*items,**keyw) - - def replot(self, *items, **keyw): - """Replot the data, possibly adding new 'PlotItem's. - - Replot the existing graph, using the items in the current - itemlist. If arguments are specified, they are interpreted as - additional items to be plotted alongside the existing items on - the same graph. See 'plot' for details. - - If you want to replot to a postscript file, you MUST give the - 'filename' keyword argument in each call to replot. The Gnuplot python - interface has no way of knowing that your previous call to - Gnuplot.plot() was meant for PostScript output.""" - - self.__plot_ps(Gnuplot_ori.Gnuplot.replot,*items,**keyw) - - # The original hardcopy has a bug. See fix at the end. The rest of the code - # was lifted verbatim from the original, so that people using IPython get the - # benefits without having to manually patch Gnuplot.py - def hardcopy(self, filename=None, - mode=None, - eps=None, - enhanced=None, - color=None, - solid=None, - duplexing=None, - fontname=None, - fontsize=None, - debug = 0, - ): - """Create a hardcopy of the current plot. - - Create a postscript hardcopy of the current plot to the - default printer (if configured) or to the specified filename. - - Note that gnuplot remembers the postscript suboptions across - terminal changes. Therefore if you set, for example, color=1 - for one hardcopy then the next hardcopy will also be color - unless you explicitly choose color=0. Alternately you can - force all of the options to their defaults by setting - mode='default'. I consider this to be a bug in gnuplot. - - Keyword arguments: - - 'filename=<string>' -- if a filename is specified, save the - output in that file; otherwise print it immediately - using the 'default_lpr' configuration option. If the - filename ends in '.eps', EPS mode is automatically - selected (like manually specifying eps=1 or mode='eps'). - - 'mode=<string>' -- set the postscript submode ('landscape', - 'portrait', 'eps', or 'default'). The default is - to leave this option unspecified. - - 'eps=<bool>' -- shorthand for 'mode="eps"'; asks gnuplot to - generate encapsulated postscript. - - 'enhanced=<bool>' -- if set (the default), then generate - enhanced postscript, which allows extra features like - font-switching, superscripts, and subscripts in axis - labels. (Some old gnuplot versions do not support - enhanced postscript; if this is the case set - gp.GnuplotOpts.prefer_enhanced_postscript=None.) - - 'color=<bool>' -- if set, create a plot with color. Default - is to leave this option unchanged. - - 'solid=<bool>' -- if set, force lines to be solid (i.e., not - dashed). - - 'duplexing=<string>' -- set duplexing option ('defaultplex', - 'simplex', or 'duplex'). Only request double-sided - printing if your printer can handle it. Actually this - option is probably meaningless since hardcopy() can only - print a single plot at a time. - - 'fontname=<string>' -- set the default font to <string>, - which must be a valid postscript font. The default is - to leave this option unspecified. - - 'fontsize=<double>' -- set the default font size, in - postscript points. - - 'debug=<bool>' -- print extra debugging information (useful if - your PostScript files are misteriously not being created). - """ - - if filename is None: - assert gp.GnuplotOpts.default_lpr is not None, \ - OptionException('default_lpr is not set, so you can only ' - 'print to a file.') - filename = gp.GnuplotOpts.default_lpr - lpr_output = 1 - else: - if filename.endswith('.eps'): - eps = 1 - lpr_output = 0 - - # Be careful processing the options. If the user didn't - # request an option explicitly, do not specify it on the 'set - # terminal' line (don't even specify the default value for the - # option). This is to avoid confusing older versions of - # gnuplot that do not support all of these options. The - # exception is 'enhanced', which is just too useful to have to - # specify each time! - - setterm = ['set', 'terminal', 'postscript'] - if eps: - assert mode is None or mode=='eps', \ - OptionException('eps option and mode are incompatible') - setterm.append('eps') - else: - if mode is not None: - assert mode in ['landscape', 'portrait', 'eps', 'default'], \ - OptionException('illegal mode "%s"' % mode) - setterm.append(mode) - if enhanced is None: - enhanced = gp.GnuplotOpts.prefer_enhanced_postscript - if enhanced is not None: - if enhanced: setterm.append('enhanced') - else: setterm.append('noenhanced') - if color is not None: - if color: setterm.append('color') - else: setterm.append('monochrome') - if solid is not None: - if solid: setterm.append('solid') - else: setterm.append('dashed') - if duplexing is not None: - assert duplexing in ['defaultplex', 'simplex', 'duplex'], \ - OptionException('illegal duplexing mode "%s"' % duplexing) - setterm.append(duplexing) - if fontname is not None: - setterm.append('"%s"' % fontname) - if fontsize is not None: - setterm.append('%s' % fontsize) - - self(string.join(setterm)) - self.set_string('output', filename) - # replot the current figure (to the printer): - self.refresh() - - # fperez. Ugly kludge: often for some reason the file is NOT created - # and we must reissue the creation commands. I have no idea why! - if not lpr_output: - #print 'Hardcopy <%s>' % filename # dbg - maxtries = 20 - delay = 0.1 # delay (in seconds) between print attempts - for i in range(maxtries): - time.sleep(0.05) # safety, very small delay - if os.path.isfile(filename): - if debug: - print 'Hardcopy to file <%s> success at attempt #%s.' \ - % (filename,i+1) - break - time.sleep(delay) - # try again, issue all commands just in case - self(string.join(setterm)) - self.set_string('output', filename) - self.refresh() - if not os.path.isfile(filename): - print >> sys.stderr,'ERROR: Tried %s times and failed to '\ - 'create hardcopy file `%s`' % (maxtries,filename) - - # reset the terminal to its `default' setting: - self('set terminal %s' % gp.GnuplotOpts.default_term) - self.set_string('output') - -#********************** End of file <Gnuplot2.py> ************************ diff --git a/IPython/deathrow/GnuplotInteractive.py b/IPython/deathrow/GnuplotInteractive.py deleted file mode 100644 index b528428..0000000 --- a/IPython/deathrow/GnuplotInteractive.py +++ /dev/null @@ -1,148 +0,0 @@ -# -*- coding: utf-8 -*- -"""Interactive functions and magic functions for Gnuplot usage. - -This requires the Gnuplot.py module for interfacing python with Gnuplot, which -can be downloaded from: - -http://gnuplot-py.sourceforge.net/ - -See gphelp() below for details on the services offered by this module. - -Inspired by a suggestion/request from Arnd Baecker. -""" - -__all__ = ['Gnuplot','gp','gp_new','plot','plot2','splot','replot', - 'hardcopy','gpdata','gpfile','gpstring','gpfunc','gpgrid', - 'gphelp'] - -import IPython.GnuplotRuntime as GRun -from IPython.utils.genutils import warn -from IPython.core import page - -# Set global names for interactive use -Gnuplot = GRun.Gnuplot -gp_new = GRun.gp_new -gp = GRun.gp -plot = gp.plot -plot2 = gp.plot2 -splot = gp.splot -replot = gp.replot -hardcopy = gp.hardcopy - -# Accessors for the main plot object constructors: -gpdata = Gnuplot.Data -gpfile = Gnuplot.File -gpstring = Gnuplot.String -gpfunc = Gnuplot.Func -gpgrid = Gnuplot.GridData - -def gphelp(): - """Print information about the Gnuplot facilities in IPython.""" - - page(""" -IPython provides an interface to access the Gnuplot scientific plotting -system, in an environment similar to that of Mathematica or Matlab. - -New top-level global objects ----------------------------- - -Please see their respective docstrings for further details. - -- gp: a running Gnuplot instance. You can access its methods as -gp.<method>. gp(`a string`) will execute the given string as if it had been -typed in an interactive gnuplot window. - -- plot, splot, replot and hardcopy: aliases to the methods of the same name in -the global running Gnuplot instance gp. These allow you to simply type: - -In [1]: plot(x,sin(x),title='Sin(x)') # assuming x is a Numeric array - -and obtain a plot of sin(x) vs x with the title 'Sin(x)'. - -- gp_new: a function which returns a new Gnuplot instance. This can be used to -have multiple Gnuplot instances running in your session to compare different -plots, each in a separate window. - -- Gnuplot: alias to the Gnuplot2 module, an improved drop-in replacement for -the original Gnuplot.py. Gnuplot2 needs Gnuplot but redefines several of its -functions with improved versions (Gnuplot2 comes with IPython). - -- gpdata, gpfile, gpstring, gpfunc, gpgrid: aliases to Gnuplot.Data, -Gnuplot.File, Gnuplot.String, Gnuplot.Func and Gnuplot.GridData -respectively. These functions create objects which can then be passed to the -plotting commands. See the Gnuplot.py documentation for details. - -Keep in mind that all commands passed to a Gnuplot instance are executed in -the Gnuplot namespace, where no Python variables exist. For example, for -plotting sin(x) vs x as above, typing - -In [2]: gp('plot x,sin(x)') - -would not work. Instead, you would get the plot of BOTH the functions 'x' and -'sin(x)', since Gnuplot doesn't know about the 'x' Python array. The plot() -method lives in python and does know about these variables. - - -New magic functions -------------------- - -%gpc: pass one command to Gnuplot and execute it or open a Gnuplot shell where -each line of input is executed. - -%gp_set_default: reset the value of IPython's global Gnuplot instance.""") - -# Code below is all for IPython use -# Define the magic functions for communicating with the above gnuplot instance. -def magic_gpc(self,parameter_s=''): - """Execute a gnuplot command or open a gnuplot shell. - - Usage (omit the % if automagic is on). There are two ways to use it: - - 1) %gpc 'command' -> passes 'command' directly to the gnuplot instance. - - 2) %gpc -> will open up a prompt (gnuplot>>>) which takes input like the - standard gnuplot interactive prompt. If you need to type a multi-line - command, use \\ at the end of each intermediate line. - - Upon exiting of the gnuplot sub-shell, you return to your IPython - session (the gnuplot sub-shell can be invoked as many times as needed). - """ - - if parameter_s.strip(): - self.shell.gnuplot(parameter_s) - else: - self.shell.gnuplot.interact() - -def magic_gp_set_default(self,parameter_s=''): - """Set the default gnuplot instance accessed by the %gp magic function. - - %gp_set_default name - - Call with the name of the new instance at the command line. If you want to - set this instance in your own code (using an embedded IPython, for - example), simply set the variable __IPYTHON__.gnuplot to your own gnuplot - instance object.""" - - gname = parameter_s.strip() - G = eval(gname,self.shell.user_ns) - self.shell.gnuplot = G - self.shell.user_ns.update({'plot':G.plot,'splot':G.splot,'plot2':G.plot2, - 'replot':G.replot,'hardcopy':G.hardcopy}) - -try: - __IPYTHON__ -except NameError: - pass -else: - # make the global Gnuplot instance known to IPython - __IPYTHON__.gnuplot = GRun.gp - __IPYTHON__.gnuplot.shell_first_time = 1 - - print """*** Type `gphelp` for help on the Gnuplot integration features.""" - - # Add the new magic functions to the class dict - from IPython.core.iplib import InteractiveShell - InteractiveShell.magic_gpc = magic_gpc - InteractiveShell.magic_gp_set_default = magic_gp_set_default - -#********************** End of file <GnuplotInteractive.py> ******************* diff --git a/IPython/deathrow/GnuplotRuntime.py b/IPython/deathrow/GnuplotRuntime.py deleted file mode 100644 index 8d524e3..0000000 --- a/IPython/deathrow/GnuplotRuntime.py +++ /dev/null @@ -1,146 +0,0 @@ -# -*- coding: utf-8 -*- -"""Basic Gnuplot functionality for inclusion in other code. - -This module creates a running Gnuplot instance called 'gp' and builds other -convenient globals for quick use in running scripts. It is intended to allow -you to script plotting tasks in Python with a minimum of effort. A typical -usage would be: - -import IPython.GnuplotRuntime as GP # or some other short name -GP.gp.plot(GP.File('your_data.dat')) - - -This module exposes the following objects: - -- gp: a running Gnuplot instance. You can access its methods as -gp.<method>. gp(`a string`) will execute the given string as if it had been -typed in an interactive gnuplot window. - -- gp_new: a function which returns a new Gnuplot instance. This can be used to -have multiple Gnuplot instances running in your session to compare different -plots. - -- Gnuplot: alias to the Gnuplot2 module, an improved drop-in replacement for -the original Gnuplot.py. Gnuplot2 needs Gnuplot but redefines several of its -functions with improved versions (Gnuplot2 comes with IPython). - -- Data: alias to Gnuplot.Data, makes a PlotItem from array data. - -- File: alias to Gnuplot.File, makes a PlotItem from a file. - -- String: alias to Gnuplot.String, makes a PlotItem from a string formatted -exactly like a file for Gnuplot.File would be. - -- Func: alias to Gnuplot.Func, makes a PlotItem from a function string. - -- GridData: alias to Gnuplot.GridData, makes a PlotItem from grid data. - -- pm3d_config: a string with Gnuplot commands to set up the pm3d mode for -surface plotting. You can activate it simply by calling gp(pm3d_config). - -- eps_fix_bbox: A Unix-only function to fix eps files with bad bounding boxes -(which Gnuplot generates when the plot size is set to square). - -This requires the Gnuplot.py module for interfacing Python with Gnuplot, which -can be downloaded from: - -http://gnuplot-py.sourceforge.net/ - -Inspired by a suggestion/request from Arnd Baecker. -""" - -__all__ = ['Gnuplot','gp','gp_new','Data','File','Func','GridData', - 'pm3d_config','eps_fix_bbox'] - -import os,tempfile,sys -from IPython.utils.process import getoutput - -#--------------------------------------------------------------------------- -# Notes on mouse support for Gnuplot.py - -# If you do not have a mouse-enabled gnuplot, set gnuplot_mouse to 0. If you -# use gnuplot, you should really grab a recent, mouse enabled copy. It is an -# extremely useful feature. Mouse support is official as of gnuplot 4.0, -# released in April 2004. - -# For the mouse features to work correctly, you MUST set your Gnuplot.py -# module to use temporary files instead of 'inline data' for data -# communication. Note that this is the default, so unless you've manually -# fiddled with it you should be ok. If you need to make changes, in the -# Gnuplot module directory, loook for the gp_unix.py file and make sure the -# prefer_inline_data variable is set to 0. If you set it to 1 Gnuplot.py will -# try to pass the data to gnuplot via standard input, which completely -# confuses the mouse control system (even though it may be a bit faster than -# using temp files). - -# As of Gnuplot.py v1.7, a new option was added to use FIFOs (pipes). This -# mechanism, while fast, also breaks the mouse system. You must therefore set -# the variable prefer_fifo_data to 0 in gp_unix.py. - -tmpname = tempfile.mktemp() -open(tmpname,'w').write('set mouse') -gnu_out = getoutput('gnuplot '+ tmpname) -os.unlink(tmpname) -if gnu_out: # Gnuplot won't print anything if it has mouse support - print "*** Your version of Gnuplot appears not to have mouse support." - gnuplot_mouse = 0 -else: - gnuplot_mouse = 1 -del tmpname,gnu_out - -# Default state for persistence of new gnuplot instances -if os.name in ['nt','dos'] or sys.platform == 'cygwin': - gnuplot_persist = 0 -else: - gnuplot_persist = 1 - -import IPython.Gnuplot2 as Gnuplot - -class NotGiven: pass - -def gp_new(mouse=NotGiven,persist=NotGiven): - """Return a new Gnuplot instance. - - The instance returned uses the improved methods defined in Gnuplot2. - - Options (boolean): - - - mouse: if unspecified, the module global gnuplot_mouse is used. - - - persist: if unspecified, the module global gnuplot_persist is used.""" - - if mouse is NotGiven: - mouse = gnuplot_mouse - if persist is NotGiven: - persist = gnuplot_persist - g = Gnuplot.Gnuplot(persist=persist) - if mouse: - g('set mouse') - return g - -# Global-level names. - -# A global Gnuplot instance for interactive use: -gp = gp_new() - -# Accessors for the main plot object constructors: -Data = Gnuplot.Data -File = Gnuplot.File -Func = Gnuplot.Func -String = Gnuplot.String -GridData = Gnuplot.GridData - -# A Unix-only function to fix eps files with bad bounding boxes (which Gnuplot -# generates when the plot size is set to square): -eps_fix_bbox = Gnuplot.eps_fix_bbox - -# String for configuring pm3d. Simply call g(pm3d_config) to execute it. pm3d -# is a very nice mode for plotting colormaps on surfaces. Modify the defaults -# below to suit your taste. -pm3d_config = """ -set pm3d solid -set hidden3d -unset surface -set isosamples 50 -""" -#******************** End of file <GnuplotRuntime.py> ****************** diff --git a/IPython/deathrow/PhysicalQInput.py b/IPython/deathrow/PhysicalQInput.py deleted file mode 100644 index aac8788..0000000 --- a/IPython/deathrow/PhysicalQInput.py +++ /dev/null @@ -1,84 +0,0 @@ -# -*- coding: utf-8 -*- -"""Modified input prompt for entering quantities with units. - -Modify the behavior of the interactive interpreter to allow direct input of -quantities with units without having to make a function call. - -Now the following forms are accepted: - -x = 4 m -y = -.45e3 m/s -g = 9.8 m/s**2 -a = 2.3 m/s^2 # ^ -> ** automatically - -All other input is processed normally. - -Authors -------- -- Fernando Perez <Fernando.Perez@berkeley.edu> -""" -#***************************************************************************** -# Copyright (C) 2008-2011 The IPython Development Team -# Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#***************************************************************************** - -# This file is an example of how to modify IPython's line-processing behavior -# without touching the internal code. We'll define an alternate pre-processing -# stage which allows a special form of input (which is invalid Python syntax) -# for certain quantities, rewrites a line of proper Python in those cases, and -# then passes it off to IPython's normal processor for further work. - -# With this kind of customization, IPython can be adapted for many -# special-purpose scenarios providing alternate input syntaxes. - -# This file can be imported like a regular module. - -# IPython has a prefilter() function that analyzes each input line. We redefine -# it here to first pre-process certain forms of input - -# The prototype of any alternate prefilter must be like this one (the name -# doesn't matter): -# - line is a string containing the user input line. -# - continuation is a parameter which tells us if we are processing a first line of -# user input or the second or higher of a multi-line statement. - -def prefilter_PQ(self,line,continuation): - """Alternate prefilter for input of PhysicalQuantityInteractive objects. - - This assumes that the function PhysicalQuantityInteractive() has been - imported.""" - - from re import match - from IPython.core.iplib import InteractiveShell - - # This regexp is what does the real work - unit_split = match(r'\s*(\w+)\s*=\s*(-?\d*\.?\d*[eE]?-?\d*)\s+([a-zA-Z].*)', - line) - - # If special input was ecnountered, process it: - if unit_split: - var,val,units = unit_split.groups() - if var and val and units: - units = units.replace('^','**') - # Now a valid line needs to be constructed for IPython to process: - line = var +" = PhysicalQuantityInteractive(" + val + ", '" + \ - units + "')" - #print 'New line:',line # dbg - - # In the end, always call the default IPython _prefilter() function. Note - # that self must be passed explicitly, b/c we're calling the unbound class - # method (since this method will overwrite the instance prefilter()) - return InteractiveShell._prefilter(self,line,continuation) - -# Rebind this to be the new IPython prefilter: -from IPython.core.iplib import InteractiveShell -InteractiveShell.prefilter = prefilter_PQ - -# Clean up the namespace. -del InteractiveShell,prefilter_PQ - -# Just a heads up at the console -print '*** Simplified input for physical quantities enabled.' diff --git a/IPython/deathrow/PhysicalQInteractive.py b/IPython/deathrow/PhysicalQInteractive.py deleted file mode 100644 index 338bb4d..0000000 --- a/IPython/deathrow/PhysicalQInteractive.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -"""Modify the PhysicalQuantities class for more convenient interactive use. - -Also redefine some math functions to operate on PhysQties with no need for -special method syntax. This just means moving them out to the global -namespace. - -This module should always be loaded *after* math or Numeric, so it can -overwrite math functions with the versions that handle units. - -Authors -------- -- Fernando Perez <Fernando.Perez@berkeley.edu> -""" - -#***************************************************************************** -# Copyright (C) 2008-2011 The IPython Development Team -# Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#***************************************************************************** - -from Scientific.Physics.PhysicalQuantities import PhysicalQuantity - -# This code can be set up to work with Numeric or with math for providing the -# mathematical functions. Uncomment the one you prefer to use below. - -# If you use math, sin(x) won't work for x an array, only float or PhysQty -import math - -# If you use Numeric, sin(x) works for x a float, PhysQty an array. -#import Numeric as math - -class PhysicalQuantityFunction: - """Generic function wrapper for PhysicalQuantity instances. - - Calls functions from either the math library or the instance's methods as - required. Allows using sin(theta) or sqrt(v**2) syntax irrespective of - whether theta is a pure number or a PhysicalQuantity. - - This is *slow*. It's meant for convenient interactive use, not for - speed.""" - - def __init__(self,name): - self.name = name - - def __call__(self,x): - if isinstance(x,PhysicalQuantity): - return PhysicalQuantity.__dict__[self.name](x) - else: - return math.__dict__[self.name](x) - -class PhysicalQuantityInteractive(PhysicalQuantity): - """Physical quantity with units - modified for Interactive use. - - Basically, the __str__ and __repr__ methods have been swapped for more - convenient interactive use. Powers are shown as ^ instead of ** and only 4 - significant figures are shown. - - Also adds the following aliases for commonly used methods: - b = PhysicalQuantity.inBaseUnits - u = PhysicalQuantity.inUnitsOf - - These are useful when doing a lot of interactive calculations. - """ - - # shorthands for the most useful unit conversions - b = PhysicalQuantity.inBaseUnits # so you can just type x.b to get base units - u = PhysicalQuantity.inUnitsOf - - # This can be done, but it can get dangerous when coupled with IPython's - # auto-calling. Everything ends up shown in baseunits and things like x*2 - # get automatically converted to k(*2), which doesn't work. - # Probably not a good idea in general... - #__call__ = b - - def __str__(self): - return PhysicalQuantity.__repr__(self) - - def __repr__(self): - value = '%.4G' % self.value - units = self.unit.name().replace('**','^') - return value + ' ' + units - -# implement the methods defined in PhysicalQuantity as PhysicalQuantityFunctions -sin = PhysicalQuantityFunction('sin') -cos = PhysicalQuantityFunction('cos') -tan = PhysicalQuantityFunction('tan') -sqrt = PhysicalQuantityFunction('sqrt') diff --git a/IPython/deathrow/Shell.py b/IPython/deathrow/Shell.py deleted file mode 100644 index cd8bb0c..0000000 --- a/IPython/deathrow/Shell.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python -# encoding: utf-8 -""" -A backwards compatibility layer for IPython.Shell. - -Previously, IPython had an IPython.Shell module. IPython.Shell has been moved -to IPython.core.shell and is being refactored. This new module is provided -for backwards compatability. We strongly encourage everyone to start using -the new code in IPython.core.shell. -""" - -#----------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#----------------------------------------------------------------------------- - -from warnings import warn - -msg = """ -This module (IPython.Shell) is deprecated. The classes that were in this -module have been replaced by: - -IPShell->IPython.core.iplib.InteractiveShell -IPShellEmbed->IPython.core.embed.InteractiveShellEmbed - -Please migrate your code to use these classes instead. -""" - -warn(msg, category=DeprecationWarning, stacklevel=1) - -from IPython.core.iplib import InteractiveShell as IPShell -from IPython.core.embed import InteractiveShellEmbed as IPShellEmbed - -def start(user_ns=None, embedded=False): - """Return an instance of :class:`InteractiveShell`.""" - if embedded: - return IPShellEmbed(user_ns=user_ns) - else: - return IPShell(user_ns=user_ns) - diff --git a/IPython/deathrow/astyle.py b/IPython/deathrow/astyle.py deleted file mode 100644 index 9821d58..0000000 --- a/IPython/deathrow/astyle.py +++ /dev/null @@ -1,400 +0,0 @@ -""" -``astyle`` provides classes for adding style (foreground and background color; -bold; blink; etc.) to terminal and curses output. -""" - - -import sys, os - -try: - import curses -except ImportError: - curses = None - - -COLOR_BLACK = 0 -COLOR_RED = 1 -COLOR_GREEN = 2 -COLOR_YELLOW = 3 -COLOR_BLUE = 4 -COLOR_MAGENTA = 5 -COLOR_CYAN = 6 -COLOR_WHITE = 7 - -A_BLINK = 1<<0 # Blinking text -A_BOLD = 1<<1 # Extra bright or bold text -A_DIM = 1<<2 # Half bright text -A_REVERSE = 1<<3 # Reverse-video text -A_STANDOUT = 1<<4 # The best highlighting mode available -A_UNDERLINE = 1<<5 # Underlined text - - -class Style(object): - """ - Store foreground color, background color and attribute (bold, underlined - etc.). - """ - __slots__ = ("fg", "bg", "attrs") - - COLORNAMES = { - "black": COLOR_BLACK, - "red": COLOR_RED, - "green": COLOR_GREEN, - "yellow": COLOR_YELLOW, - "blue": COLOR_BLUE, - "magenta": COLOR_MAGENTA, - "cyan": COLOR_CYAN, - "white": COLOR_WHITE, - } - ATTRNAMES = { - "blink": A_BLINK, - "bold": A_BOLD, - "dim": A_DIM, - "reverse": A_REVERSE, - "standout": A_STANDOUT, - "underline": A_UNDERLINE, - } - - def __init__(self, fg, bg, attrs=0): - """ - Create a ``Style`` object with ``fg`` as the foreground color, - ``bg`` as the background color and ``attrs`` as the attributes. - - Examples: - >>> Style(COLOR_RED, COLOR_BLACK) - <Style fg=red bg=black attrs=0> - - >>> Style(COLOR_YELLOW, COLOR_BLUE, A_BOLD|A_UNDERLINE) - <Style fg=yellow bg=blue attrs=bold|underline> - """ - self.fg = fg - self.bg = bg - self.attrs = attrs - - def __call__(self, *args): - text = Text() - for arg in args: - if isinstance(arg, Text): - text.extend(arg) - else: - text.append((self, arg)) - return text - - def __eq__(self, other): - return self.fg == other.fg and self.bg == other.bg and self.attrs == other.attrs - - def __neq__(self, other): - return self.fg != other.fg or self.bg != other.bg or self.attrs != other.attrs - - def __repr__(self): - color2name = ("black", "red", "green", "yellow", "blue", "magenta", "cyan", "white") - attrs2name = ("blink", "bold", "dim", "reverse", "standout", "underline") - - return "<%s fg=%s bg=%s attrs=%s>" % ( - self.__class__.__name__, color2name[self.fg], color2name[self.bg], - "|".join([attrs2name[b] for b in xrange(6) if self.attrs&(1<<b)]) or 0) - - def fromstr(cls, value): - """ - Create a ``Style`` object from a string. The format looks like this: - ``"red:black:bold|blink"``. - """ - # defaults - fg = COLOR_WHITE - bg = COLOR_BLACK - attrs = 0 - - parts = value.split(":") - if len(parts) > 0: - fg = cls.COLORNAMES[parts[0].lower()] - if len(parts) > 1: - bg = cls.COLORNAMES[parts[1].lower()] - if len(parts) > 2: - for strattr in parts[2].split("|"): - attrs |= cls.ATTRNAMES[strattr.lower()] - return cls(fg, bg, attrs) - fromstr = classmethod(fromstr) - - def fromenv(cls, name, default): - """ - Create a ``Style`` from an environment variable named ``name`` - (using ``default`` if the environment variable doesn't exist). - """ - return cls.fromstr(os.environ.get(name, default)) - fromenv = classmethod(fromenv) - - -def switchstyle(s1, s2): - """ - Return the ANSI escape sequence needed to switch from style ``s1`` to - style ``s2``. - """ - attrmask = (A_BLINK|A_BOLD|A_UNDERLINE|A_REVERSE) - a1 = s1.attrs & attrmask - a2 = s2.attrs & attrmask - - args = [] - if s1 != s2: - # do we have to get rid of the bold/underline/blink bit? - # (can only be done by a reset) - # use reset when our target color is the default color - # (this is shorter than 37;40) - if (a1 & ~a2 or s2==style_default): - args.append("0") - s1 = style_default - a1 = 0 - - # now we know that old and new color have the same boldness, - # or the new color is bold and the old isn't, - # i.e. we only might have to switch bold on, not off - if not (a1 & A_BOLD) and (a2 & A_BOLD): - args.append("1") - - # Fix underline - if not (a1 & A_UNDERLINE) and (a2 & A_UNDERLINE): - args.append("4") - - # Fix blink - if not (a1 & A_BLINK) and (a2 & A_BLINK): - args.append("5") - - # Fix reverse - if not (a1 & A_REVERSE) and (a2 & A_REVERSE): - args.append("7") - - # Fix foreground color - if s1.fg != s2.fg: - args.append("3%d" % s2.fg) - - # Finally fix the background color - if s1.bg != s2.bg: - args.append("4%d" % s2.bg) - - if args: - return "\033[%sm" % ";".join(args) - return "" - - -class Text(list): - """ - A colored string. A ``Text`` object is a sequence, the sequence - items will be ``(style, string)`` tuples. - """ - - def __init__(self, *args): - list.__init__(self) - self.append(*args) - - def __repr__(self): - return "%s.%s(%s)" % ( - self.__class__.__module__, self.__class__.__name__, - list.__repr__(self)[1:-1]) - - def append(self, *args): - for arg in args: - if isinstance(arg, Text): - self.extend(arg) - elif isinstance(arg, tuple): # must be (style, string) - list.append(self, arg) - elif isinstance(arg, unicode): - list.append(self, (style_default, arg)) - else: - list.append(self, (style_default, str(arg))) - - def insert(self, index, *args): - self[index:index] = Text(*args) - - def __add__(self, other): - new = Text() - new.append(self) - new.append(other) - return new - - def __iadd__(self, other): - self.append(other) - return self - - def format(self, styled=True): - """ - This generator yields the strings that will make up the final - colorized string. - """ - if styled: - oldstyle = style_default - for (style, string) in self: - if not isinstance(style, (int, long)): - switch = switchstyle(oldstyle, style) - if switch: - yield switch - if string: - yield string - oldstyle = style - switch = switchstyle(oldstyle, style_default) - if switch: - yield switch - else: - for (style, string) in self: - if not isinstance(style, (int, long)): - yield string - - def string(self, styled=True): - """ - Return the resulting string (with escape sequences, if ``styled`` - is true). - """ - return "".join(self.format(styled)) - - def __str__(self): - """ - Return ``self`` as a string (without ANSI escape sequences). - """ - return self.string(False) - - def write(self, stream, styled=True): - """ - Write ``self`` to the output stream ``stream`` (with escape sequences, - if ``styled`` is true). - """ - for part in self.format(styled): - stream.write(part) - - -try: - import ipipe -except ImportError: - pass -else: - def xrepr_astyle_text(self, mode="default"): - yield (-1, True) - for info in self: - yield info - ipipe.xrepr.when_type(Text)(xrepr_astyle_text) - - -def streamstyle(stream, styled=None): - """ - If ``styled`` is ``None``, return whether ``stream`` refers to a terminal. - If this can't be determined (either because ``stream`` doesn't refer to a - real OS file, or because you're on Windows) return ``False``. If ``styled`` - is not ``None`` ``styled`` will be returned unchanged. - """ - if styled is None: - try: - styled = os.isatty(stream.fileno()) - except (KeyboardInterrupt, SystemExit): - raise - except Exception: - styled = False - return styled - - -def write(stream, styled, *texts): - """ - Write ``texts`` to ``stream``. - """ - text = Text(*texts) - text.write(stream, streamstyle(stream, styled)) - - -def writeln(stream, styled, *texts): - """ - Write ``texts`` to ``stream`` and finish with a line feed. - """ - write(stream, styled, *texts) - stream.write("\n") - - -class Stream(object): - """ - Stream wrapper that adds color output. - """ - def __init__(self, stream, styled=None): - self.stream = stream - self.styled = streamstyle(stream, styled) - - def write(self, *texts): - write(self.stream, self.styled, *texts) - - def writeln(self, *texts): - writeln(self.stream, self.styled, *texts) - - def __getattr__(self, name): - return getattr(self.stream, name) - - -class stdout(object): - """ - Stream wrapper for ``sys.stdout`` that adds color output. - """ - def write(self, *texts): - write(sys.stdout, None, *texts) - - def writeln(self, *texts): - writeln(sys.stdout, None, *texts) - - def __getattr__(self, name): - return getattr(sys.stdout, name) -stdout = stdout() - - -class stderr(object): - """ - Stream wrapper for ``sys.stderr`` that adds color output. - """ - def write(self, *texts): - write(sys.stderr, None, *texts) - - def writeln(self, *texts): - writeln(sys.stderr, None, *texts) - - def __getattr__(self, name): - return getattr(sys.stdout, name) -stderr = stderr() - - -if curses is not None: - # This is probably just range(8) - COLOR2CURSES = [ - COLOR_BLACK, - COLOR_RED, - COLOR_GREEN, - COLOR_YELLOW, - COLOR_BLUE, - COLOR_MAGENTA, - COLOR_CYAN, - COLOR_WHITE, - ] - - A2CURSES = { - A_BLINK: curses.A_BLINK, - A_BOLD: curses.A_BOLD, - A_DIM: curses.A_DIM, - A_REVERSE: curses.A_REVERSE, - A_STANDOUT: curses.A_STANDOUT, - A_UNDERLINE: curses.A_UNDERLINE, - } - - -# default style -style_default = Style.fromstr("white:black") - -# Styles for datatypes -style_type_none = Style.fromstr("magenta:black") -style_type_bool = Style.fromstr("magenta:black") -style_type_number = Style.fromstr("yellow:black") -style_type_datetime = Style.fromstr("magenta:black") -style_type_type = Style.fromstr("cyan:black") - -# Style for URLs and file/directory names -style_url = Style.fromstr("green:black") -style_dir = Style.fromstr("cyan:black") -style_file = Style.fromstr("green:black") - -# Style for ellipsis (when an output has been shortened -style_ellisis = Style.fromstr("red:black") - -# Style for displaying exceptions -style_error = Style.fromstr("red:black") - -# Style for displaying non-existing attributes -style_nodata = Style.fromstr("red:black") diff --git a/IPython/deathrow/dtutils.py b/IPython/deathrow/dtutils.py deleted file mode 100644 index 41e377f..0000000 --- a/IPython/deathrow/dtutils.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Doctest-related utilities for IPython. - -For most common uses, all you should need to run is:: - - from IPython.dtutils import idoctest - -See the idoctest docstring below for usage details. -""" - -import doctest -import sys - -from IPython.core import ipapi -ip = ipapi.get() - -def rundoctest(text,ns=None,eraise=False): - """Run a the input source as a doctest, in the caller's namespace. - - :Parameters: - text : str - Source to execute. - - :Keywords: - ns : dict (None) - Namespace where the code should be executed. If not given, the - caller's locals and globals are used. - eraise : bool (False) - If true, immediately raise any exceptions instead of reporting them at - the end. This allows you to then do interactive debugging via - IPython's facilities (use %debug after the fact, or with %pdb for - automatic activation). - """ - - name = 'interactive doctest' - filename = '<IPython console>' - - if eraise: - runner = doctest.DebugRunner() - else: - runner = doctest.DocTestRunner() - - parser = doctest.DocTestParser() - if ns is None: - f = sys._getframe(1) - ns = f.f_globals.copy() - ns.update(f.f_locals) - - test = parser.get_doctest(text,ns,name,filename,0) - runner.run(test) - runner.summarize(True) - - -def idoctest(ns=None,eraise=False): - """Interactively prompt for input and run it as a doctest. - - To finish entering input, enter two blank lines or Ctrl-D (EOF). If you - use Ctrl-C, the example is aborted and all input discarded. - - :Keywords: - ns : dict (None) - Namespace where the code should be executed. If not given, the IPython - interactive namespace is used. - eraise : bool (False) - If true, immediately raise any exceptions instead of reporting them at - the end. This allows you to then do interactive debugging via - IPython's facilities (use %debug after the fact, or with %pdb for - automatic activation). - end_mark : str ('--') - String to explicitly indicate the end of input. - - """ - - inlines = [] - empty_lines = 0 # count consecutive empty lines - run_test = True - - if ns is None: - ns = ip.user_ns - - ip.savehist() - try: - while True: - line = raw_input() - if not line or line.isspace(): - empty_lines += 1 - else: - empty_lines = 0 - - if empty_lines>=2: - break - - inlines.append(line) - except EOFError: - pass - except KeyboardInterrupt: - print "KeyboardInterrupt - Discarding input." - run_test = False - - ip.reloadhist() - - if run_test: - # Extra blank line at the end to ensure that the final docstring has a - # closing newline - inlines.append('') - rundoctest('\n'.join(inlines),ns,eraise) - - -# For debugging of this module itself. -if __name__ == "__main__": - t = """ - >>> for i in range(10): - ... print i, - ... - 0 1 2 3 4 5 6 7 8 9 - """ - - t2 = """ - A simple example:: - - >>> for i in range(10): - ... print i, - ... - 0 1 2 3 4 5 6 7 8 9 - - Some more details:: - - >>> print "hello" - hello - """ - - t3 = """ - A failing example:: - - >>> x=1 - >>> x+1 - 3 - """ diff --git a/IPython/deathrow/gui/wx/ipshell_nonblocking.py b/IPython/deathrow/gui/wx/ipshell_nonblocking.py deleted file mode 100755 index 5a152fc..0000000 --- a/IPython/deathrow/gui/wx/ipshell_nonblocking.py +++ /dev/null @@ -1,518 +0,0 @@ -#!/usr/bin/python -# -*- coding: iso-8859-15 -*- -''' -Provides IPython remote instance. - -@author: Laurent Dufrechou -laurent.dufrechou _at_ gmail.com -@license: BSD - -All rights reserved. This program and the accompanying materials are made -available under the terms of the BSD which accompanies this distribution, and -is available at U{http://www.opensource.org/licenses/bsd-license.php} -''' - -__version__ = 0.9 -__author__ = "Laurent Dufrechou" -__email__ = "laurent.dufrechou _at_ gmail.com" -__license__ = "BSD" - -import re -import sys -import os -import locale -from thread_ex import ThreadEx - -from IPython.core import iplib -import IPython.utils.io - -############################################################################## -class _Helper(object): - """Redefine the built-in 'help'. - This is a wrapper around pydoc.help (with a twist). - """ - - def __init__(self, pager): - self._pager = pager - - def __repr__(self): - return "Type help() for interactive help, " \ - "or help(object) for help about object." - - def __call__(self, *args, **kwds): - class DummyWriter(object): - '''Dumy class to handle help output''' - def __init__(self, pager): - self._pager = pager - - def write(self, data): - '''hook to fill self._pager''' - self._pager(data) - - import pydoc - pydoc.help.output = DummyWriter(self._pager) - pydoc.help.interact = lambda :1 - - return pydoc.help(*args, **kwds) - - -############################################################################## -class _CodeExecutor(ThreadEx): - ''' Thread that execute ipython code ''' - def __init__(self, instance): - ThreadEx.__init__(self) - self.instance = instance - - def run(self): - '''Thread main loop''' - try: - self.instance._doc_text = None - self.instance._help_text = None - self.instance._execute() - # used for uper class to generate event after execution - self.instance._after_execute() - - except KeyboardInterrupt: - pass - - -############################################################################## -class NonBlockingIPShell(object): - ''' - Create an IPython instance, running the commands in a separate, - non-blocking thread. - This allows embedding in any GUI without blockage. - - Note: The ThreadEx class supports asynchroneous function call - via raise_exc() - ''' - - def __init__(self, user_ns={}, user_global_ns=None, - cin=None, cout=None, cerr=None, - ask_exit_handler=None): - ''' - @param user_ns: User namespace. - @type user_ns: dictionary - @param user_global_ns: User global namespace. - @type user_global_ns: dictionary. - @param cin: Console standard input. - @type cin: IO stream - @param cout: Console standard output. - @type cout: IO stream - @param cerr: Console standard error. - @type cerr: IO stream - @param exit_handler: Replacement for builtin exit() function - @type exit_handler: function - @param time_loop: Define the sleep time between two thread's loop - @type int - ''' - #ipython0 initialisation - self._IP = None - self.init_ipython0(user_ns, user_global_ns, - cin, cout, cerr, - ask_exit_handler) - - #vars used by _execute - self._iter_more = 0 - self._history_level = 0 - self._complete_sep = re.compile('[\s\{\}\[\]\(\)\=]') - self._prompt = str(self._IP.outputcache.prompt1).strip() - - #thread working vars - self._line_to_execute = '' - self._threading = True - - #vars that will be checked by GUI loop to handle thread states... - #will be replaced later by PostEvent GUI funtions... - self._doc_text = None - self._help_text = None - self._add_button = None - - def init_ipython0(self, user_ns={}, user_global_ns=None, - cin=None, cout=None, cerr=None, - ask_exit_handler=None): - ''' Initialize an ipython0 instance ''' - - #first we redefine in/out/error functions of IPython - #BUG: we've got a limitation form ipython0 there - #only one instance can be instanciated else tehre will be - #cin/cout/cerr clash... - if cin: - Term.cin = cin - if cout: - Term.cout = cout - if cerr: - Term.cerr = cerr - - excepthook = sys.excepthook - - #Hack to save sys.displayhook, because ipython seems to overwrite it... - self.sys_displayhook_ori = sys.displayhook - ipython0 = iplib.InteractiveShell( - parent=None, config=None, - user_ns=user_ns, - user_global_ns=user_global_ns - ) - self._IP = ipython0 - - #we save ipython0 displayhook and we restore sys.displayhook - self.displayhook = sys.displayhook - sys.displayhook = self.sys_displayhook_ori - - #we replace IPython default encoding by wx locale encoding - loc = locale.getpreferredencoding() - if loc: - self._IP.stdin_encoding = loc - #we replace the ipython default pager by our pager - self._IP.set_hook('show_in_pager', self._pager) - - #we replace the ipython default shell command caller - #by our shell handler - self._IP.set_hook('shell_hook', self._shell) - - #we replace the ipython default input command caller by our method - iplib.raw_input_original = self._raw_input_original - #we replace the ipython default exit command by our method - self._IP.exit = ask_exit_handler - #we replace the help command - self._IP.user_ns['help'] = _Helper(self._pager_help) - - #we disable cpaste magic... until we found a way to use it properly. - def bypass_magic(self, arg): - print '%this magic is currently disabled.' - ipython0.define_magic('cpaste', bypass_magic) - - import __builtin__ - __builtin__.raw_input = self._raw_input - - sys.excepthook = excepthook - - #----------------------- Thread management section ---------------------- - def do_execute(self, line): - """ - Tell the thread to process the 'line' command - """ - - self._line_to_execute = line - - if self._threading: - #we launch the ipython line execution in a thread to make it - #interruptible with include it in self namespace to be able - #to call ce.raise_exc(KeyboardInterrupt) - self.ce = _CodeExecutor(self) - self.ce.start() - else: - try: - self._doc_text = None - self._help_text = None - self._execute() - # used for uper class to generate event after execution - self._after_execute() - - except KeyboardInterrupt: - pass - - #----------------------- IPython management section ---------------------- - def get_threading(self): - """ - Returns threading status, is set to True, then each command sent to - the interpreter will be executed in a separated thread allowing, - for example, breaking a long running commands. - Disallowing it, permits better compatibilty with instance that is embedding - IPython instance. - - @return: Execution method - @rtype: bool - """ - return self._threading - - def set_threading(self, state): - """ - Sets threading state, if set to True, then each command sent to - the interpreter will be executed in a separated thread allowing, - for example, breaking a long running commands. - Disallowing it, permits better compatibilty with instance that is embedding - IPython instance. - - @param state: Sets threading state - @type bool - """ - self._threading = state - - def get_doc_text(self): - """ - Returns the output of the processing that need to be paged (if any) - - @return: The std output string. - @rtype: string - """ - return self._doc_text - - def get_help_text(self): - """ - Returns the output of the processing that need to be paged via help pager(if any) - - @return: The std output string. - @rtype: string - """ - return self._help_text - - def get_banner(self): - """ - Returns the IPython banner for useful info on IPython instance - - @return: The banner string. - @rtype: string - """ - return self._IP.banner - - def get_prompt_count(self): - """ - Returns the prompt number. - Each time a user execute a line in the IPython shell the prompt count is increased - - @return: The prompt number - @rtype: int - """ - return self._IP.outputcache.prompt_count - - def get_prompt(self): - """ - Returns current prompt inside IPython instance - (Can be In [...]: ot ...:) - - @return: The current prompt. - @rtype: string - """ - return self._prompt - - def get_indentation(self): - """ - Returns the current indentation level - Usefull to put the caret at the good start position if we want to do autoindentation. - - @return: The indentation level. - @rtype: int - """ - return self._IP.indent_current_nsp - - def update_namespace(self, ns_dict): - ''' - Add the current dictionary to the shell namespace. - - @param ns_dict: A dictionary of symbol-values. - @type ns_dict: dictionary - ''' - self._IP.user_ns.update(ns_dict) - - def complete(self, line): - ''' - Returns an auto completed line and/or posibilities for completion. - - @param line: Given line so far. - @type line: string - - @return: Line completed as for as possible, - and possible further completions. - @rtype: tuple - ''' - split_line = self._complete_sep.split(line) - possibilities = self._IP.complete(split_line[-1]) - if possibilities: - - def _common_prefix(str1, str2): - ''' - Reduction function. returns common prefix of two given strings. - - @param str1: First string. - @type str1: string - @param str2: Second string - @type str2: string - - @return: Common prefix to both strings. - @rtype: string - ''' - for i in range(len(str1)): - if not str2.startswith(str1[:i+1]): - return str1[:i] - return str1 - common_prefix = reduce(_common_prefix, possibilities) - completed = line[:-len(split_line[-1])]+common_prefix - else: - completed = line - return completed, possibilities - - def history_back(self): - ''' - Provides one history command back. - - @return: The command string. - @rtype: string - ''' - history = '' - #the below while loop is used to suppress empty history lines - while((history == '' or history == '\n') and self._history_level >0): - if self._history_level >= 1: - self._history_level -= 1 - history = self._get_history() - return history - - def history_forward(self): - ''' - Provides one history command forward. - - @return: The command string. - @rtype: string - ''' - history = '' - #the below while loop is used to suppress empty history lines - while((history == '' or history == '\n') \ - and self._history_level <= self._get_history_max_index()): - if self._history_level < self._get_history_max_index(): - self._history_level += 1 - history = self._get_history() - else: - if self._history_level == self._get_history_max_index(): - history = self._get_history() - self._history_level += 1 - else: - history = '' - return history - - def init_history_index(self): - ''' - set history to last command entered - ''' - self._history_level = self._get_history_max_index()+1 - - #----------------------- IPython PRIVATE management section -------------- - def _after_execute(self): - ''' - Can be redefined to generate post event after excution is done - ''' - pass - - def _ask_exit(self): - ''' - Can be redefined to generate post event to exit the Ipython shell - ''' - pass - - def _get_history_max_index(self): - ''' - returns the max length of the history buffer - - @return: history length - @rtype: int - ''' - return len(self._IP.input_hist_raw)-1 - - def _get_history(self): - ''' - Get's the command string of the current history level. - - @return: Historic command stri - @rtype: string - ''' - rv = self._IP.input_hist_raw[self._history_level].strip('\n') - return rv - - def _pager_help(self, text): - ''' - This function is used as a callback replacment to IPython help pager function - - It puts the 'text' value inside the self._help_text string that can be retrived via - get_help_text function. - ''' - if self._help_text == None: - self._help_text = text - else: - self._help_text += text - - def _pager(self, IP, text): - ''' - This function is used as a callback replacment to IPython pager function - - It puts the 'text' value inside the self._doc_text string that can be retrived via - get_doc_text function. - ''' - self._doc_text = text - - def _raw_input_original(self, prompt=''): - ''' - Custom raw_input() replacement. Get's current line from console buffer. - - @param prompt: Prompt to print. Here for compatability as replacement. - @type prompt: string - - @return: The current command line text. - @rtype: string - ''' - return self._line_to_execute - - def _raw_input(self, prompt=''): - """ A replacement from python's raw_input. - """ - raise NotImplementedError - - def _execute(self): - ''' - Executes the current line provided by the shell object. - ''' - - orig_stdout = sys.stdout - sys.stdout = Term.cout - #self.sys_displayhook_ori = sys.displayhook - #sys.displayhook = self.displayhook - - try: - line = self._IP.raw_input(None, self._iter_more) - if self._IP.autoindent: - self._IP.readline_startup_hook(None) - - except KeyboardInterrupt: - self._IP.write('\nKeyboardInterrupt\n') - self._IP.resetbuffer() - # keep cache in sync with the prompt counter: - self._IP.outputcache.prompt_count -= 1 - - if self._IP.autoindent: - self._IP.indent_current_nsp = 0 - self._iter_more = 0 - except: - self._IP.showtraceback() - else: - self._IP.write(str(self._IP.outputcache.prompt_out).strip()) - self._iter_more = self._IP.push_line(line) - if (self._IP.SyntaxTB.last_syntax_error and \ - self._IP.autoedit_syntax): - self._IP.edit_syntax_error() - if self._iter_more: - self._prompt = str(self._IP.outputcache.prompt2).strip() - if self._IP.autoindent: - self._IP.readline_startup_hook(self._IP.pre_readline) - else: - self._prompt = str(self._IP.outputcache.prompt1).strip() - self._IP.indent_current_nsp = 0 #we set indentation to 0 - - sys.stdout = orig_stdout - #sys.displayhook = self.sys_displayhook_ori - - def _shell(self, ip, cmd): - ''' - Replacement method to allow shell commands without them blocking. - - @param ip: Ipython instance, same as self._IP - @type cmd: Ipython instance - @param cmd: Shell command to execute. - @type cmd: string - ''' - stdin, stdout = os.popen4(cmd) - result = stdout.read().decode('cp437').\ - encode(locale.getpreferredencoding()) - #we use print command because the shell command is called - #inside IPython instance and thus is redirected to thread cout - #"\x01\x1b[1;36m\x02" <-- add colour to the text... - print "\x01\x1b[1;36m\x02"+result - stdout.close() - stdin.close() diff --git a/IPython/deathrow/gui/wx/ipython_history.py b/IPython/deathrow/gui/wx/ipython_history.py deleted file mode 100644 index 7d8c0be..0000000 --- a/IPython/deathrow/gui/wx/ipython_history.py +++ /dev/null @@ -1,510 +0,0 @@ -#!/usr/bin/python -# -*- coding: iso-8859-15 -*- -import wx -import wx.stc as stc -import keyword - -#----------------------------------------- -# History widget for IPython -__version__ = 0.5 -__author__ = "Laurent Dufrechou" -__email__ = "laurent.dufrechou _at_ gmail.com" -__license__ = "BSD" -#----------------------------------------- - -class IPythonHistoryPanel(wx.Panel): - - def __init__(self, parent,flt_empty=True, - flt_doc=True,flt_cmd=True,flt_magic=True): - - wx.Panel.__init__(self,parent,-1) - #text_ctrl = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE) - text_ctrl = PythonSTC(self, -1) - - - st_filt = wx.StaticText(self, -1, " Filter:") - - self.filter_empty = wx.CheckBox(self, -1, "Empty commands") - self.filter_doc = wx.CheckBox(self, -1, "?: Doc commands") - self.filter_cmd = wx.CheckBox(self, -1, "!: Sys commands") - self.filter_magic = wx.CheckBox(self, -1, "%: Magic keys") - - self.options={'filter_empty':{'value':'True', - 'checkbox':self.filter_empty, \ - 'True':True,'False':False, - 'setfunc':lambda x:None}, - 'filter_doc':{'value':'True', - 'checkbox':self.filter_doc, \ - 'True':True,'False':False, - 'setfunc':lambda x:None}, - 'filter_cmd':{'value':'True', - 'checkbox':self.filter_cmd, \ - 'True':True,'False':False, - 'setfunc':lambda x:None}, - 'filter_magic':{'value':'True', - 'checkbox':self.filter_magic, \ - 'True':True,'False':False, - 'setfunc':lambda x:None}, - } - self.reloadOptions(self.options) - - self.filter_empty.Bind(wx.EVT_CHECKBOX, self.evtCheckEmptyFilter) - self.filter_doc.Bind(wx.EVT_CHECKBOX, self.evtCheckDocFilter) - self.filter_cmd.Bind(wx.EVT_CHECKBOX, self.evtCheckCmdFilter) - self.filter_magic.Bind(wx.EVT_CHECKBOX, self.evtCheckMagicFilter) - - #self.filter_empty.SetValue(flt_empty) - #self.filter_doc.SetValue(flt_doc) - #self.filter_cmd.SetValue(flt_cmd) - #self.filter_magic.SetValue(flt_magic) - - sizer = wx.BoxSizer(wx.VERTICAL) - - sizer.Add(text_ctrl, 1, wx.EXPAND) - sizer.AddMany( [(5,5), - st_filt, - (10,10), - self.filter_empty, - self.filter_doc, - self.filter_cmd, - self.filter_magic, - (10,10), - ]) - self.SetAutoLayout(True) - sizer.Fit(self) - sizer.SetSizeHints(self) - self.SetSizer(sizer) - self.text_ctrl=text_ctrl - #text_ctrl.SetText(demoText + open('Main.py').read()) - text_ctrl.EmptyUndoBuffer() - text_ctrl.Colourise(0, -1) - - # line numbers in the margin - text_ctrl.SetMarginType(1, stc.STC_MARGIN_NUMBER) - text_ctrl.SetMarginWidth(1, 15) - - - def write(self,history_line): - add = True - if self.filter_empty.GetValue() == True and history_line == '': - add = False - if len(history_line)>0: - if self.filter_doc.GetValue() == True and history_line[-1:] == '?': - add = False - if self.filter_cmd.GetValue() == True and history_line[0] == '!': - add = False - if self.filter_magic.GetValue() == True and history_line[0] == '%': - add = False - if add: - self.text_ctrl.AppendText(history_line+'\n') - -#------------------------ Option Section ----------------------------------- - def processOptionCheckedEvt(self, event, name): - if event.IsChecked(): - self.options[name]['value']='True' - else: - self.options[name]['value']='False' - self.updateOptionTracker(name, - self.options[name]['value']) - - def evtCheckEmptyFilter(self, event): - self.processOptionCheckedEvt(event, 'filter_empty') - - def evtCheckDocFilter(self, event): - self.processOptionCheckedEvt(event, 'filter_doc') - - def evtCheckCmdFilter(self, event): - self.processOptionCheckedEvt(event, 'filter_cmd') - - def evtCheckMagicFilter(self, event): - self.processOptionCheckedEvt(event, 'filter_magic') - - def getOptions(self): - return self.options - - def reloadOptions(self,options): - self.options = options - for key in self.options.keys(): - value = self.options[key]['value'] - self.options[key]['checkbox'].SetValue(self.options[key][value]) - self.options[key]['setfunc'](value) - -#------------------------ Hook Section ----------------------------------- - def updateOptionTracker(self,name,value): - ''' - Default history tracker (does nothing) - ''' - pass - - def setOptionTrackerHook(self,func): - ''' - Define a new history tracker - ''' - self.updateOptionTracker = func - - -#---------------------------------------------------------------------- -# Font definition for Styled Text Control - -if wx.Platform == '__WXMSW__': - faces = { 'times': 'Times New Roman', - 'mono' : 'Courier New', - 'helv' : 'Arial', - 'other': 'Comic Sans MS', - 'size' : 8, - 'size2': 6, - } -elif wx.Platform == '__WXMAC__': - faces = { 'times': 'Times New Roman', - 'mono' : 'Monaco', - 'helv' : 'Arial', - 'other': 'Comic Sans MS', - 'size' : 8, - 'size2': 6, - } -else: - faces = { 'times': 'Times', - 'mono' : 'Courier', - 'helv' : 'Helvetica', - 'other': 'new century schoolbook', - 'size' : 8, - 'size2': 6, - } - - -#---------------------------------------------------------------------- - -class PythonSTC(stc.StyledTextCtrl): - - fold_symbols = 3 - - def __init__(self, parent, ID, - pos=wx.DefaultPosition, size=wx.DefaultSize, - style=0): - stc.StyledTextCtrl.__init__(self, parent, ID, pos, size, style) - #self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN) - #self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT) - - self.SetLexer(stc.STC_LEX_PYTHON) - self.SetKeyWords(0, " ".join(keyword.kwlist)) - - #self.SetProperty("fold", "1") - #self.SetProperty("tab.timmy.whinge.level", "1") - #self.SetMargins(0,0) - - #self.SetViewWhiteSpace(False) - #self.SetBufferedDraw(False) - #self.SetViewEOL(True) - self.SetEOLMode(stc.STC_EOL_CRLF) - #self.SetUseAntiAliasing(True) - - self.SetEdgeMode(stc.STC_EDGE_LINE) - self.SetEdgeColumn(80) - self.SetEdgeColour(wx.LIGHT_GREY) - self.SetLayoutCache(stc.STC_CACHE_PAGE) - - # Setup a margin to hold fold markers - #self.SetFoldFlags(16) - ### WHAT IS THIS VALUE? WHAT ARE THE OTHER FLAGS? DOES IT MATTER? - self.SetMarginType(2, stc.STC_MARGIN_SYMBOL) - self.SetMarginMask(2, stc.STC_MASK_FOLDERS) - self.SetMarginSensitive(2, True) - self.SetMarginWidth(2, 12) - - if self.fold_symbols == 0: - # Arrow pointing right for contracted folders, - # arrow pointing down for expanded - self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, \ - stc.STC_MARK_ARROWDOWN, "black", "black") - self.MarkerDefine(stc.STC_MARKNUM_FOLDER, \ - stc.STC_MARK_ARROW, "black", "black") - self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, \ - stc.STC_MARK_EMPTY, "black", "black") - self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, \ - stc.STC_MARK_EMPTY, "black", "black") - self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, \ - stc.STC_MARK_EMPTY, "white", "black") - self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, \ - stc.STC_MARK_EMPTY, "white", "black") - self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, \ - stc.STC_MARK_EMPTY, "white", "black") - - elif self.fold_symbols == 1: - # Plus for contracted folders, minus for expanded - self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, \ - stc.STC_MARK_MINUS, "white", "black") - self.MarkerDefine(stc.STC_MARKNUM_FOLDER, \ - stc.STC_MARK_PLUS, "white", "black") - self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, \ - stc.STC_MARK_EMPTY, "white", "black") - self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, \ - stc.STC_MARK_EMPTY, "white", "black") - self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, \ - stc.STC_MARK_EMPTY, "white", "black") - self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, \ - stc.STC_MARK_EMPTY, "white", "black") - self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, \ - stc.STC_MARK_EMPTY, "white", "black") - - elif self.fold_symbols == 2: - # Like a flattened tree control using circular headers and curved joins - self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, \ - stc.STC_MARK_CIRCLEMINUS, "white", "#404040") - self.MarkerDefine(stc.STC_MARKNUM_FOLDER, \ - stc.STC_MARK_CIRCLEPLUS, "white", "#404040") - self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, \ - stc.STC_MARK_VLINE, "white", "#404040") - self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, \ - stc.STC_MARK_LCORNERCURVE, "white", "#404040") - self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, \ - stc.STC_MARK_CIRCLEPLUSCONNECTED, "white", "#404040") - self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, \ - stc.STC_MARK_CIRCLEMINUSCONNECTED, "white", "#404040") - self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, \ - stc.STC_MARK_TCORNERCURVE, "white", "#404040") - - elif self.fold_symbols == 3: - # Like a flattened tree control using square headers - self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, \ - stc.STC_MARK_BOXMINUS, "white", "#808080") - self.MarkerDefine(stc.STC_MARKNUM_FOLDER, \ - stc.STC_MARK_BOXPLUS, "white", "#808080") - self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, \ - stc.STC_MARK_VLINE, "white", "#808080") - self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, \ - stc.STC_MARK_LCORNER, "white", "#808080") - self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, \ - stc.STC_MARK_BOXPLUSCONNECTED, "white", "#808080") - self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, \ - stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080") - self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, \ - stc.STC_MARK_TCORNER, "white", "#808080") - - - self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI) - self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick) - self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed) - - # Make some styles, The lexer defines what each style is used for, we - # just have to define what each style looks like. This set is adapted from - # Scintilla sample property files. - - # Global default styles for all languages - self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % faces) - self.StyleClearAll() # Reset all to be like the default - - # Global default styles for all languages - self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % faces) - self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(helv)s,size:%(size2)d" % faces) - self.StyleSetSpec(stc.STC_STYLE_CONTROLCHAR, "face:%(other)s" % faces) - self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, "fore:#FFFFFF,back:#0000FF,bold") - self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold") - - # Python styles - # Default - self.StyleSetSpec(stc.STC_P_DEFAULT, "fore:#000000,face:%(helv)s,size:%(size)d" % faces) - # Comments - self.StyleSetSpec(stc.STC_P_COMMENTLINE, "fore:#007F00,face:%(other)s,size:%(size)d" % faces) - # Number - self.StyleSetSpec(stc.STC_P_NUMBER, "fore:#007F7F,size:%(size)d" % faces) - # String - self.StyleSetSpec(stc.STC_P_STRING, "fore:#7F007F,face:%(helv)s,size:%(size)d" % faces) - # Single quoted string - self.StyleSetSpec(stc.STC_P_CHARACTER, "fore:#7F007F,face:%(helv)s,size:%(size)d" % faces) - # Keyword - self.StyleSetSpec(stc.STC_P_WORD, "fore:#00007F,bold,size:%(size)d" % faces) - # Triple quotes - self.StyleSetSpec(stc.STC_P_TRIPLE, "fore:#7F0000,size:%(size)d" % faces) - # Triple double quotes - self.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE, "fore:#7F0000,size:%(size)d" % faces) - # Class name definition - self.StyleSetSpec(stc.STC_P_CLASSNAME, "fore:#0000FF,bold,underline,size:%(size)d" % faces) - # Function or method name definition - self.StyleSetSpec(stc.STC_P_DEFNAME, "fore:#007F7F,bold,size:%(size)d" % faces) - # Operators - self.StyleSetSpec(stc.STC_P_OPERATOR, "bold,size:%(size)d" % faces) - # Identifiers - self.StyleSetSpec(stc.STC_P_IDENTIFIER, "fore:#000000,face:%(helv)s,size:%(size)d" % faces) - # Comment-blocks - self.StyleSetSpec(stc.STC_P_COMMENTBLOCK, "fore:#7F7F7F,size:%(size)d" % faces) - # End of line where string is not closed - self.StyleSetSpec(stc.STC_P_STRINGEOL, "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % faces) - - self.SetCaretForeground("BLUE") - - - # register some images for use in the AutoComplete box. - #self.RegisterImage(1, images.getSmilesBitmap()) - #self.RegisterImage(2, - # wx.ArtProvider.GetBitmap(wx.ART_NEW, size=(16,16))) - #self.RegisterImage(3, - # wx.ArtProvider.GetBitmap(wx.ART_COPY, size=(16,16))) - - - def OnKeyPressed(self, event): - if self.CallTipActive(): - self.CallTipCancel() - key = event.GetKeyCode() - - if key == 32 and event.ControlDown(): - pos = self.GetCurrentPos() - - # Tips - if event.ShiftDown(): - self.CallTipSetBackground("yellow") - self.CallTipShow(pos, 'lots of of text: blah, blah, blah\n\n' - 'show some suff, maybe parameters..\n\n' - 'fubar(param1, param2)') - # Code completion - else: - #lst = [] - #for x in range(50000): - # lst.append('%05d' % x) - #st = " ".join(lst) - #print len(st) - #self.AutoCompShow(0, st) - - kw = keyword.kwlist[:] - - kw.sort() # Python sorts are case sensitive - self.AutoCompSetIgnoreCase(False) # so this needs to match - - # Images are specified with a appended "?type" - for i in range(len(kw)): - if kw[i] in keyword.kwlist: - kw[i] = kw[i]# + "?1" - - self.AutoCompShow(0, " ".join(kw)) - else: - event.Skip() - - - def OnUpdateUI(self, evt): - # check for matching braces - braceAtCaret = -1 - braceOpposite = -1 - charBefore = None - caretPos = self.GetCurrentPos() - - if caretPos > 0: - charBefore = self.GetCharAt(caretPos - 1) - styleBefore = self.GetStyleAt(caretPos - 1) - - # check before - if charBefore and chr(charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR: - braceAtCaret = caretPos - 1 - - # check after - if braceAtCaret < 0: - charAfter = self.GetCharAt(caretPos) - styleAfter = self.GetStyleAt(caretPos) - - if charAfter and chr(charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR: - braceAtCaret = caretPos - - if braceAtCaret >= 0: - braceOpposite = self.BraceMatch(braceAtCaret) - - if braceAtCaret != -1 and braceOpposite == -1: - self.BraceBadLight(braceAtCaret) - else: - self.BraceHighlight(braceAtCaret, braceOpposite) - #pt = self.PointFromPosition(braceOpposite) - #self.Refresh(True, wxRect(pt.x, pt.y, 5,5)) - #print pt - #self.Refresh(False) - - - def OnMarginClick(self, evt): - # fold and unfold as needed - if evt.GetMargin() == 2: - if evt.GetShift() and evt.GetControl(): - self.FoldAll() - else: - lineClicked = self.LineFromPosition(evt.GetPosition()) - - if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG: - if evt.GetShift(): - self.SetFoldExpanded(lineClicked, True) - self.Expand(lineClicked, True, True, 1) - elif evt.GetControl(): - if self.GetFoldExpanded(lineClicked): - self.SetFoldExpanded(lineClicked, False) - self.Expand(lineClicked, False, True, 0) - else: - self.SetFoldExpanded(lineClicked, True) - self.Expand(lineClicked, True, True, 100) - else: - self.ToggleFold(lineClicked) - - - def FoldAll(self): - lineCount = self.GetLineCount() - expanding = True - - # find out if we are folding or unfolding - for lineNum in range(lineCount): - if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG: - expanding = not self.GetFoldExpanded(lineNum) - break - - lineNum = 0 - - while lineNum < lineCount: - level = self.GetFoldLevel(lineNum) - if level & stc.STC_FOLDLEVELHEADERFLAG and \ - (level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE: - - if expanding: - self.SetFoldExpanded(lineNum, True) - lineNum = self.Expand(lineNum, True) - lineNum = lineNum - 1 - else: - lastChild = self.GetLastChild(lineNum, -1) - self.SetFoldExpanded(lineNum, False) - - if lastChild > lineNum: - self.HideLines(lineNum+1, lastChild) - - lineNum = lineNum + 1 - - - - def Expand(self, line, doExpand, force=False, visLevels=0, level=-1): - lastChild = self.GetLastChild(line, level) - line = line + 1 - - while line <= lastChild: - if force: - if visLevels > 0: - self.ShowLines(line, line) - else: - self.HideLines(line, line) - else: - if doExpand: - self.ShowLines(line, line) - - if level == -1: - level = self.GetFoldLevel(line) - - if level & stc.STC_FOLDLEVELHEADERFLAG: - if force: - if visLevels > 1: - self.SetFoldExpanded(line, True) - else: - self.SetFoldExpanded(line, False) - - line = self.Expand(line, doExpand, force, visLevels-1) - - else: - if doExpand and self.GetFoldExpanded(line): - line = self.Expand(line, True, force, visLevels-1) - else: - line = self.Expand(line, False, force, visLevels-1) - else: - line = line + 1 - - return line - - -#---------------------------------------------------------------------- diff --git a/IPython/deathrow/gui/wx/ipython_view.py b/IPython/deathrow/gui/wx/ipython_view.py deleted file mode 100644 index f1a234a..0000000 --- a/IPython/deathrow/gui/wx/ipython_view.py +++ /dev/null @@ -1,942 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -''' -Provides IPython WX console widgets. - -@author: Laurent Dufrechou -laurent.dufrechou _at_ gmail.com -This WX widget is based on the original work of Eitan Isaacson -that provided the console for the GTK toolkit. - -Original work from: -@author: Eitan Isaacson -@organization: IBM Corporation -@copyright: Copyright (c) 2007 IBM Corporation -@license: BSD - -All rights reserved. This program and the accompanying materials are made -available under the terms of the BSD which accompanies this distribution, and -is available at U{http://www.opensource.org/licenses/bsd-license.php} -''' - -__version__ = 0.9 -__author__ = "Laurent Dufrechou" -__email__ = "laurent.dufrechou _at_ gmail.com" -__license__ = "BSD" - -import wx -import wx.stc as stc - -import re -from StringIO import StringIO - -import sys -import codecs -import locale -import time - -for enc in (locale.getpreferredencoding(), - sys.getfilesystemencoding(), - sys.getdefaultencoding()): - try: - codecs.lookup(enc) - ENCODING = enc - break - except LookupError: - pass -else: - ENCODING = 'utf-8' - -from ipshell_nonblocking import NonBlockingIPShell - -class WxNonBlockingIPShell(NonBlockingIPShell): - ''' - An NonBlockingIPShell Thread that is WX dependent. - ''' - def __init__(self, parent, - argv=[],user_ns={},user_global_ns=None, - cin=None, cout=None, cerr=None, - ask_exit_handler=None): - - NonBlockingIPShell.__init__(self, argv, user_ns, user_global_ns, - cin, cout, cerr, - ask_exit_handler) - - self.parent = parent - - self.ask_exit_callback = ask_exit_handler - self._IP.exit = self._ask_exit - - def addGUIShortcut(self, text, func): - wx.CallAfter(self.parent.add_button_handler, - button_info={ 'text':text, - 'func':self.parent.doExecuteLine(func)}) - - def _raw_input(self, prompt=''): - """ A replacement from python's raw_input. - """ - self.answer = None - if(self._threading == True): - wx.CallAfter(self._yesNoBox, prompt) - while self.answer is None: - time.sleep(.1) - else: - self._yesNoBox(prompt) - return self.answer - - def _yesNoBox(self, prompt): - """ yes/no box managed with wx.CallAfter jsut in case caler is executed in a thread""" - dlg = wx.TextEntryDialog( - self.parent, prompt, - 'Input requested', 'Python') - dlg.SetValue("") - - answer = '' - if dlg.ShowModal() == wx.ID_OK: - answer = dlg.GetValue() - - dlg.Destroy() - self.answer = answer - - def _ask_exit(self): - wx.CallAfter(self.ask_exit_callback, ()) - - def _after_execute(self): - wx.CallAfter(self.parent.evtStateExecuteDone, ()) - - -class WxConsoleView(stc.StyledTextCtrl): - ''' - Specialized styled text control view for console-like workflow. - We use here a scintilla frontend thus it can be reused in any GUI that - supports scintilla with less work. - - @cvar ANSI_COLORS_BLACK: Mapping of terminal colors to X11 names. - (with Black background) - @type ANSI_COLORS_BLACK: dictionary - - @cvar ANSI_COLORS_WHITE: Mapping of terminal colors to X11 names. - (with White background) - @type ANSI_COLORS_WHITE: dictionary - - @ivar color_pat: Regex of terminal color pattern - @type color_pat: _sre.SRE_Pattern - ''' - ANSI_STYLES_BLACK = {'0;30': [0, 'WHITE'], '0;31': [1, 'RED'], - '0;32': [2, 'GREEN'], '0;33': [3, 'BROWN'], - '0;34': [4, 'BLUE'], '0;35': [5, 'PURPLE'], - '0;36': [6, 'CYAN'], '0;37': [7, 'LIGHT GREY'], - '1;30': [8, 'DARK GREY'], '1;31': [9, 'RED'], - '1;32': [10, 'SEA GREEN'], '1;33': [11, 'YELLOW'], - '1;34': [12, 'LIGHT BLUE'], '1;35': - [13, 'MEDIUM VIOLET RED'], - '1;36': [14, 'LIGHT STEEL BLUE'], '1;37': [15, 'YELLOW']} - - ANSI_STYLES_WHITE = {'0;30': [0, 'BLACK'], '0;31': [1, 'RED'], - '0;32': [2, 'GREEN'], '0;33': [3, 'BROWN'], - '0;34': [4, 'BLUE'], '0;35': [5, 'PURPLE'], - '0;36': [6, 'CYAN'], '0;37': [7, 'LIGHT GREY'], - '1;30': [8, 'DARK GREY'], '1;31': [9, 'RED'], - '1;32': [10, 'SEA GREEN'], '1;33': [11, 'YELLOW'], - '1;34': [12, 'LIGHT BLUE'], '1;35': - [13, 'MEDIUM VIOLET RED'], - '1;36': [14, 'LIGHT STEEL BLUE'], '1;37': [15, 'YELLOW']} - - def __init__(self, parent, prompt, intro="", background_color="BLACK", - pos=wx.DefaultPosition, ID = -1, size=wx.DefaultSize, - style=0, autocomplete_mode = 'IPYTHON'): - ''' - Initialize console view. - - @param parent: Parent widget - @param prompt: User specified prompt - @type intro: string - @param intro: User specified startup introduction string - @type intro: string - @param background_color: Can be BLACK or WHITE - @type background_color: string - @param other: init param of styledTextControl (can be used as-is) - @param autocomplete_mode: Can be 'IPYTHON' or 'STC' - 'IPYTHON' show autocompletion the ipython way - 'STC" show it scintilla text control way - ''' - stc.StyledTextCtrl.__init__(self, parent, ID, pos, size, style) - - ####### Scintilla configuration ################################### - - # Ctrl + B or Ctrl + N can be used to zoomin/zoomout the text inside - # the widget - self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN) - self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT) - - #We draw a line at position 80 - self.SetEdgeMode(stc.STC_EDGE_LINE) - self.SetEdgeColumn(80) - self.SetEdgeColour(wx.LIGHT_GREY) - - #self.SetViewWhiteSpace(True) - #self.SetViewEOL(True) - self.SetEOLMode(stc.STC_EOL_CRLF) - #self.SetWrapMode(stc.STC_WRAP_CHAR) - #self.SetWrapMode(stc.STC_WRAP_WORD) - self.SetBufferedDraw(True) - #self.SetUseAntiAliasing(True) - self.SetLayoutCache(stc.STC_CACHE_PAGE) - self.SetUndoCollection(False) - self.SetUseTabs(True) - self.SetIndent(4) - self.SetTabWidth(4) - - self.EnsureCaretVisible() - - self.SetMargins(3, 3) #text is moved away from border with 3px - # Suppressing Scintilla margins - self.SetMarginWidth(0, 0) - self.SetMarginWidth(1, 0) - self.SetMarginWidth(2, 0) - - self.background_color = background_color - self.buildStyles() - - self.indent = 0 - self.prompt_count = 0 - self.color_pat = re.compile('\x01?\x1b\[(.*?)m\x02?') - - self.write(intro) - self.setPrompt(prompt) - self.showPrompt() - - self.autocomplete_mode = autocomplete_mode - - self.Bind(wx.EVT_KEY_DOWN, self._onKeypress) - - def buildStyles(self): - #we define platform specific fonts - if wx.Platform == '__WXMSW__': - faces = { 'times': 'Times New Roman', - 'mono' : 'Courier New', - 'helv' : 'Arial', - 'other': 'Comic Sans MS', - 'size' : 10, - 'size2': 8, - } - elif wx.Platform == '__WXMAC__': - faces = { 'times': 'Times New Roman', - 'mono' : 'Monaco', - 'helv' : 'Arial', - 'other': 'Comic Sans MS', - 'size' : 10, - 'size2': 8, - } - else: - faces = { 'times': 'Times', - 'mono' : 'Courier', - 'helv' : 'Helvetica', - 'other': 'new century schoolbook', - 'size' : 10, - 'size2': 8, - } - - # make some styles - if self.background_color != "BLACK": - self.background_color = "WHITE" - self.SetCaretForeground("BLACK") - self.ANSI_STYLES = self.ANSI_STYLES_WHITE - else: - self.SetCaretForeground("WHITE") - self.ANSI_STYLES = self.ANSI_STYLES_BLACK - - self.StyleSetSpec(stc.STC_STYLE_DEFAULT, - "fore:%s,back:%s,size:%d,face:%s" - % (self.ANSI_STYLES['0;30'][1], - self.background_color, - faces['size'], faces['mono'])) - self.StyleClearAll() - self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, - "fore:#FF0000,back:#0000FF,bold") - self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, - "fore:#000000,back:#FF0000,bold") - - for style in self.ANSI_STYLES.values(): - self.StyleSetSpec(style[0], "bold,fore:%s" % style[1]) - - ####################################################################### - - def setBackgroundColor(self, color): - self.background_color = color - self.buildStyles() - - def getBackgroundColor(self, color): - return self.background_color - - def asyncWrite(self, text): - ''' - Write given text to buffer in an asynchroneous way. - It is used from another thread to be able to acces the GUI. - @param text: Text to append - @type text: string - ''' - try: - wx.MutexGuiEnter() - - #be sure not to be interrutpted before the MutexGuiLeave! - self.write(text) - - except KeyboardInterrupt: - wx.MutexGuiLeave() - raise KeyboardInterrupt - wx.MutexGuiLeave() - - - def write(self, text): - ''' - Write given text to buffer. - - @param text: Text to append. - @type text: string - ''' - segments = self.color_pat.split(text) - segment = segments.pop(0) - self.StartStyling(self.getCurrentLineEnd(), 0xFF) - self.AppendText(segment) - - if segments: - ansi_tags = self.color_pat.findall(text) - - for tag in ansi_tags: - i = segments.index(tag) - self.StartStyling(self.getCurrentLineEnd(), 0xFF) - self.AppendText(segments[i+1]) - - if tag != '0': - self.SetStyling(len(segments[i+1]), self.ANSI_STYLES[tag][0]) - - segments.pop(i) - - self.moveCursor(self.getCurrentLineEnd()) - - def getPromptLen(self): - ''' - Return the length of current prompt - ''' - return len(str(self.prompt_count)) + 7 - - def setPrompt(self, prompt): - self.prompt = prompt - - def setIndentation(self, indentation): - self.indent = indentation - - def setPromptCount(self, count): - self.prompt_count = count - - def showPrompt(self): - ''' - Prints prompt at start of line. - - @param prompt: Prompt to print. - @type prompt: string - ''' - self.write(self.prompt) - #now we update the position of end of prompt - self.current_start = self.getCurrentLineEnd() - - autoindent = self.indent*' ' - autoindent = autoindent.replace(' ','\t') - self.write(autoindent) - - def changeLine(self, text): - ''' - Replace currently entered command line with given text. - - @param text: Text to use as replacement. - @type text: string - ''' - self.SetSelection(self.getCurrentPromptStart(), self.getCurrentLineEnd()) - self.ReplaceSelection(text) - self.moveCursor(self.getCurrentLineEnd()) - - def getCurrentPromptStart(self): - return self.current_start - - def getCurrentLineStart(self): - return self.GotoLine(self.LineFromPosition(self.GetCurrentPos())) - - def getCurrentLineEnd(self): - return self.GetLength() - - def getCurrentLine(self): - ''' - Get text in current command line. - - @return: Text of current command line. - @rtype: string - ''' - return self.GetTextRange(self.getCurrentPromptStart(), - self.getCurrentLineEnd()) - - def moveCursorOnNewValidKey(self): - #If cursor is at wrong position put it at last line... - if self.GetCurrentPos() < self.getCurrentPromptStart(): - self.GotoPos(self.getCurrentPromptStart()) - - def removeFromTo(self, from_pos, to_pos): - if from_pos < to_pos: - self.SetSelection(from_pos, to_pos) - self.DeleteBack() - - def removeCurrentLine(self): - self.LineDelete() - - def moveCursor(self, position): - self.GotoPos(position) - - def getCursorPos(self): - return self.GetCurrentPos() - - def selectFromTo(self, from_pos, to_pos): - self.SetSelectionStart(from_pos) - self.SetSelectionEnd(to_pos) - - def writeHistory(self, history): - self.removeFromTo(self.getCurrentPromptStart(), self.getCurrentLineEnd()) - self.changeLine(history) - - def setCompletionMethod(self, completion): - if completion in ['IPYTHON', 'STC']: - self.autocomplete_mode = completion - else: - raise AttributeError - - def getCompletionMethod(self, completion): - return self.autocomplete_mode - - def writeCompletion(self, possibilities): - if self.autocomplete_mode == 'IPYTHON': - max_len = len(max(possibilities, key=len)) - max_symbol = ' '*max_len - - #now we check how much symbol we can put on a line... - test_buffer = max_symbol + ' '*4 - - allowed_symbols = 80/len(test_buffer) - if allowed_symbols == 0: - allowed_symbols = 1 - - pos = 1 - buf = '' - for symbol in possibilities: - #buf += symbol+'\n'#*spaces) - if pos < allowed_symbols: - spaces = max_len - len(symbol) + 4 - buf += symbol+' '*spaces - pos += 1 - else: - buf += symbol+'\n' - pos = 1 - self.write(buf) - else: - possibilities.sort() # Python sorts are case sensitive - self.AutoCompSetIgnoreCase(False) - self.AutoCompSetAutoHide(False) - #let compute the length ot last word - splitter = [' ', '(', '[', '{','='] - last_word = self.getCurrentLine() - for breaker in splitter: - last_word = last_word.split(breaker)[-1] - self.AutoCompShow(len(last_word), " ".join(possibilities)) - - def _onKeypress(self, event, skip=True): - ''' - Key press callback used for correcting behavior for console-like - interfaces. For example 'home' should go to prompt, not to begining of - line. - - @param widget: Widget that key press accored in. - @type widget: gtk.Widget - @param event: Event object - @type event: gtk.gdk.Event - - @return: Return True if event as been catched. - @rtype: boolean - ''' - if not self.AutoCompActive(): - if event.GetKeyCode() == wx.WXK_HOME: - if event.Modifiers == wx.MOD_NONE: - self.moveCursorOnNewValidKey() - self.moveCursor(self.getCurrentPromptStart()) - return True - elif event.Modifiers == wx.MOD_SHIFT: - self.moveCursorOnNewValidKey() - self.selectFromTo(self.getCurrentPromptStart(), self.getCursorPos()) - return True - else: - return False - - elif event.GetKeyCode() == wx.WXK_LEFT: - if event.Modifiers == wx.MOD_NONE: - self.moveCursorOnNewValidKey() - - self.moveCursor(self.getCursorPos()-1) - if self.getCursorPos() < self.getCurrentPromptStart(): - self.moveCursor(self.getCurrentPromptStart()) - return True - - elif event.GetKeyCode() == wx.WXK_BACK: - self.moveCursorOnNewValidKey() - if self.getCursorPos() > self.getCurrentPromptStart(): - event.Skip() - return True - - if skip: - if event.GetKeyCode() not in [wx.WXK_PAGEUP, wx.WXK_PAGEDOWN]\ - and event.Modifiers == wx.MOD_NONE: - self.moveCursorOnNewValidKey() - - event.Skip() - return True - return False - else: - event.Skip() - - def OnUpdateUI(self, evt): - # check for matching braces - braceAtCaret = -1 - braceOpposite = -1 - charBefore = None - caretPos = self.GetCurrentPos() - - if caretPos > 0: - charBefore = self.GetCharAt(caretPos - 1) - styleBefore = self.GetStyleAt(caretPos - 1) - - # check before - if charBefore and chr(charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR: - braceAtCaret = caretPos - 1 - - # check after - if braceAtCaret < 0: - charAfter = self.GetCharAt(caretPos) - styleAfter = self.GetStyleAt(caretPos) - - if charAfter and chr(charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR: - braceAtCaret = caretPos - - if braceAtCaret >= 0: - braceOpposite = self.BraceMatch(braceAtCaret) - - if braceAtCaret != -1 and braceOpposite == -1: - self.BraceBadLight(braceAtCaret) - else: - self.BraceHighlight(braceAtCaret, braceOpposite) - #pt = self.PointFromPosition(braceOpposite) - #self.Refresh(True, wxRect(pt.x, pt.y, 5,5)) - #print pt - #self.Refresh(False) - -class IPShellWidget(wx.Panel): - ''' - This is wx.Panel that embbed the IPython Thread and the wx.StyledTextControl - If you want to port this to any other GUI toolkit, just replace the - WxConsoleView by YOURGUIConsoleView and make YOURGUIIPythonView derivate - from whatever container you want. I've choosed to derivate from a wx.Panel - because it seems to be more useful - Any idea to make it more 'generic' welcomed. - ''' - - def __init__(self, parent, intro=None, - background_color="BLACK", add_button_handler=None, - wx_ip_shell=None, user_ns={},user_global_ns=None, - ): - ''' - Initialize. - Instanciate an IPython thread. - Instanciate a WxConsoleView. - Redirect I/O to console. - ''' - wx.Panel.__init__(self,parent,wx.ID_ANY) - - self.parent = parent - ### IPython non blocking shell instanciation ### - self.cout = StringIO() - self.add_button_handler = add_button_handler - - if wx_ip_shell is not None: - self.IP = wx_ip_shell - else: - self.IP = WxNonBlockingIPShell(self, - cout = self.cout, cerr = self.cout, - ask_exit_handler = self.askExitCallback) - - ### IPython wx console view instanciation ### - #If user didn't defined an intro text, we create one for him - #If you really wnat an empty intro just call wxIPythonViewPanel - #with intro='' - if intro is None: - welcome_text = "Welcome to WxIPython Shell.\n\n" - welcome_text+= self.IP.get_banner() - welcome_text+= "!command -> Execute command in shell\n" - welcome_text+= "TAB -> Autocompletion\n" - else: - welcome_text = intro - - self.text_ctrl = WxConsoleView(self, - self.IP.get_prompt(), - intro=welcome_text, - background_color=background_color) - - option_text = wx.StaticText(self, -1, "Options:") - self.completion_option = wx.CheckBox(self, -1, "Scintilla Completion") - self.completion_option.SetToolTip(wx.ToolTip( - "Selects the completion type:\nEither Ipython default style or Scintilla one")) - #self.completion_option.SetValue(False) - self.background_option = wx.CheckBox(self, -1, "White Background") - self.background_option.SetToolTip(wx.ToolTip( - "Selects the back ground color: BLACK or WHITE")) - #self.background_option.SetValue(False) - self.threading_option = wx.CheckBox(self, -1, "Execute in thread") - self.threading_option.SetToolTip(wx.ToolTip( - "Use threading: infinite loop don't freeze the GUI and commands can be breaked\nNo threading: maximum compatibility")) - #self.threading_option.SetValue(False) - - self.options={'completion':{'value':'IPYTHON', - 'checkbox':self.completion_option,'STC':True,'IPYTHON':False, - 'setfunc':self.text_ctrl.setCompletionMethod}, - 'background_color':{'value':'BLACK', - 'checkbox':self.background_option,'WHITE':True,'BLACK':False, - 'setfunc':self.text_ctrl.setBackgroundColor}, - 'threading':{'value':'True', - 'checkbox':self.threading_option,'True':True,'False':False, - 'setfunc':self.IP.set_threading}, - } - - #self.cout.write dEfault option is asynchroneous because default sate is threading ON - self.cout.write = self.text_ctrl.asyncWrite - #we reloard options - self.reloadOptions(self.options) - - self.text_ctrl.Bind(wx.EVT_KEY_DOWN, self.keyPress) - self.completion_option.Bind(wx.EVT_CHECKBOX, self.evtCheckOptionCompletion) - self.background_option.Bind(wx.EVT_CHECKBOX, self.evtCheckOptionBackgroundColor) - self.threading_option.Bind(wx.EVT_CHECKBOX, self.evtCheckOptionThreading) - - ### making the layout of the panel ### - sizer = wx.BoxSizer(wx.VERTICAL) - sizer.Add(self.text_ctrl, 1, wx.EXPAND) - option_sizer = wx.BoxSizer(wx.HORIZONTAL) - sizer.Add(option_sizer, 0) - option_sizer.AddMany([(10, 20), - (option_text, 0, wx.ALIGN_CENTER_VERTICAL), - (5, 5), - (self.completion_option, 0, wx.ALIGN_CENTER_VERTICAL), - (8, 8), - (self.background_option, 0, wx.ALIGN_CENTER_VERTICAL), - (8, 8), - (self.threading_option, 0, wx.ALIGN_CENTER_VERTICAL) - ]) - self.SetAutoLayout(True) - sizer.Fit(self) - sizer.SetSizeHints(self) - self.SetSizer(sizer) - #and we focus on the widget :) - self.SetFocus() - - #widget state management (for key handling different cases) - self.setCurrentState('IDLE') - self.pager_state = 'DONE' - self.raw_input_current_line = 0 - - def askExitCallback(self, event): - self.askExitHandler(event) - - #---------------------- IPython Thread Management ------------------------ - def stateDoExecuteLine(self): - lines=self.text_ctrl.getCurrentLine() - self.text_ctrl.write('\n') - lines_to_execute = lines.replace('\t',' '*4) - lines_to_execute = lines_to_execute.replace('\r','') - self.IP.do_execute(lines_to_execute.encode(ENCODING)) - self.updateHistoryTracker(lines) - if(self.text_ctrl.getCursorPos()!=0): - self.text_ctrl.removeCurrentLine() - self.setCurrentState('WAIT_END_OF_EXECUTION') - - def evtStateExecuteDone(self,evt): - self.doc = self.IP.get_doc_text() - self.help = self.IP.get_help_text() - if self.doc: - self.pager_lines = self.doc[7:].split('\n') - self.pager_state = 'INIT' - self.setCurrentState('SHOW_DOC') - self.pager(self.doc) - elif self.help: - self.pager_lines = self.help.split('\n') - self.pager_state = 'INIT' - self.setCurrentState('SHOW_DOC') - self.pager(self.help) - else: - if(self.text_ctrl.getCursorPos()!=0): - self.text_ctrl.removeCurrentLine() - self.stateShowPrompt() - - def stateShowPrompt(self): - self.setCurrentState('SHOW_PROMPT') - self.text_ctrl.setPrompt(self.IP.get_prompt()) - self.text_ctrl.setIndentation(self.IP.get_indentation()) - self.text_ctrl.setPromptCount(self.IP.get_prompt_count()) - self.text_ctrl.showPrompt() - self.IP.init_history_index() - self.setCurrentState('IDLE') - - def setCurrentState(self, state): - self.cur_state = state - self.updateStatusTracker(self.cur_state) - - def pager(self,text): - - if self.pager_state == 'INIT': - #print >>sys.__stdout__,"PAGER state:",self.pager_state - self.pager_nb_lines = len(self.pager_lines) - self.pager_index = 0 - self.pager_do_remove = False - self.text_ctrl.write('\n') - self.pager_state = 'PROCESS_LINES' - - if self.pager_state == 'PROCESS_LINES': - #print >>sys.__stdout__,"PAGER state:",self.pager_state - if self.pager_do_remove == True: - self.text_ctrl.removeCurrentLine() - self.pager_do_remove = False - - if self.pager_nb_lines > 10: - #print >>sys.__stdout__,"PAGER processing 10 lines" - if self.pager_index > 0: - self.text_ctrl.write(">\x01\x1b[1;36m\x02"+self.pager_lines[self.pager_index]+'\n') - else: - self.text_ctrl.write("\x01\x1b[1;36m\x02 "+self.pager_lines[self.pager_index]+'\n') - - for line in self.pager_lines[self.pager_index+1:self.pager_index+9]: - self.text_ctrl.write("\x01\x1b[1;36m\x02 "+line+'\n') - self.pager_index += 10 - self.pager_nb_lines -= 10 - self.text_ctrl.write("--- Push Enter to continue or 'Q' to quit---") - self.pager_do_remove = True - self.pager_state = 'WAITING' - return - else: - #print >>sys.__stdout__,"PAGER processing last lines" - if self.pager_nb_lines > 0: - if self.pager_index > 0: - self.text_ctrl.write(">\x01\x1b[1;36m\x02"+self.pager_lines[self.pager_index]+'\n') - else: - self.text_ctrl.write("\x01\x1b[1;36m\x02 "+self.pager_lines[self.pager_index]+'\n') - - self.pager_index += 1 - self.pager_nb_lines -= 1 - if self.pager_nb_lines > 0: - for line in self.pager_lines[self.pager_index:]: - self.text_ctrl.write("\x01\x1b[1;36m\x02 "+line+'\n') - self.pager_nb_lines = 0 - self.pager_state = 'DONE' - self.stateShowPrompt() - - #------------------------ Key Handler ------------------------------------ - def keyPress(self, event): - ''' - Key press callback with plenty of shell goodness, like history, - autocompletions, etc. - ''' - if event.GetKeyCode() == ord('C'): - if event.Modifiers == wx.MOD_CONTROL or event.Modifiers == wx.MOD_ALT: - if self.cur_state == 'WAIT_END_OF_EXECUTION': - #we raise an exception inside the IPython thread container - self.IP.ce.raise_exc(KeyboardInterrupt) - return - - #let this before 'wx.WXK_RETURN' because we have to put 'IDLE' - #mode if AutoComp has been set as inactive - if self.cur_state == 'COMPLETING': - if not self.text_ctrl.AutoCompActive(): - self.cur_state = 'IDLE' - else: - event.Skip() - - if event.KeyCode == wx.WXK_RETURN: - if self.cur_state == 'IDLE': - #we change the state ot the state machine - self.setCurrentState('DO_EXECUTE_LINE') - self.stateDoExecuteLine() - return - - if self.pager_state == 'WAITING': - self.pager_state = 'PROCESS_LINES' - self.pager(self.doc) - return - - if self.cur_state == 'WAITING_USER_INPUT': - line=self.text_ctrl.getCurrentLine() - self.text_ctrl.write('\n') - self.setCurrentState('WAIT_END_OF_EXECUTION') - return - - if event.GetKeyCode() in [ord('q'),ord('Q')]: - if self.pager_state == 'WAITING': - self.pager_state = 'DONE' - self.text_ctrl.write('\n') - self.stateShowPrompt() - return - - if self.cur_state == 'WAITING_USER_INPUT': - event.Skip() - - if self.cur_state == 'IDLE': - if event.KeyCode == wx.WXK_UP: - history = self.IP.history_back() - self.text_ctrl.writeHistory(history) - return - if event.KeyCode == wx.WXK_DOWN: - history = self.IP.history_forward() - self.text_ctrl.writeHistory(history) - return - if event.KeyCode == wx.WXK_TAB: - #if line empty we disable tab completion - if not self.text_ctrl.getCurrentLine().strip(): - self.text_ctrl.write('\t') - return - completed, possibilities = self.IP.complete(self.text_ctrl.getCurrentLine()) - if len(possibilities) > 1: - if self.text_ctrl.autocomplete_mode == 'IPYTHON': - cur_slice = self.text_ctrl.getCurrentLine() - self.text_ctrl.write('\n') - self.text_ctrl.writeCompletion(possibilities) - self.text_ctrl.write('\n') - - self.text_ctrl.showPrompt() - self.text_ctrl.write(cur_slice) - self.text_ctrl.changeLine(completed or cur_slice) - else: - self.cur_state = 'COMPLETING' - self.text_ctrl.writeCompletion(possibilities) - else: - self.text_ctrl.changeLine(completed or cur_slice) - return - event.Skip() - - #------------------------ Option Section --------------------------------- - def evtCheckOptionCompletion(self, event): - if event.IsChecked(): - self.options['completion']['value']='STC' - else: - self.options['completion']['value']='IPYTHON' - self.text_ctrl.setCompletionMethod(self.options['completion']['value']) - self.updateOptionTracker('completion', - self.options['completion']['value']) - self.text_ctrl.SetFocus() - - def evtCheckOptionBackgroundColor(self, event): - if event.IsChecked(): - self.options['background_color']['value']='WHITE' - else: - self.options['background_color']['value']='BLACK' - self.text_ctrl.setBackgroundColor(self.options['background_color']['value']) - self.updateOptionTracker('background_color', - self.options['background_color']['value']) - self.text_ctrl.SetFocus() - - def evtCheckOptionThreading(self, event): - if event.IsChecked(): - self.options['threading']['value']='True' - self.IP.set_threading(True) - self.cout.write = self.text_ctrl.asyncWrite - else: - self.options['threading']['value']='False' - self.IP.set_threading(False) - self.cout.write = self.text_ctrl.write - self.updateOptionTracker('threading', - self.options['threading']['value']) - self.text_ctrl.SetFocus() - - def getOptions(self): - return self.options - - def reloadOptions(self,options): - self.options = options - for key in self.options.keys(): - value = self.options[key]['value'] - self.options[key]['checkbox'].SetValue(self.options[key][value]) - self.options[key]['setfunc'](value) - - if self.options['threading']['value']=='True': - self.IP.set_threading(True) - self.cout.write = self.text_ctrl.asyncWrite - else: - self.IP.set_threading(False) - self.cout.write = self.text_ctrl.write - - #------------------------ Hook Section ----------------------------------- - def updateOptionTracker(self,name,value): - ''' - Default history tracker (does nothing) - ''' - pass - - def setOptionTrackerHook(self,func): - ''' - Define a new history tracker - ''' - self.updateOptionTracker = func - - def updateHistoryTracker(self,command_line): - ''' - Default history tracker (does nothing) - ''' - pass - - def setHistoryTrackerHook(self,func): - ''' - Define a new history tracker - ''' - self.updateHistoryTracker = func - - def updateStatusTracker(self,status): - ''' - Default status tracker (does nothing) - ''' - pass - - def setStatusTrackerHook(self,func): - ''' - Define a new status tracker - ''' - self.updateStatusTracker = func - - def askExitHandler(self, event): - ''' - Default exit handler - ''' - self.text_ctrl.write('\nExit callback has not been set.') - - def setAskExitHandler(self, func): - ''' - Define an exit handler - ''' - self.askExitHandler = func - -if __name__ == '__main__': - # Some simple code to test the shell widget. - class MainWindow(wx.Frame): - def __init__(self, parent, id, title): - wx.Frame.__init__(self, parent, id, title, size=(300,250)) - self._sizer = wx.BoxSizer(wx.VERTICAL) - self.shell = IPShellWidget(self) - self._sizer.Add(self.shell, 1, wx.EXPAND) - self.SetSizer(self._sizer) - self.SetAutoLayout(1) - self.Show(True) - - app = wx.PySimpleApp() - frame = MainWindow(None, wx.ID_ANY, 'Ipython') - frame.SetSize((780, 460)) - shell = frame.shell - - app.MainLoop() diff --git a/IPython/deathrow/gui/wx/thread_ex.py b/IPython/deathrow/gui/wx/thread_ex.py deleted file mode 100644 index b11a19a..0000000 --- a/IPython/deathrow/gui/wx/thread_ex.py +++ /dev/null @@ -1,50 +0,0 @@ -""" -Thread subclass that can deal with asynchronously function calls via -raise_exc. -""" - -import threading -import inspect -import ctypes - - -def _async_raise(tid, exctype): - """raises the exception, performs cleanup if needed""" - if not inspect.isclass(exctype): - raise TypeError("Only types can be raised (not instances)") - res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) - if res == 0: - raise ValueError("invalid thread id") - elif res != 1: - # """if it returns a number greater than one, you're in trouble, - # and you should call it again with exc=NULL to revert the effect""" - ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) - raise SystemError("PyThreadState_SetAsyncExc failed") - - -class ThreadEx(threading.Thread): - def _get_my_tid(self): - """determines this (self's) thread id""" - if not self.isAlive(): - raise threading.ThreadError("the thread is not active") - - # do we have it cached? - if hasattr(self, "_thread_id"): - return self._thread_id - - # no, look for it in the _active dict - for tid, tobj in threading._active.items(): - if tobj is self: - self._thread_id = tid - return tid - - raise AssertionError("could not determine the thread's id") - - def raise_exc(self, exctype): - """raises the given exception type in the context of this thread""" - _async_raise(self._get_my_tid(), exctype) - - def kill(self): - """raises SystemExit in the context of the given thread, which should - cause the thread to exit silently (unless caught)""" - self.raise_exc(SystemExit) diff --git a/IPython/deathrow/gui/wx/wxIPython.py b/IPython/deathrow/gui/wx/wxIPython.py deleted file mode 100644 index 200d213..0000000 --- a/IPython/deathrow/gui/wx/wxIPython.py +++ /dev/null @@ -1,266 +0,0 @@ -#!/usr/bin/python -# -*- coding: iso-8859-15 -*- - -import wx.aui -import sys -#used for about dialog -from wx.lib.wordwrap import wordwrap - -#used for ipython GUI objects -from IPython.gui.wx.ipython_view import IPShellWidget -from IPython.gui.wx.ipython_history import IPythonHistoryPanel - -#used to invoke ipython1 wx implementation -### FIXME ### temporary disabled due to interference with 'show_in_pager' hook -is_sync_frontend_ok = False -try: - from IPython.frontend.wx.ipythonx import IPythonXController -except ImportError: - is_sync_frontend_ok = False - -#used to create options.conf file in user directory -from IPython.core.ipapi import get - -__version__ = 0.91 -__author__ = "Laurent Dufrechou" -__email__ = "laurent.dufrechou _at_ gmail.com" -__license__ = "BSD" - -#----------------------------------------- -# Creating one main frame for our -# application with movables windows -#----------------------------------------- -class MyFrame(wx.Frame): - """Creating one main frame for our - application with movables windows""" - def __init__(self, parent=None, id=-1, title="WxIPython", - pos=wx.DefaultPosition, - size=(800, 600), style=wx.DEFAULT_FRAME_STYLE, sync_ok=False): - wx.Frame.__init__(self, parent, id, title, pos, size, style) - self._mgr = wx.aui.AuiManager() - - # notify PyAUI which frame to use - self._mgr.SetManagedWindow(self) - - #create differents panels and make them persistant - self.history_panel = IPythonHistoryPanel(self) - - self.history_panel.setOptionTrackerHook(self.optionSave) - - self.ipython_panel = IPShellWidget(self,background_color = "BLACK") - #self.ipython_panel = IPShellWidget(self,background_color = "WHITE") - if(sync_ok): - self.ipython_panel2 = IPythonXController(self) - else: - self.ipython_panel2 = None - self.ipython_panel.setHistoryTrackerHook(self.history_panel.write) - self.ipython_panel.setStatusTrackerHook(self.updateStatus) - self.ipython_panel.setAskExitHandler(self.OnExitDlg) - self.ipython_panel.setOptionTrackerHook(self.optionSave) - - #Create a notebook to display different IPython shell implementations - self.nb = wx.aui.AuiNotebook(self) - - self.optionLoad() - - self.statusbar = self.createStatus() - self.createMenu() - - ######################################################################## - ### add the panes to the manager - # main panels - self._mgr.AddPane(self.nb , wx.CENTER, "IPython Shells") - self.nb.AddPage(self.ipython_panel , "IPython0 Shell") - if(sync_ok): - self.nb.AddPage(self.ipython_panel2, "IPython1 Synchroneous Shell") - - self._mgr.AddPane(self.history_panel , wx.RIGHT, "IPython history") - - # now we specify some panel characteristics - self._mgr.GetPane(self.ipython_panel).CaptionVisible(True); - self._mgr.GetPane(self.history_panel).CaptionVisible(True); - self._mgr.GetPane(self.history_panel).MinSize((200,400)); - - # tell the manager to "commit" all the changes just made - self._mgr.Update() - - #global event handling - self.Bind(wx.EVT_CLOSE, self.OnClose) - self.Bind(wx.EVT_MENU, self.OnClose,id=wx.ID_EXIT) - self.Bind(wx.EVT_MENU, self.OnShowIPythonPanel,id=wx.ID_HIGHEST+1) - self.Bind(wx.EVT_MENU, self.OnShowHistoryPanel,id=wx.ID_HIGHEST+2) - self.Bind(wx.EVT_MENU, self.OnShowAbout, id=wx.ID_HIGHEST+3) - self.Bind(wx.EVT_MENU, self.OnShowAllPanel,id=wx.ID_HIGHEST+6) - - warn_text = 'Hello from IPython and wxPython.\n' - warn_text +='Please Note that this work is still EXPERIMENTAL\n' - warn_text +='It does NOT emulate currently all the IPython functions.\n' - warn_text +="\nIf you use MATPLOTLIB with show() you'll need to deactivate the THREADING option.\n" - if(not sync_ok): - warn_text +="\n->No twisted package detected, IPython1 example deactivated." - - dlg = wx.MessageDialog(self, - warn_text, - 'Warning Box', - wx.OK | wx.ICON_INFORMATION - ) - dlg.ShowModal() - dlg.Destroy() - - def optionSave(self, name, value): - ip = get() - path = ip.ipython_dir - opt = open(path + '/options.conf','w') - - try: - options_ipython_panel = self.ipython_panel.getOptions() - options_history_panel = self.history_panel.getOptions() - - for key in options_ipython_panel.keys(): - opt.write(key + '=' + options_ipython_panel[key]['value']+'\n') - for key in options_history_panel.keys(): - opt.write(key + '=' + options_history_panel[key]['value']+'\n') - finally: - opt.close() - - def optionLoad(self): - try: - ip = get() - path = ip.ipython_dir - opt = open(path + '/options.conf','r') - lines = opt.readlines() - opt.close() - - options_ipython_panel = self.ipython_panel.getOptions() - options_history_panel = self.history_panel.getOptions() - - for line in lines: - key = line.split('=')[0] - value = line.split('=')[1].replace('\n','').replace('\r','') - if key in options_ipython_panel.keys(): - options_ipython_panel[key]['value'] = value - elif key in options_history_panel.keys(): - options_history_panel[key]['value'] = value - else: - print >>sys.__stdout__,"Warning: key ",key,"not found in widget options. Check Options.conf" - self.ipython_panel.reloadOptions(options_ipython_panel) - self.history_panel.reloadOptions(options_history_panel) - - except IOError: - print >>sys.__stdout__,"Could not open Options.conf, defaulting to default values." - - - def createMenu(self): - """local method used to create one menu bar""" - - mb = wx.MenuBar() - - file_menu = wx.Menu() - file_menu.Append(wx.ID_EXIT, "Exit") - - view_menu = wx.Menu() - view_menu.Append(wx.ID_HIGHEST+1, "Show IPython Panel") - view_menu.Append(wx.ID_HIGHEST+2, "Show History Panel") - view_menu.AppendSeparator() - view_menu.Append(wx.ID_HIGHEST+6, "Show All") - - about_menu = wx.Menu() - about_menu.Append(wx.ID_HIGHEST+3, "About") - - mb.Append(file_menu, "File") - mb.Append(view_menu, "View") - mb.Append(about_menu, "About") - #mb.Append(options_menu, "Options") - - self.SetMenuBar(mb) - - def createStatus(self): - statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP) - statusbar.SetStatusWidths([-2, -3]) - statusbar.SetStatusText("Ready", 0) - statusbar.SetStatusText("WxIPython "+str(__version__), 1) - return statusbar - - def updateStatus(self,text): - states = {'IDLE':'Idle', - 'DO_EXECUTE_LINE':'Send command', - 'WAIT_END_OF_EXECUTION':'Running command', - 'WAITING_USER_INPUT':'Waiting user input', - 'SHOW_DOC':'Showing doc', - 'SHOW_PROMPT':'Showing prompt'} - self.statusbar.SetStatusText(states[text], 0) - - def OnClose(self, event): - """#event used to close program """ - # deinitialize the frame manager - self._mgr.UnInit() - self.Destroy() - event.Skip() - - def OnExitDlg(self, event): - dlg = wx.MessageDialog(self, 'Are you sure you want to quit WxIPython', - 'WxIPython exit', - wx.ICON_QUESTION | - wx.YES_NO | wx.NO_DEFAULT - ) - if dlg.ShowModal() == wx.ID_YES: - dlg.Destroy() - self._mgr.UnInit() - self.Destroy() - dlg.Destroy() - - #event to display IPython pannel - def OnShowIPythonPanel(self,event): - """ #event to display Boxpannel """ - self._mgr.GetPane(self.ipython_panel).Show(True) - self._mgr.Update() - #event to display History pannel - def OnShowHistoryPanel(self,event): - self._mgr.GetPane(self.history_panel).Show(True) - self._mgr.Update() - - def OnShowAllPanel(self,event): - """#event to display all Pannels""" - self._mgr.GetPane(self.ipython_panel).Show(True) - self._mgr.GetPane(self.history_panel).Show(True) - self._mgr.Update() - - def OnShowAbout(self, event): - # First we create and fill the info object - info = wx.AboutDialogInfo() - info.Name = "WxIPython" - info.Version = str(__version__) - info.Copyright = "(C) 2007 Laurent Dufrechou" - info.Description = wordwrap( - "A Gui that embbed a multithreaded IPython Shell", - 350, wx.ClientDC(self)) - info.WebSite = ("http://ipython.scipy.org/", "IPython home page") - info.Developers = [ "Laurent Dufrechou" ] - licenseText="BSD License.\nAll rights reserved. This program and the accompanying materials are made available under the terms of the BSD which accompanies this distribution, and is available at http://www.opensource.org/licenses/bsd-license.php" - info.License = wordwrap(licenseText, 500, wx.ClientDC(self)) - - # Then we call wx.AboutBox giving it that info object - wx.AboutBox(info) - -#----------------------------------------- -#Creating our application -#----------------------------------------- -class MyApp(wx.PySimpleApp): - """Creating our application""" - def __init__(self, sync_ok=False): - wx.PySimpleApp.__init__(self) - - self.frame = MyFrame(sync_ok=sync_ok) - self.frame.Show() - -#----------------------------------------- -#Main loop -#----------------------------------------- -def main(): - app = MyApp(is_sync_frontend_ok) - app.SetTopWindow(app.frame) - app.MainLoop() - -#if launched as main program run this -if __name__ == '__main__': - main() diff --git a/IPython/deathrow/ibrowse.py b/IPython/deathrow/ibrowse.py deleted file mode 100644 index edab24e..0000000 --- a/IPython/deathrow/ibrowse.py +++ /dev/null @@ -1,1767 +0,0 @@ -# -*- coding: iso-8859-1 -*- - -import curses, fcntl, signal, struct, tty, textwrap, inspect - -from IPython.core import ipapi - -import astyle, ipipe - - -# Python 2.3 compatibility -try: - set -except NameError: - import sets - set = sets.Set - -# Python 2.3 compatibility -try: - sorted -except NameError: - from ipipe import sorted - - -class UnassignedKeyError(Exception): - """ - Exception that is used for reporting unassigned keys. - """ - - -class UnknownCommandError(Exception): - """ - Exception that is used for reporting unknown commands (this should never - happen). - """ - - -class CommandError(Exception): - """ - Exception that is used for reporting that a command can't be executed. - """ - - -class Keymap(dict): - """ - Stores mapping of keys to commands. - """ - def __init__(self): - self._keymap = {} - - def __setitem__(self, key, command): - if isinstance(key, str): - for c in key: - dict.__setitem__(self, ord(c), command) - else: - dict.__setitem__(self, key, command) - - def __getitem__(self, key): - if isinstance(key, str): - key = ord(key) - return dict.__getitem__(self, key) - - def __detitem__(self, key): - if isinstance(key, str): - key = ord(key) - dict.__detitem__(self, key) - - def register(self, command, *keys): - for key in keys: - self[key] = command - - def get(self, key, default=None): - if isinstance(key, str): - key = ord(key) - return dict.get(self, key, default) - - def findkey(self, command, default=ipipe.noitem): - for (key, commandcandidate) in self.iteritems(): - if commandcandidate == command: - return key - if default is ipipe.noitem: - raise KeyError(command) - return default - - -class _BrowserCachedItem(object): - # This is used internally by ``ibrowse`` to store a item together with its - # marked status. - __slots__ = ("item", "marked") - - def __init__(self, item): - self.item = item - self.marked = False - - -class _BrowserHelp(object): - style_header = astyle.Style.fromstr("yellow:black:bold") - # This is used internally by ``ibrowse`` for displaying the help screen. - def __init__(self, browser): - self.browser = browser - - def __xrepr__(self, mode): - yield (-1, True) - if mode == "header" or mode == "footer": - yield (astyle.style_default, "ibrowse help screen") - else: - yield (astyle.style_default, repr(self)) - - def __iter__(self): - # Get reverse key mapping - allkeys = {} - for (key, cmd) in self.browser.keymap.iteritems(): - allkeys.setdefault(cmd, []).append(key) - - fields = ("key", "description") - - commands = [] - for name in dir(self.browser): - if name.startswith("cmd_"): - command = getattr(self.browser, name) - commands.append((inspect.getsourcelines(command)[-1], name[4:], command)) - commands.sort() - commands = [(c[1], c[2]) for c in commands] - for (i, (name, command)) in enumerate(commands): - if i: - yield ipipe.Fields(fields, key="", description="") - - description = command.__doc__ - if description is None: - lines = [] - else: - lines = [l.strip() for l in description.splitlines() if l.strip()] - description = "\n".join(lines) - lines = textwrap.wrap(description, 60) - keys = allkeys.get(name, []) - - yield ipipe.Fields(fields, key="", description=astyle.Text((self.style_header, name))) - for i in xrange(max(len(keys), len(lines))): - try: - key = self.browser.keylabel(keys[i]) - except IndexError: - key = "" - try: - line = lines[i] - except IndexError: - line = "" - yield ipipe.Fields(fields, key=key, description=line) - - -class _BrowserLevel(object): - # This is used internally to store the state (iterator, fetch items, - # position of cursor and screen, etc.) of one browser level - # An ``ibrowse`` object keeps multiple ``_BrowserLevel`` objects in - # a stack. - def __init__(self, browser, input, mainsizey, *attrs): - self.browser = browser - self.input = input - self.header = [x for x in ipipe.xrepr(input, "header") if not isinstance(x[0], int)] - # iterator for the input - self.iterator = ipipe.xiter(input) - - # is the iterator exhausted? - self.exhausted = False - - # attributes to be display (autodetected if empty) - self.attrs = attrs - - # fetched items (+ marked flag) - self.items = ipipe.deque() - - # Number of marked objects - self.marked = 0 - - # Vertical cursor position - self.cury = 0 - - # Horizontal cursor position - self.curx = 0 - - # Index of first data column - self.datastartx = 0 - - # Index of first data line - self.datastarty = 0 - - # height of the data display area - self.mainsizey = mainsizey - - # width of the data display area (changes when scrolling) - self.mainsizex = 0 - - # Size of row number (changes when scrolling) - self.numbersizex = 0 - - # Attributes to display (in this order) - self.displayattrs = [] - - # index and attribute under the cursor - self.displayattr = (None, ipipe.noitem) - - # Maps attributes to column widths - self.colwidths = {} - - # Set of hidden attributes - self.hiddenattrs = set() - - # This takes care of all the caches etc. - self.moveto(0, 0, refresh=True) - - def fetch(self, count): - # Try to fill ``self.items`` with at least ``count`` objects. - have = len(self.items) - while not self.exhausted and have < count: - try: - item = self.iterator.next() - except StopIteration: - self.exhausted = True - break - except (KeyboardInterrupt, SystemExit): - raise - except Exception as exc: - have += 1 - self.items.append(_BrowserCachedItem(exc)) - self.exhausted = True - break - else: - have += 1 - self.items.append(_BrowserCachedItem(item)) - - def calcdisplayattrs(self): - # Calculate which attributes are available from the objects that are - # currently visible on screen (and store it in ``self.displayattrs``) - - attrs = set() - self.displayattrs = [] - if self.attrs: - # If the browser object specifies a fixed list of attributes, - # simply use it (removing hidden attributes). - for attr in self.attrs: - attr = ipipe.upgradexattr(attr) - if attr not in attrs and attr not in self.hiddenattrs: - self.displayattrs.append(attr) - attrs.add(attr) - else: - endy = min(self.datastarty+self.mainsizey, len(self.items)) - for i in xrange(self.datastarty, endy): - for attr in ipipe.xattrs(self.items[i].item, "default"): - if attr not in attrs and attr not in self.hiddenattrs: - self.displayattrs.append(attr) - attrs.add(attr) - - def getrow(self, i): - # Return a dictionary with the attributes for the object - # ``self.items[i]``. Attribute names are taken from - # ``self.displayattrs`` so ``calcdisplayattrs()`` must have been - # called before. - row = {} - item = self.items[i].item - for attr in self.displayattrs: - try: - value = attr.value(item) - except (KeyboardInterrupt, SystemExit): - raise - except Exception as exc: - value = exc - # only store attribute if it exists (or we got an exception) - if value is not ipipe.noitem: - # remember alignment, length and colored text - row[attr] = ipipe.xformat(value, "cell", self.browser.maxattrlength) - return row - - def calcwidths(self): - # Recalculate the displayed fields and their widths. - # ``calcdisplayattrs()'' must have been called and the cache - # for attributes of the objects on screen (``self.displayrows``) - # must have been filled. This sets ``self.colwidths`` which maps - # attribute descriptors to widths. - self.colwidths = {} - for row in self.displayrows: - for attr in self.displayattrs: - try: - length = row[attr][1] - except KeyError: - length = 0 - # always add attribute to colwidths, even if it doesn't exist - if attr not in self.colwidths: - self.colwidths[attr] = len(attr.name()) - newwidth = max(self.colwidths[attr], length) - self.colwidths[attr] = newwidth - - # How many characters do we need to paint the largest item number? - self.numbersizex = len(str(self.datastarty+self.mainsizey-1)) - # How must space have we got to display data? - self.mainsizex = self.browser.scrsizex-self.numbersizex-3 - # width of all columns - self.datasizex = sum(self.colwidths.itervalues()) + len(self.colwidths) - - def calcdisplayattr(self): - # Find out which attribute the cursor is on and store this - # information in ``self.displayattr``. - pos = 0 - for (i, attr) in enumerate(self.displayattrs): - if pos+self.colwidths[attr] >= self.curx: - self.displayattr = (i, attr) - break - pos += self.colwidths[attr]+1 - else: - self.displayattr = (None, ipipe.noitem) - - def moveto(self, x, y, refresh=False): - # Move the cursor to the position ``(x,y)`` (in data coordinates, - # not in screen coordinates). If ``refresh`` is true, all cached - # values will be recalculated (e.g. because the list has been - # resorted, so screen positions etc. are no longer valid). - olddatastarty = self.datastarty - oldx = self.curx - oldy = self.cury - x = int(x+0.5) - y = int(y+0.5) - newx = x # remember where we wanted to move - newy = y # remember where we wanted to move - - scrollbordery = min(self.browser.scrollbordery, self.mainsizey//2) - scrollborderx = min(self.browser.scrollborderx, self.mainsizex//2) - - # Make sure that the cursor didn't leave the main area vertically - if y < 0: - y = 0 - # try to get enough items to fill the screen - self.fetch(max(y+scrollbordery+1, self.mainsizey)) - if y >= len(self.items): - y = max(0, len(self.items)-1) - - # Make sure that the cursor stays on screen vertically - if y < self.datastarty+scrollbordery: - self.datastarty = max(0, y-scrollbordery) - elif y >= self.datastarty+self.mainsizey-scrollbordery: - self.datastarty = max(0, min(y-self.mainsizey+scrollbordery+1, - len(self.items)-self.mainsizey)) - - if refresh: # Do we need to refresh the complete display? - self.calcdisplayattrs() - endy = min(self.datastarty+self.mainsizey, len(self.items)) - self.displayrows = map(self.getrow, xrange(self.datastarty, endy)) - self.calcwidths() - # Did we scroll vertically => update displayrows - # and various other attributes - elif self.datastarty != olddatastarty: - # Recalculate which attributes we have to display - olddisplayattrs = self.displayattrs - self.calcdisplayattrs() - # If there are new attributes, recreate the cache - if self.displayattrs != olddisplayattrs: - endy = min(self.datastarty+self.mainsizey, len(self.items)) - self.displayrows = map(self.getrow, xrange(self.datastarty, endy)) - elif self.datastarty<olddatastarty: # we did scroll up - # drop rows from the end - del self.displayrows[self.datastarty-olddatastarty:] - # fetch new items - for i in xrange(min(olddatastarty, self.datastarty+self.mainsizey)-1, - self.datastarty-1, -1): - try: - row = self.getrow(i) - except IndexError: - # we didn't have enough objects to fill the screen - break - self.displayrows.insert(0, row) - else: # we did scroll down - # drop rows from the start - del self.displayrows[:self.datastarty-olddatastarty] - # fetch new items - for i in xrange(max(olddatastarty+self.mainsizey, self.datastarty), - self.datastarty+self.mainsizey): - try: - row = self.getrow(i) - except IndexError: - # we didn't have enough objects to fill the screen - break - self.displayrows.append(row) - self.calcwidths() - - # Make sure that the cursor didn't leave the data area horizontally - if x < 0: - x = 0 - elif x >= self.datasizex: - x = max(0, self.datasizex-1) - - # Make sure that the cursor stays on screen horizontally - if x < self.datastartx+scrollborderx: - self.datastartx = max(0, x-scrollborderx) - elif x >= self.datastartx+self.mainsizex-scrollborderx: - self.datastartx = max(0, min(x-self.mainsizex+scrollborderx+1, - self.datasizex-self.mainsizex)) - - if x == oldx and y == oldy and (x != newx or y != newy): # couldn't move - self.browser.beep() - else: - self.curx = x - self.cury = y - self.calcdisplayattr() - - def sort(self, key, reverse=False): - """ - Sort the currently list of items using the key function ``key``. If - ``reverse`` is true the sort order is reversed. - """ - curitem = self.items[self.cury] # Remember where the cursor is now - - # Sort items - def realkey(item): - return key(item.item) - self.items = ipipe.deque(sorted(self.items, key=realkey, reverse=reverse)) - - # Find out where the object under the cursor went - cury = self.cury - for (i, item) in enumerate(self.items): - if item is curitem: - cury = i - break - - self.moveto(self.curx, cury, refresh=True) - - def refresh(self): - """ - Restart iterating the input. - """ - self.iterator = ipipe.xiter(self.input) - self.items.clear() - self.exhausted = False - self.datastartx = self.datastarty = 0 - self.moveto(0, 0, refresh=True) - - def refreshfind(self): - """ - Restart iterating the input and go back to the same object as before - (if it can be found in the new iterator). - """ - try: - oldobject = self.items[self.cury].item - except IndexError: - oldobject = ipipe.noitem - self.iterator = ipipe.xiter(self.input) - self.items.clear() - self.exhausted = False - while True: - self.fetch(len(self.items)+1) - if self.exhausted: - curses.beep() - self.datastartx = self.datastarty = 0 - self.moveto(self.curx, 0, refresh=True) - break - if self.items[-1].item == oldobject: - self.datastartx = self.datastarty = 0 - self.moveto(self.curx, len(self.items)-1, refresh=True) - break - - -class _CommandInput(object): - keymap = Keymap() - keymap.register("left", curses.KEY_LEFT) - keymap.register("right", curses.KEY_RIGHT) - keymap.register("home", curses.KEY_HOME, "\x01") # Ctrl-A - keymap.register("end", curses.KEY_END, "\x05") # Ctrl-E - # FIXME: What's happening here? - keymap.register("backspace", curses.KEY_BACKSPACE, "\x08\x7f") - keymap.register("delete", curses.KEY_DC) - keymap.register("delend", 0x0b) # Ctrl-K - keymap.register("execute", "\r\n") - keymap.register("up", curses.KEY_UP) - keymap.register("down", curses.KEY_DOWN) - keymap.register("incsearchup", curses.KEY_PPAGE) - keymap.register("incsearchdown", curses.KEY_NPAGE) - keymap.register("exit", "\x18"), # Ctrl-X - - def __init__(self, prompt): - self.prompt = prompt - self.history = [] - self.maxhistory = 100 - self.input = "" - self.curx = 0 - self.cury = -1 # blank line - - def start(self): - self.input = "" - self.curx = 0 - self.cury = -1 # blank line - - def handlekey(self, browser, key): - cmdname = self.keymap.get(key, None) - if cmdname is not None: - cmdfunc = getattr(self, "cmd_%s" % cmdname, None) - if cmdfunc is not None: - return cmdfunc(browser) - curses.beep() - elif key != -1: - try: - char = chr(key) - except ValueError: - curses.beep() - else: - return self.handlechar(browser, char) - - def handlechar(self, browser, char): - self.input = self.input[:self.curx] + char + self.input[self.curx:] - self.curx += 1 - return True - - def dohistory(self): - self.history.insert(0, self.input) - del self.history[:-self.maxhistory] - - def cmd_backspace(self, browser): - if self.curx: - self.input = self.input[:self.curx-1] + self.input[self.curx:] - self.curx -= 1 - return True - else: - curses.beep() - - def cmd_delete(self, browser): - if self.curx<len(self.input): - self.input = self.input[:self.curx] + self.input[self.curx+1:] - return True - else: - curses.beep() - - def cmd_delend(self, browser): - if self.curx<len(self.input): - self.input = self.input[:self.curx] - return True - - def cmd_left(self, browser): - if self.curx: - self.curx -= 1 - return True - else: - curses.beep() - - def cmd_right(self, browser): - if self.curx < len(self.input): - self.curx += 1 - return True - else: - curses.beep() - - def cmd_home(self, browser): - if self.curx: - self.curx = 0 - return True - else: - curses.beep() - - def cmd_end(self, browser): - if self.curx < len(self.input): - self.curx = len(self.input) - return True - else: - curses.beep() - - def cmd_up(self, browser): - if self.cury < len(self.history)-1: - self.cury += 1 - self.input = self.history[self.cury] - self.curx = len(self.input) - return True - else: - curses.beep() - - def cmd_down(self, browser): - if self.cury >= 0: - self.cury -= 1 - if self.cury>=0: - self.input = self.history[self.cury] - else: - self.input = "" - self.curx = len(self.input) - return True - else: - curses.beep() - - def cmd_incsearchup(self, browser): - prefix = self.input[:self.curx] - cury = self.cury - while True: - cury += 1 - if cury >= len(self.history): - break - if self.history[cury].startswith(prefix): - self.input = self.history[cury] - self.cury = cury - return True - curses.beep() - - def cmd_incsearchdown(self, browser): - prefix = self.input[:self.curx] - cury = self.cury - while True: - cury -= 1 - if cury <= 0: - break - if self.history[cury].startswith(prefix): - self.input = self.history[self.cury] - self.cury = cury - return True - curses.beep() - - def cmd_exit(self, browser): - browser.mode = "default" - return True - - def cmd_execute(self, browser): - raise NotImplementedError - - -class _CommandGoto(_CommandInput): - def __init__(self): - _CommandInput.__init__(self, "goto object #") - - def handlechar(self, browser, char): - # Only accept digits - if not "0" <= char <= "9": - curses.beep() - else: - return _CommandInput.handlechar(self, browser, char) - - def cmd_execute(self, browser): - level = browser.levels[-1] - if self.input: - self.dohistory() - level.moveto(level.curx, int(self.input)) - browser.mode = "default" - return True - - -class _CommandFind(_CommandInput): - def __init__(self): - _CommandInput.__init__(self, "find expression") - - def cmd_execute(self, browser): - level = browser.levels[-1] - if self.input: - self.dohistory() - while True: - cury = level.cury - level.moveto(level.curx, cury+1) - if cury == level.cury: - curses.beep() - break # hit end - item = level.items[level.cury].item - try: - globals = ipipe.getglobals(None) - if eval(self.input, globals, ipipe.AttrNamespace(item)): - break # found something - except (KeyboardInterrupt, SystemExit): - raise - except Exception as exc: - browser.report(exc) - curses.beep() - break # break on error - browser.mode = "default" - return True - - -class _CommandFindBackwards(_CommandInput): - def __init__(self): - _CommandInput.__init__(self, "find backwards expression") - - def cmd_execute(self, browser): - level = browser.levels[-1] - if self.input: - self.dohistory() - while level.cury: - level.moveto(level.curx, level.cury-1) - item = level.items[level.cury].item - try: - globals = ipipe.getglobals(None) - if eval(self.input, globals, ipipe.AttrNamespace(item)): - break # found something - except (KeyboardInterrupt, SystemExit): - raise - except Exception as exc: - browser.report(exc) - curses.beep() - break # break on error - else: - curses.beep() - browser.mode = "default" - return True - - -class ibrowse(ipipe.Display): - # Show this many lines from the previous screen when paging horizontally - pageoverlapx = 1 - - # Show this many lines from the previous screen when paging vertically - pageoverlapy = 1 - - # Start scrolling when the cursor is less than this number of columns - # away from the left or right screen edge - scrollborderx = 10 - - # Start scrolling when the cursor is less than this number of lines - # away from the top or bottom screen edge - scrollbordery = 5 - - # Accelerate by this factor when scrolling horizontally - acceleratex = 1.05 - - # Accelerate by this factor when scrolling vertically - acceleratey = 1.05 - - # The maximum horizontal scroll speed - # (as a factor of the screen width (i.e. 0.5 == half a screen width) - maxspeedx = 0.5 - - # The maximum vertical scroll speed - # (as a factor of the screen height (i.e. 0.5 == half a screen height) - maxspeedy = 0.5 - - # The maximum number of header lines for browser level - # if the nesting is deeper, only the innermost levels are displayed - maxheaders = 5 - - # The approximate maximum length of a column entry - maxattrlength = 200 - - # Styles for various parts of the GUI - style_objheadertext = astyle.Style.fromstr("white:black:bold|reverse") - style_objheadernumber = astyle.Style.fromstr("white:blue:bold|reverse") - style_objheaderobject = astyle.Style.fromstr("white:black:reverse") - style_colheader = astyle.Style.fromstr("blue:white:reverse") - style_colheaderhere = astyle.Style.fromstr("green:black:bold|reverse") - style_colheadersep = astyle.Style.fromstr("blue:black:reverse") - style_number = astyle.Style.fromstr("blue:white:reverse") - style_numberhere = astyle.Style.fromstr("green:black:bold|reverse") - style_sep = astyle.Style.fromstr("blue:black") - style_data = astyle.Style.fromstr("white:black") - style_datapad = astyle.Style.fromstr("blue:black:bold") - style_footer = astyle.Style.fromstr("black:white") - style_report = astyle.Style.fromstr("white:black") - - # Column separator in header - headersepchar = "|" - - # Character for padding data cell entries - datapadchar = "." - - # Column separator in data area - datasepchar = "|" - - # Character to use for "empty" cell (i.e. for non-existing attributes) - nodatachar = "-" - - # Prompts for modes that require keyboard input - prompts = { - "goto": _CommandGoto(), - "find": _CommandFind(), - "findbackwards": _CommandFindBackwards() - } - - # Maps curses key codes to "function" names - keymap = Keymap() - keymap.register("quit", "q") - keymap.register("up", curses.KEY_UP) - keymap.register("down", curses.KEY_DOWN) - keymap.register("pageup", curses.KEY_PPAGE) - keymap.register("pagedown", curses.KEY_NPAGE) - keymap.register("left", curses.KEY_LEFT) - keymap.register("right", curses.KEY_RIGHT) - keymap.register("home", curses.KEY_HOME, "\x01") - keymap.register("end", curses.KEY_END, "\x05") - keymap.register("prevattr", "<\x1b") - keymap.register("nextattr", ">\t") - keymap.register("pick", "p") - keymap.register("pickattr", "P") - keymap.register("pickallattrs", "C") - keymap.register("pickmarked", "m") - keymap.register("pickmarkedattr", "M") - keymap.register("pickinput", "i") - keymap.register("pickinputattr", "I") - keymap.register("hideattr", "h") - keymap.register("unhideattrs", "H") - keymap.register("help", "?") - keymap.register("enter", "\r\n") - keymap.register("enterattr", "E") - # FIXME: What's happening here? - keymap.register("leave", curses.KEY_BACKSPACE, "x\x08\x7f") - keymap.register("detail", "d") - keymap.register("detailattr", "D") - keymap.register("tooglemark", " ") - keymap.register("markrange", "%") - keymap.register("sortattrasc", "v") - keymap.register("sortattrdesc", "V") - keymap.register("goto", "g") - keymap.register("find", "f") - keymap.register("findbackwards", "b") - keymap.register("refresh", "r") - keymap.register("refreshfind", "R") - - def __init__(self, input=None, *attrs): - """ - Create a new browser. If ``attrs`` is not empty, it is the list - of attributes that will be displayed in the browser, otherwise - these will be determined by the objects on screen. - """ - ipipe.Display.__init__(self, input) - - self.attrs = attrs - - # Stack of browser levels - self.levels = [] - # how many colums to scroll (Changes when accelerating) - self.stepx = 1. - - # how many rows to scroll (Changes when accelerating) - self.stepy = 1. - - # Beep on the edges of the data area? (Will be set to ``False`` - # once the cursor hits the edge of the screen, so we don't get - # multiple beeps). - self._dobeep = True - - # Cache for registered ``curses`` colors and styles. - self._styles = {} - self._colors = {} - self._maxcolor = 1 - - # How many header lines do we want to paint (the numbers of levels - # we have, but with an upper bound) - self._headerlines = 1 - - # Index of first header line - self._firstheaderline = 0 - - # curses window - self.scr = None - # report in the footer line (error, executed command etc.) - self._report = None - - # value to be returned to the caller (set by commands) - self.returnvalue = None - - # The mode the browser is in - # e.g. normal browsing or entering an argument for a command - self.mode = "default" - - # set by the SIGWINCH signal handler - self.resized = False - - def nextstepx(self, step): - """ - Accelerate horizontally. - """ - return max(1., min(step*self.acceleratex, - self.maxspeedx*self.levels[-1].mainsizex)) - - def nextstepy(self, step): - """ - Accelerate vertically. - """ - return max(1., min(step*self.acceleratey, - self.maxspeedy*self.levels[-1].mainsizey)) - - def getstyle(self, style): - """ - Register the ``style`` with ``curses`` or get it from the cache, - if it has been registered before. - """ - try: - return self._styles[style.fg, style.bg, style.attrs] - except KeyError: - attrs = 0 - for b in astyle.A2CURSES: - if style.attrs & b: - attrs |= astyle.A2CURSES[b] - try: - color = self._colors[style.fg, style.bg] - except KeyError: - curses.init_pair( - self._maxcolor, - astyle.COLOR2CURSES[style.fg], - astyle.COLOR2CURSES[style.bg] - ) - color = curses.color_pair(self._maxcolor) - self._colors[style.fg, style.bg] = color - self._maxcolor += 1 - c = color | attrs - self._styles[style.fg, style.bg, style.attrs] = c - return c - - def addstr(self, y, x, begx, endx, text, style): - """ - A version of ``curses.addstr()`` that can handle ``x`` coordinates - that are outside the screen. - """ - text2 = text[max(0, begx-x):max(0, endx-x)] - if text2: - self.scr.addstr(y, max(x, begx), text2, self.getstyle(style)) - return len(text) - - def addchr(self, y, x, begx, endx, c, l, style): - x0 = max(x, begx) - x1 = min(x+l, endx) - if x1>x0: - self.scr.addstr(y, x0, c*(x1-x0), self.getstyle(style)) - return l - - def _calcheaderlines(self, levels): - # Calculate how many headerlines do we have to display, if we have - # ``levels`` browser levels - if levels is None: - levels = len(self.levels) - self._headerlines = min(self.maxheaders, levels) - self._firstheaderline = levels-self._headerlines - - def getstylehere(self, style): - """ - Return a style for displaying the original style ``style`` - in the row the cursor is on. - """ - return astyle.Style(style.fg, astyle.COLOR_BLUE, style.attrs | astyle.A_BOLD) - - def report(self, msg): - """ - Store the message ``msg`` for display below the footer line. This - will be displayed as soon as the screen is redrawn. - """ - self._report = msg - - def enter(self, item, *attrs): - """ - Enter the object ``item``. If ``attrs`` is specified, it will be used - as a fixed list of attributes to display. - """ - if self.levels and item is self.levels[-1].input: - curses.beep() - self.report(CommandError("Recursion on input object")) - else: - oldlevels = len(self.levels) - self._calcheaderlines(oldlevels+1) - try: - level = _BrowserLevel( - self, - item, - self.scrsizey-1-self._headerlines-2, - *attrs - ) - except (KeyboardInterrupt, SystemExit): - raise - except Exception as exc: - if not self.levels: - raise - self._calcheaderlines(oldlevels) - curses.beep() - self.report(exc) - else: - self.levels.append(level) - - def startkeyboardinput(self, mode): - """ - Enter mode ``mode``, which requires keyboard input. - """ - self.mode = mode - self.prompts[mode].start() - - def keylabel(self, keycode): - """ - Return a pretty name for the ``curses`` key ``keycode`` (used in the - help screen and in reports about unassigned keys). - """ - if keycode <= 0xff: - specialsnames = { - ord("\n"): "RETURN", - ord(" "): "SPACE", - ord("\t"): "TAB", - ord("\x7f"): "DELETE", - ord("\x08"): "BACKSPACE", - } - if keycode in specialsnames: - return specialsnames[keycode] - elif 0x00 < keycode < 0x20: - return "CTRL-%s" % chr(keycode + 64) - return repr(chr(keycode)) - for name in dir(curses): - if name.startswith("KEY_") and getattr(curses, name) == keycode: - return name - return str(keycode) - - def beep(self, force=False): - if force or self._dobeep: - curses.beep() - # don't beep again (as long as the same key is pressed) - self._dobeep = False - - def cmd_up(self): - """ - Move the cursor to the previous row. - """ - level = self.levels[-1] - self.report("up") - level.moveto(level.curx, level.cury-self.stepy) - - def cmd_down(self): - """ - Move the cursor to the next row. - """ - level = self.levels[-1] - self.report("down") - level.moveto(level.curx, level.cury+self.stepy) - - def cmd_pageup(self): - """ - Move the cursor up one page. - """ - level = self.levels[-1] - self.report("page up") - level.moveto(level.curx, level.cury-level.mainsizey+self.pageoverlapy) - - def cmd_pagedown(self): - """ - Move the cursor down one page. - """ - level = self.levels[-1] - self.report("page down") - level.moveto(level.curx, level.cury+level.mainsizey-self.pageoverlapy) - - def cmd_left(self): - """ - Move the cursor left. - """ - level = self.levels[-1] - self.report("left") - level.moveto(level.curx-self.stepx, level.cury) - - def cmd_right(self): - """ - Move the cursor right. - """ - level = self.levels[-1] - self.report("right") - level.moveto(level.curx+self.stepx, level.cury) - - def cmd_home(self): - """ - Move the cursor to the first column. - """ - level = self.levels[-1] - self.report("home") - level.moveto(0, level.cury) - - def cmd_end(self): - """ - Move the cursor to the last column. - """ - level = self.levels[-1] - self.report("end") - level.moveto(level.datasizex+level.mainsizey-self.pageoverlapx, level.cury) - - def cmd_prevattr(self): - """ - Move the cursor one attribute column to the left. - """ - level = self.levels[-1] - if level.displayattr[0] is None or level.displayattr[0] == 0: - self.beep() - else: - self.report("prevattr") - pos = 0 - for (i, attrname) in enumerate(level.displayattrs): - if i == level.displayattr[0]-1: - break - pos += level.colwidths[attrname] + 1 - level.moveto(pos, level.cury) - - def cmd_nextattr(self): - """ - Move the cursor one attribute column to the right. - """ - level = self.levels[-1] - if level.displayattr[0] is None or level.displayattr[0] == len(level.displayattrs)-1: - self.beep() - else: - self.report("nextattr") - pos = 0 - for (i, attrname) in enumerate(level.displayattrs): - if i == level.displayattr[0]+1: - break - pos += level.colwidths[attrname] + 1 - level.moveto(pos, level.cury) - - def cmd_pick(self): - """ - 'Pick' the object under the cursor (i.e. the row the cursor is on). - This leaves the browser and returns the picked object to the caller. - (In IPython this object will be available as the ``_`` variable.) - """ - level = self.levels[-1] - self.returnvalue = level.items[level.cury].item - return True - - def cmd_pickattr(self): - """ - 'Pick' the attribute under the cursor (i.e. the row/column the - cursor is on). - """ - level = self.levels[-1] - attr = level.displayattr[1] - if attr is ipipe.noitem: - curses.beep() - self.report(CommandError("no column under cursor")) - return - value = attr.value(level.items[level.cury].item) - if value is ipipe.noitem: - curses.beep() - self.report(AttributeError(attr.name())) - else: - self.returnvalue = value - return True - - def cmd_pickallattrs(self): - """ - Pick' the complete column under the cursor (i.e. the attribute under - the cursor) from all currently fetched objects. These attributes - will be returned as a list. - """ - level = self.levels[-1] - attr = level.displayattr[1] - if attr is ipipe.noitem: - curses.beep() - self.report(CommandError("no column under cursor")) - return - result = [] - for cache in level.items: - value = attr.value(cache.item) - if value is not ipipe.noitem: - result.append(value) - self.returnvalue = result - return True - - def cmd_pickmarked(self): - """ - 'Pick' marked objects. Marked objects will be returned as a list. - """ - level = self.levels[-1] - self.returnvalue = [cache.item for cache in level.items if cache.marked] - return True - - def cmd_pickmarkedattr(self): - """ - 'Pick' the attribute under the cursor from all marked objects - (This returns a list). - """ - - level = self.levels[-1] - attr = level.displayattr[1] - if attr is ipipe.noitem: - curses.beep() - self.report(CommandError("no column under cursor")) - return - result = [] - for cache in level.items: - if cache.marked: - value = attr.value(cache.item) - if value is not ipipe.noitem: - result.append(value) - self.returnvalue = result - return True - - def cmd_pickinput(self): - """ - Use the object under the cursor (i.e. the row the cursor is on) as - the next input line. This leaves the browser and puts the picked object - in the input. - """ - level = self.levels[-1] - value = level.items[level.cury].item - self.returnvalue = None - api = ipapi.get() - api.set_next_input(str(value)) - return True - - def cmd_pickinputattr(self): - """ - Use the attribute under the cursor i.e. the row/column the cursor is on) - as the next input line. This leaves the browser and puts the picked - object in the input. - """ - level = self.levels[-1] - attr = level.displayattr[1] - if attr is ipipe.noitem: - curses.beep() - self.report(CommandError("no column under cursor")) - return - value = attr.value(level.items[level.cury].item) - if value is ipipe.noitem: - curses.beep() - self.report(AttributeError(attr.name())) - self.returnvalue = None - api = ipapi.get() - api.set_next_input(str(value)) - return True - - def cmd_markrange(self): - """ - Mark all objects from the last marked object before the current cursor - position to the cursor position. - """ - level = self.levels[-1] - self.report("markrange") - start = None - if level.items: - for i in xrange(level.cury, -1, -1): - if level.items[i].marked: - start = i - break - if start is None: - self.report(CommandError("no mark before cursor")) - curses.beep() - else: - for i in xrange(start, level.cury+1): - cache = level.items[i] - if not cache.marked: - cache.marked = True - level.marked += 1 - - def cmd_enter(self): - """ - Enter the object under the cursor. (what this mean depends on the object - itself (i.e. how it implements iteration). This opens a new browser 'level'. - """ - level = self.levels[-1] - try: - item = level.items[level.cury].item - except IndexError: - self.report(CommandError("No object")) - curses.beep() - else: - self.report("entering object...") - self.enter(item) - - def cmd_leave(self): - """ - Leave the current browser level and go back to the previous one. - """ - self.report("leave") - if len(self.levels) > 1: - self._calcheaderlines(len(self.levels)-1) - self.levels.pop(-1) - else: - self.report(CommandError("This is the last level")) - curses.beep() - - def cmd_enterattr(self): - """ - Enter the attribute under the cursor. - """ - level = self.levels[-1] - attr = level.displayattr[1] - if attr is ipipe.noitem: - curses.beep() - self.report(CommandError("no column under cursor")) - return - try: - item = level.items[level.cury].item - except IndexError: - self.report(CommandError("No object")) - curses.beep() - else: - value = attr.value(item) - name = attr.name() - if value is ipipe.noitem: - self.report(AttributeError(name)) - else: - self.report("entering object attribute %s..." % name) - self.enter(value) - - def cmd_detail(self): - """ - Show a detail view of the object under the cursor. This shows the - name, type, doc string and value of the object attributes (and it - might show more attributes than in the list view, depending on - the object). - """ - level = self.levels[-1] - try: - item = level.items[level.cury].item - except IndexError: - self.report(CommandError("No object")) - curses.beep() - else: - self.report("entering detail view for object...") - attrs = [ipipe.AttributeDetail(item, attr) for attr in ipipe.xattrs(item, "detail")] - self.enter(attrs) - - def cmd_detailattr(self): - """ - Show a detail view of the attribute under the cursor. - """ - level = self.levels[-1] - attr = level.displayattr[1] - if attr is ipipe.noitem: - curses.beep() - self.report(CommandError("no attribute")) - return - try: - item = level.items[level.cury].item - except IndexError: - self.report(CommandError("No object")) - curses.beep() - else: - try: - item = attr.value(item) - except (KeyboardInterrupt, SystemExit): - raise - except Exception as exc: - self.report(exc) - else: - self.report("entering detail view for attribute %s..." % attr.name()) - attrs = [ipipe.AttributeDetail(item, attr) for attr in ipipe.xattrs(item, "detail")] - self.enter(attrs) - - def cmd_tooglemark(self): - """ - Mark/unmark the object under the cursor. Marked objects have a '!' - after the row number). - """ - level = self.levels[-1] - self.report("toggle mark") - try: - item = level.items[level.cury] - except IndexError: # no items? - pass - else: - if item.marked: - item.marked = False - level.marked -= 1 - else: - item.marked = True - level.marked += 1 - - def cmd_sortattrasc(self): - """ - Sort the objects (in ascending order) using the attribute under - the cursor as the sort key. - """ - level = self.levels[-1] - attr = level.displayattr[1] - if attr is ipipe.noitem: - curses.beep() - self.report(CommandError("no column under cursor")) - return - self.report("sort by %s (ascending)" % attr.name()) - def key(item): - try: - return attr.value(item) - except (KeyboardInterrupt, SystemExit): - raise - except Exception: - return None - level.sort(key) - - def cmd_sortattrdesc(self): - """ - Sort the objects (in descending order) using the attribute under - the cursor as the sort key. - """ - level = self.levels[-1] - attr = level.displayattr[1] - if attr is ipipe.noitem: - curses.beep() - self.report(CommandError("no column under cursor")) - return - self.report("sort by %s (descending)" % attr.name()) - def key(item): - try: - return attr.value(item) - except (KeyboardInterrupt, SystemExit): - raise - except Exception: - return None - level.sort(key, reverse=True) - - def cmd_hideattr(self): - """ - Hide the attribute under the cursor. - """ - level = self.levels[-1] - if level.displayattr[0] is None: - self.beep() - else: - self.report("hideattr") - level.hiddenattrs.add(level.displayattr[1]) - level.moveto(level.curx, level.cury, refresh=True) - - def cmd_unhideattrs(self): - """ - Make all attributes visible again. - """ - level = self.levels[-1] - self.report("unhideattrs") - level.hiddenattrs.clear() - level.moveto(level.curx, level.cury, refresh=True) - - def cmd_goto(self): - """ - Jump to a row. The row number can be entered at the - bottom of the screen. - """ - self.startkeyboardinput("goto") - - def cmd_find(self): - """ - Search forward for a row. The search condition can be entered at the - bottom of the screen. - """ - self.startkeyboardinput("find") - - def cmd_findbackwards(self): - """ - Search backward for a row. The search condition can be entered at the - bottom of the screen. - """ - self.startkeyboardinput("findbackwards") - - def cmd_refresh(self): - """ - Refreshes the display by restarting the iterator. - """ - level = self.levels[-1] - self.report("refresh") - level.refresh() - - def cmd_refreshfind(self): - """ - Refreshes the display by restarting the iterator and goes back to the - same object the cursor was on before restarting (if this object can't be - found the cursor jumps back to the first object). - """ - level = self.levels[-1] - self.report("refreshfind") - level.refreshfind() - - def cmd_help(self): - """ - Opens the help screen as a new browser level, describing keyboard - shortcuts. - """ - for level in self.levels: - if isinstance(level.input, _BrowserHelp): - curses.beep() - self.report(CommandError("help already active")) - return - - self.enter(_BrowserHelp(self)) - - def cmd_quit(self): - """ - Quit the browser and return to the IPython prompt. - """ - self.returnvalue = None - return True - - def sigwinchhandler(self, signal, frame): - self.resized = True - - def _dodisplay(self, scr): - """ - This method is the workhorse of the browser. It handles screen - drawing and the keyboard. - """ - self.scr = scr - curses.halfdelay(1) - footery = 2 - - keys = [] - for cmd in ("quit", "help"): - key = self.keymap.findkey(cmd, None) - if key is not None: - keys.append("%s=%s" % (self.keylabel(key), cmd)) - helpmsg = " | %s" % " ".join(keys) - - scr.clear() - msg = "Fetching first batch of objects..." - (self.scrsizey, self.scrsizex) = scr.getmaxyx() - scr.addstr(self.scrsizey//2, (self.scrsizex-len(msg))//2, msg) - scr.refresh() - - lastc = -1 - - self.levels = [] - # enter the first level - self.enter(self.input, *self.attrs) - - self._calcheaderlines(None) - - while True: - level = self.levels[-1] - (self.scrsizey, self.scrsizex) = scr.getmaxyx() - level.mainsizey = self.scrsizey-1-self._headerlines-footery - - # Paint object header - for i in xrange(self._firstheaderline, self._firstheaderline+self._headerlines): - lv = self.levels[i] - posx = 0 - posy = i-self._firstheaderline - endx = self.scrsizex - if i: # not the first level - msg = " (%d/%d" % (self.levels[i-1].cury, len(self.levels[i-1].items)) - if not self.levels[i-1].exhausted: - msg += "+" - msg += ") " - endx -= len(msg)+1 - posx += self.addstr(posy, posx, 0, endx, " ibrowse #%d: " % i, self.style_objheadertext) - for (style, text) in lv.header: - posx += self.addstr(posy, posx, 0, endx, text, self.style_objheaderobject) - if posx >= endx: - break - if i: - posx += self.addstr(posy, posx, 0, self.scrsizex, msg, self.style_objheadernumber) - posx += self.addchr(posy, posx, 0, self.scrsizex, " ", self.scrsizex-posx, self.style_objheadernumber) - - if not level.items: - self.addchr(self._headerlines, 0, 0, self.scrsizex, " ", self.scrsizex, self.style_colheader) - self.addstr(self._headerlines+1, 0, 0, self.scrsizex, " <empty>", astyle.style_error) - scr.clrtobot() - else: - # Paint column headers - scr.move(self._headerlines, 0) - scr.addstr(" %*s " % (level.numbersizex, "#"), self.getstyle(self.style_colheader)) - scr.addstr(self.headersepchar, self.getstyle(self.style_colheadersep)) - begx = level.numbersizex+3 - posx = begx-level.datastartx - for attr in level.displayattrs: - attrname = attr.name() - cwidth = level.colwidths[attr] - header = attrname.ljust(cwidth) - if attr is level.displayattr[1]: - style = self.style_colheaderhere - else: - style = self.style_colheader - posx += self.addstr(self._headerlines, posx, begx, self.scrsizex, header, style) - posx += self.addstr(self._headerlines, posx, begx, self.scrsizex, self.headersepchar, self.style_colheadersep) - if posx >= self.scrsizex: - break - else: - scr.addstr(" "*(self.scrsizex-posx), self.getstyle(self.style_colheader)) - - # Paint rows - posy = self._headerlines+1+level.datastarty - for i in xrange(level.datastarty, min(level.datastarty+level.mainsizey, len(level.items))): - cache = level.items[i] - if i == level.cury: - style = self.style_numberhere - else: - style = self.style_number - - posy = self._headerlines+1+i-level.datastarty - posx = begx-level.datastartx - - scr.move(posy, 0) - scr.addstr(" %*d%s" % (level.numbersizex, i, " !"[cache.marked]), self.getstyle(style)) - scr.addstr(self.headersepchar, self.getstyle(self.style_sep)) - - for attrname in level.displayattrs: - cwidth = level.colwidths[attrname] - try: - (align, length, parts) = level.displayrows[i-level.datastarty][attrname] - except KeyError: - align = 2 - style = astyle.style_nodata - if i == level.cury: - style = self.getstylehere(style) - padstyle = self.style_datapad - sepstyle = self.style_sep - if i == level.cury: - padstyle = self.getstylehere(padstyle) - sepstyle = self.getstylehere(sepstyle) - if align == 2: - posx += self.addchr(posy, posx, begx, self.scrsizex, self.nodatachar, cwidth, style) - else: - if align == 1: - posx += self.addchr(posy, posx, begx, self.scrsizex, self.datapadchar, cwidth-length, padstyle) - elif align == 0: - pad1 = (cwidth-length)//2 - pad2 = cwidth-length-len(pad1) - posx += self.addchr(posy, posx, begx, self.scrsizex, self.datapadchar, pad1, padstyle) - for (style, text) in parts: - if i == level.cury: - style = self.getstylehere(style) - posx += self.addstr(posy, posx, begx, self.scrsizex, text, style) - if posx >= self.scrsizex: - break - if align == -1: - posx += self.addchr(posy, posx, begx, self.scrsizex, self.datapadchar, cwidth-length, padstyle) - elif align == 0: - posx += self.addchr(posy, posx, begx, self.scrsizex, self.datapadchar, pad2, padstyle) - posx += self.addstr(posy, posx, begx, self.scrsizex, self.datasepchar, sepstyle) - else: - scr.clrtoeol() - - # Add blank row headers for the rest of the screen - for posy in xrange(posy+1, self.scrsizey-2): - scr.addstr(posy, 0, " " * (level.numbersizex+2), self.getstyle(self.style_colheader)) - scr.clrtoeol() - - posy = self.scrsizey-footery - # Display footer - scr.addstr(posy, 0, " "*self.scrsizex, self.getstyle(self.style_footer)) - - if level.exhausted: - flag = "" - else: - flag = "+" - - endx = self.scrsizex-len(helpmsg)-1 - scr.addstr(posy, endx, helpmsg, self.getstyle(self.style_footer)) - - posx = 0 - msg = " %d%s objects (%d marked): " % (len(level.items), flag, level.marked) - posx += self.addstr(posy, posx, 0, endx, msg, self.style_footer) - try: - item = level.items[level.cury].item - except IndexError: # empty - pass - else: - for (nostyle, text) in ipipe.xrepr(item, "footer"): - if not isinstance(nostyle, int): - posx += self.addstr(posy, posx, 0, endx, text, self.style_footer) - if posx >= endx: - break - - attrstyle = [(astyle.style_default, "no attribute")] - attr = level.displayattr[1] - if attr is not ipipe.noitem and not isinstance(attr, ipipe.SelfDescriptor): - posx += self.addstr(posy, posx, 0, endx, " | ", self.style_footer) - posx += self.addstr(posy, posx, 0, endx, attr.name(), self.style_footer) - posx += self.addstr(posy, posx, 0, endx, ": ", self.style_footer) - try: - value = attr.value(item) - except (SystemExit, KeyboardInterrupt): - raise - except Exception as exc: - value = exc - if value is not ipipe.noitem: - attrstyle = ipipe.xrepr(value, "footer") - for (nostyle, text) in attrstyle: - if not isinstance(nostyle, int): - posx += self.addstr(posy, posx, 0, endx, text, self.style_footer) - if posx >= endx: - break - - try: - # Display input prompt - if self.mode in self.prompts: - history = self.prompts[self.mode] - posx = 0 - posy = self.scrsizey-1 - posx += self.addstr(posy, posx, 0, endx, history.prompt, astyle.style_default) - posx += self.addstr(posy, posx, 0, endx, " [", astyle.style_default) - if history.cury==-1: - text = "new" - else: - text = str(history.cury+1) - posx += self.addstr(posy, posx, 0, endx, text, astyle.style_type_number) - if history.history: - posx += self.addstr(posy, posx, 0, endx, "/", astyle.style_default) - posx += self.addstr(posy, posx, 0, endx, str(len(history.history)), astyle.style_type_number) - posx += self.addstr(posy, posx, 0, endx, "]: ", astyle.style_default) - inputstartx = posx - posx += self.addstr(posy, posx, 0, endx, history.input, astyle.style_default) - # Display report - else: - if self._report is not None: - if isinstance(self._report, Exception): - style = self.getstyle(astyle.style_error) - if self._report.__class__.__module__ == "exceptions": - msg = "%s: %s" % \ - (self._report.__class__.__name__, self._report) - else: - msg = "%s.%s: %s" % \ - (self._report.__class__.__module__, - self._report.__class__.__name__, self._report) - else: - style = self.getstyle(self.style_report) - msg = self._report - scr.addstr(self.scrsizey-1, 0, msg[:self.scrsizex], style) - self._report = None - else: - scr.move(self.scrsizey-1, 0) - except curses.error: - # Protect against errors from writing to the last line - pass - scr.clrtoeol() - - # Position cursor - if self.mode in self.prompts: - history = self.prompts[self.mode] - scr.move(self.scrsizey-1, inputstartx+history.curx) - else: - scr.move( - 1+self._headerlines+level.cury-level.datastarty, - level.numbersizex+3+level.curx-level.datastartx - ) - scr.refresh() - - # Check keyboard - while True: - c = scr.getch() - if self.resized: - size = fcntl.ioctl(0, tty.TIOCGWINSZ, "12345678") - size = struct.unpack("4H", size) - oldsize = scr.getmaxyx() - scr.erase() - curses.resize_term(size[0], size[1]) - newsize = scr.getmaxyx() - scr.erase() - for l in self.levels: - l.mainsizey += newsize[0]-oldsize[0] - l.moveto(l.curx, l.cury, refresh=True) - scr.refresh() - self.resized = False - break # Redisplay - if self.mode in self.prompts: - if self.prompts[self.mode].handlekey(self, c): - break # Redisplay - else: - # if no key is pressed slow down and beep again - if c == -1: - self.stepx = 1. - self.stepy = 1. - self._dobeep = True - else: - # if a different key was pressed slow down and beep too - if c != lastc: - lastc = c - self.stepx = 1. - self.stepy = 1. - self._dobeep = True - cmdname = self.keymap.get(c, None) - if cmdname is None: - self.report( - UnassignedKeyError("Unassigned key %s" % - self.keylabel(c))) - else: - cmdfunc = getattr(self, "cmd_%s" % cmdname, None) - if cmdfunc is None: - self.report( - UnknownCommandError("Unknown command %r" % - (cmdname,))) - elif cmdfunc(): - returnvalue = self.returnvalue - self.returnvalue = None - return returnvalue - self.stepx = self.nextstepx(self.stepx) - self.stepy = self.nextstepy(self.stepy) - curses.flushinp() # get rid of type ahead - break # Redisplay - self.scr = None - - def display(self): - if hasattr(curses, "resize_term") and hasattr(signal, 'SIGWINCH'): - oldhandler = signal.signal(signal.SIGWINCH, self.sigwinchhandler) - try: - return curses.wrapper(self._dodisplay) - finally: - signal.signal(signal.SIGWINCH, oldhandler) - else: - return curses.wrapper(self._dodisplay) diff --git a/IPython/deathrow/igrid.py b/IPython/deathrow/igrid.py deleted file mode 100644 index 9026102..0000000 --- a/IPython/deathrow/igrid.py +++ /dev/null @@ -1,1126 +0,0 @@ -# -*- coding: iso-8859-1 -*- - -import ipipe, os, webbrowser, urllib -from IPython.core import ipapi -import wx -import wx.grid, wx.html - -try: - sorted -except NameError: - from ipipe import sorted -try: - set -except: - from sets import Set as set - - -__all__ = ["igrid"] - - -help = """ -<?xml version='1.0' encoding='iso-8859-1'?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> -<link rel="stylesheet" href="igrid_help.css" type="text/css" /> -<title>igrid help</title> -</head> -<body> -<h1>igrid help</h1> - - -<h2>Commands</h2> - - -<h3>pick (P)</h3> -<p>Pick the whole row (object is available as "_")</p> - -<h3>pickattr (Shift-P)</h3> -<p>Pick the attribute under the cursor</p> - -<h3>pickallattrs (Shift-C)</h3> -<p>Pick the complete column under the cursor (i.e. the attribute under the -cursor) from all currently fetched objects. These attributes will be returned -as a list.</p> - -<h3>pickinput (I)</h3> -<p>Pick the current row as next input line in IPython. Additionally the row is stored as "_"</p> - -<h3>pickinputattr (Shift-I)</h3> -<p>Pick the attribute under the cursor as next input line in IPython. Additionally the row is stored as "_"</p> - -<h3>enter (E)</h3> -<p>Enter the object under the cursor. (what this mean depends on the object -itself, i.e. how it implements iteration). This opens a new browser 'level'.</p> - -<h3>enterattr (Shift-E)</h3> -<p>Enter the attribute under the cursor.</p> - -<h3>detail (D)</h3> -<p>Show a detail view of the object under the cursor. This shows the name, -type, doc string and value of the object attributes (and it might show more -attributes than in the list view, depending on the object).</p> - -<h3>detailattr (Shift-D)</h3> -<p>Show a detail view of the attribute under the cursor.</p> - -<h3>pickrows (M)</h3> -<p>Pick multiple selected rows (M)</p> - -<h3>pickrowsattr (CTRL-M)</h3> -<p>From multiple selected rows pick the cells matching the attribute the cursor is in (CTRL-M)</p> - -<h3>find (CTRL-F)</h3> -<p>Find text</p> - -<h3>find_expression (CTRL-Shift-F)</h3> -<p>Find entries matching an expression</p> - -<h3>find_next (F3)</h3> -<p>Find next occurrence</p> - -<h3>find_previous (Shift-F3)</h3> -<p>Find previous occurrence</p> - -<h3>sortattrasc (V)</h3> -<p>Sort the objects (in ascending order) using the attribute under the cursor as the sort key.</p> - -<h3>sortattrdesc (Shift-V)</h3> -<p>Sort the objects (in descending order) using the attribute under the cursor as the sort key.</p> - -<h3>refresh_once (R, F5)</h3> -<p>Refreshes the display by restarting the iterator</p> - -<h3>refresh_every_second</h3> -<p>Refreshes the display by restarting the iterator every second until stopped by stop_refresh.</p> - -<h3>refresh_interval</h3> -<p>Refreshes the display by restarting the iterator every X ms (X is a custom interval set by the user) until stopped by stop_refresh.</p> - -<h3>stop_refresh</h3> -<p>Stops all refresh timers.</p> - -<h3>leave (Backspace, DEL, X)</h3> -<p>Close current tab (and all the tabs to the right of the current one).</h3> - -<h3>quit (ESC,Q)</h3> -<p>Quit igrid and return to the IPython prompt.</p> - - -<h2>Navigation</h2> - - -<h3>Jump to the last column of the current row (END, CTRL-E, CTRL-Right)</h3> - -<h3>Jump to the first column of the current row (HOME, CTRL-A, CTRL-Left)</h3> - -<h3>Move the cursor one column to the left (<)</h3> - -<h3>Move the cursor one column to the right (>)</h3> - -<h3>Jump to the first row in the current column (CTRL-Up)</h3> - -<h3>Jump to the last row in the current column (CTRL-Down)</h3> - -</body> -</html> - -""" - - -class IGridRenderer(wx.grid.PyGridCellRenderer): - """ - This is a custom renderer for our IGridGrid - """ - def __init__(self, table): - self.maxchars = 200 - self.table = table - self.colormap = ( - ( 0, 0, 0), - (174, 0, 0), - ( 0, 174, 0), - (174, 174, 0), - ( 0, 0, 174), - (174, 0, 174), - ( 0, 174, 174), - ( 64, 64, 64) - ) - - wx.grid.PyGridCellRenderer.__init__(self) - - def _getvalue(self, row, col): - try: - value = self.table._displayattrs[col].value(self.table.items[row]) - (align, width, text) = ipipe.xformat(value, "cell", self.maxchars) - except Exception as exc: - (align, width, text) = ipipe.xformat(exc, "cell", self.maxchars) - return (align, text) - - def GetBestSize(self, grid, attr, dc, row, col): - text = grid.GetCellValue(row, col) - (align, text) = self._getvalue(row, col) - dc.SetFont(attr.GetFont()) - (w, h) = dc.GetTextExtent(str(text)) - return wx.Size(min(w+2, 600), h+2) # add border - - def Draw(self, grid, attr, dc, rect, row, col, isSelected): - """ - Takes care of drawing everything in the cell; aligns the text - """ - text = grid.GetCellValue(row, col) - (align, text) = self._getvalue(row, col) - if isSelected: - bg = grid.GetSelectionBackground() - else: - bg = ["white", (240, 240, 240)][row%2] - dc.SetTextBackground(bg) - dc.SetBrush(wx.Brush(bg, wx.SOLID)) - dc.SetPen(wx.TRANSPARENT_PEN) - dc.SetFont(attr.GetFont()) - dc.DrawRectangleRect(rect) - dc.SetClippingRect(rect) - # Format the text - if align == -1: # left alignment - (width, height) = dc.GetTextExtent(str(text)) - x = rect[0]+1 - y = rect[1]+0.5*(rect[3]-height) - - for (style, part) in text: - if isSelected: - fg = grid.GetSelectionForeground() - else: - fg = self.colormap[style.fg] - dc.SetTextForeground(fg) - (w, h) = dc.GetTextExtent(part) - dc.DrawText(part, x, y) - x += w - elif align == 0: # center alignment - (width, height) = dc.GetTextExtent(str(text)) - x = rect[0]+0.5*(rect[2]-width) - y = rect[1]+0.5*(rect[3]-height) - for (style, part) in text: - if isSelected: - fg = grid.GetSelectionForeground() - else: - fg = self.colormap[style.fg] - dc.SetTextForeground(fg) - (w, h) = dc.GetTextExtent(part) - dc.DrawText(part, x, y) - x += w - else: # right alignment - (width, height) = dc.GetTextExtent(str(text)) - x = rect[0]+rect[2]-1 - y = rect[1]+0.5*(rect[3]-height) - for (style, part) in reversed(text): - (w, h) = dc.GetTextExtent(part) - x -= w - if isSelected: - fg = grid.GetSelectionForeground() - else: - fg = self.colormap[style.fg] - dc.SetTextForeground(fg) - dc.DrawText(part, x, y) - dc.DestroyClippingRegion() - - def Clone(self): - return IGridRenderer(self.table) - - -class IGridTable(wx.grid.PyGridTableBase): - # The data table for the ``IGridGrid``. Some dirty tricks were used here: - # ``GetValue()`` does not get any values (or at least it does not return - # anything, accessing the values is done by the renderer) - # but rather tries to fetch the objects which were requested into the table. - # General behaviour is: Fetch the first X objects. If the user scrolls down - # to the last object another bunch of X objects is fetched (if possible) - def __init__(self, input, fontsize, *attrs): - wx.grid.PyGridTableBase.__init__(self) - self.input = input - self.iterator = ipipe.xiter(input) - self.items = [] - self.attrs = [ipipe.upgradexattr(attr) for attr in attrs] - self._displayattrs = self.attrs[:] - self._displayattrset = set(self.attrs) - self.fontsize = fontsize - self._fetch(1) - self.timer = wx.Timer() - self.timer.Bind(wx.EVT_TIMER, self.refresh_content) - - def GetAttr(self, *args): - attr = wx.grid.GridCellAttr() - attr.SetFont(wx.Font(self.fontsize, wx.TELETYPE, wx.NORMAL, wx.NORMAL)) - return attr - - def GetNumberRows(self): - return len(self.items) - - def GetNumberCols(self): - return len(self._displayattrs) - - def GetColLabelValue(self, col): - if col < len(self._displayattrs): - return self._displayattrs[col].name() - else: - return "" - - def GetRowLabelValue(self, row): - return str(row) - - def IsEmptyCell(self, row, col): - return False - - def _append(self, item): - self.items.append(item) - # Nothing to do if the set of attributes has been fixed by the user - if not self.attrs: - for attr in ipipe.xattrs(item): - attr = ipipe.upgradexattr(attr) - if attr not in self._displayattrset: - self._displayattrs.append(attr) - self._displayattrset.add(attr) - - def _fetch(self, count): - # Try to fill ``self.items`` with at least ``count`` objects. - have = len(self.items) - while self.iterator is not None and have < count: - try: - item = self.iterator.next() - except StopIteration: - self.iterator = None - break - except (KeyboardInterrupt, SystemExit): - raise - except Exception as exc: - have += 1 - self._append(exc) - self.iterator = None - break - else: - have += 1 - self._append(item) - - def GetValue(self, row, col): - # some kind of dummy-function: does not return anything but ""; - # (The value isn't use anyway) - # its main task is to trigger the fetch of new objects - sizing_needed = False - had_cols = len(self._displayattrs) - had_rows = len(self.items) - if row == had_rows - 1 and self.iterator is not None: - self._fetch(row + 20) - sizing_needed = True - have_rows = len(self.items) - have_cols = len(self._displayattrs) - if have_rows > had_rows: - msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED, have_rows - had_rows) - self.GetView().ProcessTableMessage(msg) - sizing_needed = True - if row >= have_rows: - return "" - if have_cols != had_cols: - msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_NOTIFY_COLS_APPENDED, have_cols - had_cols) - self.GetView().ProcessTableMessage(msg) - sizing_needed = True - if sizing_needed: - self.GetView().AutoSizeColumns(False) - return "" - - def SetValue(self, row, col, value): - pass - - def refresh_content(self, event): - msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED, 0, self.GetNumberRows()) - self.GetView().ProcessTableMessage(msg) - self.iterator = ipipe.xiter(self.input) - self.items = [] - self.attrs = [] # _append will calculate new displayattrs - self._fetch(1) # fetch one... - if self.items: - msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED, 1) - self.GetView().ProcessTableMessage(msg) - self.GetValue(0, 0) # and trigger "fetch next 20" - item = self.items[0] - self.GetView().AutoSizeColumns(False) - panel = self.GetView().GetParent() - nb = panel.GetParent() - current = nb.GetSelection() - if nb.GetPage(current) == panel: - self.GetView().set_footer(item) - -class IGridGrid(wx.grid.Grid): - # The actual grid - # all methods for selecting/sorting/picking/... data are implemented here - def __init__(self, panel, input, *attrs): - wx.grid.Grid.__init__(self, panel) - fontsize = 9 - self.input = input - self.table = IGridTable(self.input, fontsize, *attrs) - self.SetTable(self.table, True) - self.SetSelectionMode(wx.grid.Grid.wxGridSelectRows) - self.SetDefaultRenderer(IGridRenderer(self.table)) - self.EnableEditing(False) - self.Bind(wx.EVT_KEY_DOWN, self.key_pressed) - self.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.cell_doubleclicked) - self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.cell_leftclicked) - self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_DCLICK, self.label_doubleclicked) - self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.on_label_leftclick) - self.Bind(wx.grid.EVT_GRID_RANGE_SELECT, self._on_selected_range) - self.Bind(wx.grid.EVT_GRID_SELECT_CELL, self._on_selected_cell) - self.current_selection = set() - self.maxchars = 200 - - def on_label_leftclick(self, event): - event.Skip() - - def error_output(self, text): - wx.Bell() - frame = self.GetParent().GetParent().GetParent() - frame.SetStatusText(str(text)) - - def _on_selected_range(self, event): - # Internal update to the selection tracking lists - if event.Selecting(): - # adding to the list... - self.current_selection.update(xrange(event.GetTopRow(), event.GetBottomRow()+1)) - else: - # removal from list - for index in xrange(event.GetTopRow(), event.GetBottomRow()+1): - self.current_selection.discard(index) - event.Skip() - - def _on_selected_cell(self, event): - # Internal update to the selection tracking list - self.current_selection = set([event.GetRow()]) - event.Skip() - - def sort(self, key, reverse=False): - """ - Sort the current list of items using the key function ``key``. If - ``reverse`` is true the sort order is reversed. - """ - row = self.GetGridCursorRow() - col = self.GetGridCursorCol() - curitem = self.table.items[row] # Remember where the cursor is now - # Sort items - def realkey(item): - try: - return key(item) - except (KeyboardInterrupt, SystemExit): - raise - except Exception: - return None - try: - self.table.items = ipipe.deque(sorted(self.table.items, key=realkey, reverse=reverse)) - except TypeError as exc: - self.error_output("Exception encountered: %s" % exc) - return - # Find out where the object under the cursor went - for (i, item) in enumerate(self.table.items): - if item is curitem: - self.SetGridCursor(i,col) - self.MakeCellVisible(i,col) - self.Refresh() - - def sortattrasc(self): - """ - Sort in ascending order; sorting criteria is the current attribute - """ - col = self.GetGridCursorCol() - attr = self.table._displayattrs[col] - frame = self.GetParent().GetParent().GetParent() - if attr is ipipe.noitem: - self.error_output("no column under cursor") - return - frame.SetStatusText("sort by %s (ascending)" % attr.name()) - def key(item): - try: - return attr.value(item) - except (KeyboardInterrupt, SystemExit): - raise - except Exception: - return None - self.sort(key) - - def sortattrdesc(self): - """ - Sort in descending order; sorting criteria is the current attribute - """ - col = self.GetGridCursorCol() - attr = self.table._displayattrs[col] - frame = self.GetParent().GetParent().GetParent() - if attr is ipipe.noitem: - self.error_output("no column under cursor") - return - frame.SetStatusText("sort by %s (descending)" % attr.name()) - def key(item): - try: - return attr.value(item) - except (KeyboardInterrupt, SystemExit): - raise - except Exception: - return None - self.sort(key, reverse=True) - - def label_doubleclicked(self, event): - row = event.GetRow() - col = event.GetCol() - if col == -1: - self.enter(row) - - def _getvalue(self, row, col): - """ - Gets the text which is displayed at ``(row, col)`` - """ - try: - value = self.table._displayattrs[col].value(self.table.items[row]) - (align, width, text) = ipipe.xformat(value, "cell", self.maxchars) - except IndexError: - raise IndexError - except Exception as exc: - (align, width, text) = ipipe.xformat(exc, "cell", self.maxchars) - return text - - def searchexpression(self, searchexp, startrow=None, search_forward=True ): - """ - Find by expression - """ - frame = self.GetParent().GetParent().GetParent() - if searchexp: - if search_forward: - if not startrow: - row = self.GetGridCursorRow()+1 - else: - row = startrow + 1 - while True: - try: - foo = self.table.GetValue(row, 0) - item = self.table.items[row] - try: - globals = ipipe.getglobals(None) - if eval(searchexp, globals, ipipe.AttrNamespace(item)): - self.SetGridCursor(row, 0) # found something - self.MakeCellVisible(row, 0) - break - except (KeyboardInterrupt, SystemExit): - raise - except Exception as exc: - frame.SetStatusText(str(exc)) - wx.Bell() - break # break on error - except IndexError: - return - row += 1 - else: - if not startrow: - row = self.GetGridCursorRow() - 1 - else: - row = startrow - 1 - while True: - try: - foo = self.table.GetValue(row, 0) - item = self.table.items[row] - try: - globals = ipipe.getglobals(None) - if eval(searchexp, globals, ipipe.AttrNamespace(item)): - self.SetGridCursor(row, 0) # found something - self.MakeCellVisible(row, 0) - break - except (KeyboardInterrupt, SystemExit): - raise - except Exception as exc: - frame.SetStatusText(str(exc)) - wx.Bell() - break # break on error - except IndexError: - return - row -= 1 - - - def search(self, searchtext, startrow=None, startcol=None, search_forward=True): - """ - search for ``searchtext``, starting in ``(startrow, startcol)``; - if ``search_forward`` is true the direction is "forward" - """ - searchtext = searchtext.lower() - if search_forward: - if startrow is not None and startcol is not None: - row = startrow - else: - startcol = self.GetGridCursorCol() + 1 - row = self.GetGridCursorRow() - if startcol >= self.GetNumberCols(): - startcol = 0 - row += 1 - while True: - for col in xrange(startcol, self.table.GetNumberCols()): - try: - foo = self.table.GetValue(row, col) - text = self._getvalue(row, col) - if searchtext in text.string().lower(): - self.SetGridCursor(row, col) - self.MakeCellVisible(row, col) - return - except IndexError: - return - startcol = 0 - row += 1 - else: - if startrow is not None and startcol is not None: - row = startrow - else: - startcol = self.GetGridCursorCol() - 1 - row = self.GetGridCursorRow() - if startcol < 0: - startcol = self.GetNumberCols() - 1 - row -= 1 - while True: - for col in xrange(startcol, -1, -1): - try: - foo = self.table.GetValue(row, col) - text = self._getvalue(row, col) - if searchtext in text.string().lower(): - self.SetGridCursor(row, col) - self.MakeCellVisible(row, col) - return - except IndexError: - return - startcol = self.table.GetNumberCols()-1 - row -= 1 - - def key_pressed(self, event): - """ - Maps pressed keys to functions - """ - frame = self.GetParent().GetParent().GetParent() - frame.SetStatusText("") - sh = event.ShiftDown() - ctrl = event.ControlDown() - - keycode = event.GetKeyCode() - if keycode == ord("P"): - row = self.GetGridCursorRow() - if sh: - col = self.GetGridCursorCol() - self.pickattr(row, col) - else: - self.pick(row) - elif keycode == ord("M"): - if ctrl: - col = self.GetGridCursorCol() - self.pickrowsattr(sorted(self.current_selection), col) - else: - self.pickrows(sorted(self.current_selection)) - elif keycode in (wx.WXK_BACK, wx.WXK_DELETE, ord("X")) and not (ctrl or sh): - self.delete_current_notebook() - elif keycode in (ord("E"), ord("\r")): - row = self.GetGridCursorRow() - if sh: - col = self.GetGridCursorCol() - self.enterattr(row, col) - else: - self.enter(row) - elif keycode == ord("E") and ctrl: - row = self.GetGridCursorRow() - self.SetGridCursor(row, self.GetNumberCols()-1) - elif keycode == wx.WXK_HOME or (keycode == ord("A") and ctrl): - row = self.GetGridCursorRow() - self.SetGridCursor(row, 0) - elif keycode == ord("C") and sh: - col = self.GetGridCursorCol() - attr = self.table._displayattrs[col] - result = [] - for i in xrange(self.GetNumberRows()): - result.append(self.table._displayattrs[col].value(self.table.items[i])) - self.quit(result) - elif keycode in (wx.WXK_ESCAPE, ord("Q")) and not (ctrl or sh): - self.quit() - elif keycode == ord("<"): - row = self.GetGridCursorRow() - col = self.GetGridCursorCol() - if not event.ShiftDown(): - newcol = col - 1 - if newcol >= 0: - self.SetGridCursor(row, col - 1) - else: - newcol = col + 1 - if newcol < self.GetNumberCols(): - self.SetGridCursor(row, col + 1) - elif keycode == ord("D"): - col = self.GetGridCursorCol() - row = self.GetGridCursorRow() - if not sh: - self.detail(row, col) - else: - self.detail_attr(row, col) - elif keycode == ord("F") and ctrl: - if sh: - frame.enter_searchexpression(event) - else: - frame.enter_searchtext(event) - elif keycode == wx.WXK_F3: - if sh: - frame.find_previous(event) - else: - frame.find_next(event) - elif keycode == ord("V"): - if sh: - self.sortattrdesc() - else: - self.sortattrasc() - elif keycode == wx.WXK_DOWN: - row = self.GetGridCursorRow() - try: - item = self.table.items[row+1] - except IndexError: - item = self.table.items[row] - self.set_footer(item) - event.Skip() - elif keycode == wx.WXK_UP: - row = self.GetGridCursorRow() - if row >= 1: - item = self.table.items[row-1] - else: - item = self.table.items[row] - self.set_footer(item) - event.Skip() - elif keycode == wx.WXK_RIGHT: - row = self.GetGridCursorRow() - item = self.table.items[row] - self.set_footer(item) - event.Skip() - elif keycode == wx.WXK_LEFT: - row = self.GetGridCursorRow() - item = self.table.items[row] - self.set_footer(item) - event.Skip() - elif keycode == ord("R") or keycode == wx.WXK_F5: - self.table.refresh_content(event) - elif keycode == ord("I"): - row = self.GetGridCursorRow() - if not sh: - self.pickinput(row) - else: - col = self.GetGridCursorCol() - self.pickinputattr(row, col) - else: - event.Skip() - - def delete_current_notebook(self): - """ - deletes the current notebook tab - """ - panel = self.GetParent() - nb = panel.GetParent() - current = nb.GetSelection() - count = nb.GetPageCount() - if count > 1: - for i in xrange(count-1, current-1, -1): - nb.DeletePage(i) - nb.GetCurrentPage().grid.SetFocus() - else: - frame = nb.GetParent() - frame.SetStatusText("This is the last level!") - - def _doenter(self, value, *attrs): - """ - "enter" a special item resulting in a new notebook tab - """ - panel = self.GetParent() - nb = panel.GetParent() - frame = nb.GetParent() - current = nb.GetSelection() - count = nb.GetPageCount() - try: # if we want to enter something non-iterable, e.g. a function - if current + 1 == count and value is not self.input: # we have an event in the last tab - frame._add_notebook(value, *attrs) - elif value != self.input: # we have to delete all tabs newer than [panel] first - for i in xrange(count-1, current, -1): # some tabs don't close if we don't close in *reverse* order - nb.DeletePage(i) - frame._add_notebook(value) - except TypeError as exc: - if exc.__class__.__module__ == "exceptions": - msg = "%s: %s" % (exc.__class__.__name__, exc) - else: - msg = "%s.%s: %s" % (exc.__class__.__module__, exc.__class__.__name__, exc) - frame.SetStatusText(msg) - - def enterattr(self, row, col): - try: - attr = self.table._displayattrs[col] - value = attr.value(self.table.items[row]) - except Exception as exc: - self.error_output(str(exc)) - else: - self._doenter(value) - - def set_footer(self, item): - frame = self.GetParent().GetParent().GetParent() - frame.SetStatusText(" ".join([str(text) for (style, text) in ipipe.xformat(item, "footer", 20)[2]]), 0) - - def enter(self, row): - try: - value = self.table.items[row] - except Exception as exc: - self.error_output(str(exc)) - else: - self._doenter(value) - - def detail(self, row, col): - """ - shows a detail-view of the current cell - """ - try: - attr = self.table._displayattrs[col] - item = self.table.items[row] - except Exception as exc: - self.error_output(str(exc)) - else: - attrs = [ipipe.AttributeDetail(item, attr) for attr in ipipe.xattrs(item, "detail")] - self._doenter(attrs) - - def detail_attr(self, row, col): - try: - attr = self.table._displayattrs[col] - item = attr.value(self.table.items[row]) - except Exception as exc: - self.error_output(str(exc)) - else: - attrs = [ipipe.AttributeDetail(item, attr) for attr in ipipe.xattrs(item, "detail")] - self._doenter(attrs) - - def quit(self, result=None): - """ - quit - """ - frame = self.GetParent().GetParent().GetParent() - if frame.helpdialog: - frame.helpdialog.Destroy() - app = frame.parent - if app is not None: - app.result = result - frame.Close() - frame.Destroy() - - def cell_doubleclicked(self, event): - self.enterattr(event.GetRow(), event.GetCol()) - event.Skip() - - def cell_leftclicked(self, event): - row = event.GetRow() - item = self.table.items[row] - self.set_footer(item) - event.Skip() - - def pick(self, row): - """ - pick a single row and return to the IPython prompt - """ - try: - value = self.table.items[row] - except Exception as exc: - self.error_output(str(exc)) - else: - self.quit(value) - - def pickinput(self, row): - try: - value = self.table.items[row] - except Exception as exc: - self.error_output(str(exc)) - else: - api = ipapi.get() - api.set_next_input(str(value)) - self.quit(value) - - def pickinputattr(self, row, col): - try: - attr = self.table._displayattrs[col] - value = attr.value(self.table.items[row]) - except Exception as exc: - self.error_output(str(exc)) - else: - api = ipapi.get() - api.set_next_input(str(value)) - self.quit(value) - - def pickrows(self, rows): - """ - pick multiple rows and return to the IPython prompt - """ - try: - value = [self.table.items[row] for row in rows] - except Exception as exc: - self.error_output(str(exc)) - else: - self.quit(value) - - def pickrowsattr(self, rows, col): - """" - pick one column from multiple rows - """ - values = [] - try: - attr = self.table._displayattrs[col] - for row in rows: - try: - values.append(attr.value(self.table.items[row])) - except (SystemExit, KeyboardInterrupt): - raise - except Exception: - raise #pass - except Exception as exc: - self.error_output(str(exc)) - else: - self.quit(values) - - def pickattr(self, row, col): - try: - attr = self.table._displayattrs[col] - value = attr.value(self.table.items[row]) - except Exception as exc: - self.error_output(str(exc)) - else: - self.quit(value) - - -class IGridPanel(wx.Panel): - # Each IGridPanel contains an IGridGrid - def __init__(self, parent, input, *attrs): - wx.Panel.__init__(self, parent, -1) - self.grid = IGridGrid(self, input, *attrs) - self.grid.FitInside() - sizer = wx.BoxSizer(wx.VERTICAL) - sizer.Add(self.grid, proportion=1, flag=wx.EXPAND | wx.ALL, border=10) - self.SetSizer(sizer) - sizer.Fit(self) - sizer.SetSizeHints(self) - - -class IGridHTMLHelp(wx.Frame): - def __init__(self, parent, title, size): - wx.Frame.__init__(self, parent, -1, title, size=size) - html = wx.html.HtmlWindow(self) - if "gtk2" in wx.PlatformInfo: - html.SetStandardFonts() - html.SetPage(help) - - -class IGridFrame(wx.Frame): - maxtitlelen = 30 - - def __init__(self, parent, input): - title = " ".join([str(text) for (style, text) in ipipe.xformat(input, "header", 20)[2]]) - wx.Frame.__init__(self, None, title=title, size=(640, 480)) - self.menubar = wx.MenuBar() - self.menucounter = 100 - self.m_help = wx.Menu() - self.m_search = wx.Menu() - self.m_sort = wx.Menu() - self.m_refresh = wx.Menu() - self.notebook = wx.Notebook(self, -1, style=0) - self.statusbar = self.CreateStatusBar(1, wx.ST_SIZEGRIP) - self.statusbar.SetFieldsCount(2) - self.SetStatusWidths([-1, 200]) - self.parent = parent - self._add_notebook(input) - self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) - self.makemenu(self.m_sort, "&Sort (asc)\tV", "Sort ascending", self.sortasc) - self.makemenu(self.m_sort, "Sort (&desc)\tShift-V", "Sort descending", self.sortdesc) - self.makemenu(self.m_help, "&Help\tF1", "Help", self.display_help) -# self.makemenu(self.m_help, "&Show help in browser", "Show help in browser", self.display_help_in_browser) - self.makemenu(self.m_search, "&Find text\tCTRL-F", "Find text", self.enter_searchtext) - self.makemenu(self.m_search, "Find by &expression\tCTRL-Shift-F", "Find by expression", self.enter_searchexpression) - self.makemenu(self.m_search, "Find &next\tF3", "Find next", self.find_next) - self.makemenu(self.m_search, "Find &previous\tShift-F3", "Find previous", self.find_previous) - self.makemenu(self.m_refresh, "&Refresh once \tF5", "Refresh once", self.refresh_once) - self.makemenu(self.m_refresh, "Refresh every &1s", "Refresh every second", self.refresh_every_second) - self.makemenu(self.m_refresh, "Refresh every &X seconds", "Refresh every X seconds", self.refresh_interval) - self.makemenu(self.m_refresh, "&Stop all refresh timers", "Stop refresh timers", self.stop_refresh) - self.menubar.Append(self.m_search, "&Find") - self.menubar.Append(self.m_sort, "&Sort") - self.menubar.Append(self.m_refresh, "&Refresh") - self.menubar.Append(self.m_help, "&Help") - self.SetMenuBar(self.menubar) - self.searchtext = "" - self.searchexpression = "" - self.helpdialog = None - self.refresh_interval = 1000 - self.SetStatusText("Refreshing inactive", 1) - - def refresh_once(self, event): - table = self.notebook.GetPage(self.notebook.GetSelection()).grid.table - table.refresh_content(event) - - def refresh_interval(self, event): - table = self.notebook.GetPage(self.notebook.GetSelection()).grid.table - dlg = wx.TextEntryDialog(self, "Enter refresh interval (milliseconds):", "Refresh timer:", defaultValue=str(self.refresh_interval)) - if dlg.ShowModal() == wx.ID_OK: - try: - milliseconds = int(dlg.GetValue()) - except ValueError as exc: - self.SetStatusText(str(exc)) - else: - table.timer.Start(milliseconds=milliseconds, oneShot=False) - self.SetStatusText("Refresh timer set to %s ms" % milliseconds) - self.SetStatusText("Refresh interval: %s ms" % milliseconds, 1) - self.refresh_interval = milliseconds - dlg.Destroy() - - def stop_refresh(self, event): - for i in xrange(self.notebook.GetPageCount()): - nb = self.notebook.GetPage(i) - nb.grid.table.timer.Stop() - self.SetStatusText("Refreshing inactive", 1) - - def refresh_every_second(self, event): - table = self.notebook.GetPage(self.notebook.GetSelection()).grid.table - table.timer.Start(milliseconds=1000, oneShot=False) - self.SetStatusText("Refresh interval: 1000 ms", 1) - - def sortasc(self, event): - grid = self.notebook.GetPage(self.notebook.GetSelection()).grid - grid.sortattrasc() - - def sortdesc(self, event): - grid = self.notebook.GetPage(self.notebook.GetSelection()).grid - grid.sortattrdesc() - - def find_previous(self, event): - """ - find previous occurrences - """ - grid = self.notebook.GetPage(self.notebook.GetSelection()).grid - if self.searchtext: - row = grid.GetGridCursorRow() - col = grid.GetGridCursorCol() - self.SetStatusText('Search mode: text; looking for %s' % self.searchtext) - if col-1 >= 0: - grid.search(self.searchtext, row, col-1, False) - else: - grid.search(self.searchtext, row-1, grid.table.GetNumberCols()-1, False) - elif self.searchexpression: - self.SetStatusText("Search mode: expression; looking for %s" % repr(self.searchexpression)[2:-1]) - grid.searchexpression(searchexp=self.searchexpression, search_forward=False) - else: - self.SetStatusText("No search yet: please enter search-text or -expression") - - def find_next(self, event): - """ - find the next occurrence - """ - grid = self.notebook.GetPage(self.notebook.GetSelection()).grid - if self.searchtext != "": - row = grid.GetGridCursorRow() - col = grid.GetGridCursorCol() - self.SetStatusText('Search mode: text; looking for %s' % self.searchtext) - if col+1 < grid.table.GetNumberCols(): - grid.search(self.searchtext, row, col+1) - else: - grid.search(self.searchtext, row+1, 0) - elif self.searchexpression != "": - self.SetStatusText('Search mode: expression; looking for %s' % repr(self.searchexpression)[2:-1]) - grid.searchexpression(searchexp=self.searchexpression) - else: - self.SetStatusText("No search yet: please enter search-text or -expression") - - def display_help(self, event): - """ - Display a help dialog - """ - if self.helpdialog: - self.helpdialog.Destroy() - self.helpdialog = IGridHTMLHelp(None, title="Help", size=wx.Size(600,400)) - self.helpdialog.Show() - - def display_help_in_browser(self, event): - """ - Show the help-HTML in a browser (as a ``HtmlWindow`` does not understand - CSS this looks better) - """ - filename = urllib.pathname2url(os.path.abspath(os.path.join(os.path.dirname(__file__), "igrid_help.html"))) - if not filename.startswith("file"): - filename = "file:" + filename - webbrowser.open(filename, new=1, autoraise=True) - - def enter_searchexpression(self, event): - dlg = wx.TextEntryDialog(self, "Find:", "Find matching expression:", defaultValue=self.searchexpression) - if dlg.ShowModal() == wx.ID_OK: - self.searchexpression = dlg.GetValue() - self.searchtext = "" - self.SetStatusText('Search mode: expression; looking for %s' % repr(self.searchexpression)[2:-1]) - self.notebook.GetPage(self.notebook.GetSelection()).grid.searchexpression(self.searchexpression) - dlg.Destroy() - - def makemenu(self, menu, label, help, cmd): - menu.Append(self.menucounter, label, help) - self.Bind(wx.EVT_MENU, cmd, id=self.menucounter) - self.menucounter += 1 - - def _add_notebook(self, input, *attrs): - # Adds another notebook which has the starting object ``input`` - panel = IGridPanel(self.notebook, input, *attrs) - text = str(ipipe.xformat(input, "header", self.maxtitlelen)[2]) - if len(text) >= self.maxtitlelen: - text = text[:self.maxtitlelen].rstrip(".") + "..." - self.notebook.AddPage(panel, text, True) - panel.grid.SetFocus() - self.Layout() - - def OnCloseWindow(self, event): - self.Destroy() - - def enter_searchtext(self, event): - # Displays a dialog asking for the searchtext - dlg = wx.TextEntryDialog(self, "Find:", "Find in list", defaultValue=self.searchtext) - if dlg.ShowModal() == wx.ID_OK: - self.searchtext = dlg.GetValue() - self.searchexpression = "" - self.SetStatusText('Search mode: text; looking for %s' % self.searchtext) - self.notebook.GetPage(self.notebook.GetSelection()).grid.search(self.searchtext) - dlg.Destroy() - - -class App(wx.App): - def __init__(self, input): - self.input = input - self.result = None # Result to be returned to IPython. Set by quit(). - wx.App.__init__(self) - - def OnInit(self): - frame = IGridFrame(self, self.input) - frame.Show() - self.SetTopWindow(frame) - frame.Raise() - return True - - -class igrid(ipipe.Display): - """ - This is a wx-based display object that can be used instead of ``ibrowse`` - (which is curses-based) or ``idump`` (which simply does a print). - """ - - if wx.VERSION < (2, 7): - def display(self): - try: - # Try to create a "standalone" frame. If this works we're probably - # running with -wthread. - # Note that this sets the parent of the frame to None, but we can't - # pass a result object back to the shell anyway. - frame = IGridFrame(None, self.input) - frame.Show() - frame.Raise() - except wx.PyNoAppError: - # There's no wx application yet => create one. - app = App(self.input) - app.MainLoop() - return app.result - else: - # With wx 2.7 it gets simpler. - def display(self): - app = App(self.input) - app.MainLoop() - return app.result - diff --git a/IPython/deathrow/igrid_help.css b/IPython/deathrow/igrid_help.css deleted file mode 100644 index c875f4d..0000000 --- a/IPython/deathrow/igrid_help.css +++ /dev/null @@ -1,45 +0,0 @@ -body -{ - background-color: #fff; - color: #000; - font-family: "Verdana", "Arial", "XHelvetica", "Helvetica", sans-serif; - padding: 20px 30px; - margin: 0px; - font-size: 11px; -} -h1 -{ - font-family: "Trebuchet MS", sans-serif; - font-size: 24px; - margin: -20px -30px 4px -30px; - padding: 6px 30px; - font-weight: normal; - border-bottom: 1px solid #000; - letter-spacing: 1px; - background-color: #666; - color: #fff; -} -h2 -{ - font-family: "Trebuchet MS", sans-serif; - font-size: 20px; - padding: 14px 0px 2px 0px; - margin: 0px; - font-weight: bold; - color: #333; -} -h3 -{ - font-family: "Trebuchet MS", sans-serif; - font-size: 14px; - padding: 12px 0px 2px 0px; - margin: 0px; - font-weight: bold; - color: #333; -} -p -{ - line-height: 120%; - margin: 0px 0px 6px 0px; - padding: 0px; -} diff --git a/IPython/deathrow/igrid_help.html b/IPython/deathrow/igrid_help.html deleted file mode 100644 index 3c7122e..0000000 --- a/IPython/deathrow/igrid_help.html +++ /dev/null @@ -1,86 +0,0 @@ -<?xml version='1.0' encoding='iso-8859-1'?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> -<link rel="stylesheet" href="igrid_help.css" type="text/css" /> -<title>igrid help</title> -</head> -<body> -<h1>igrid help</h1> - - -<h2>Commands</h2> - - -<h3>pick (P)</h3> -<p>Pick the whole row (object is available as "_")</p> - -<h3>pickattr (Shift-P)</h3> -<p>Pick the attribute under the cursor</p> - -<h3>pickallattrs (Shift-C)</h3> -<p>Pick' the complete column under the cursor (i.e. the attribute under the -cursor) from all currently fetched objects. These attributes will be returned -as a list.</p> - -<h3>enter (E)</h3> -<p>Enter the object under the cursor. (what this mean depends on the object -itself, i.e. how it implements iteration). This opens a new browser 'level'.</p> - -<h3>enterattr (Shift-E)</h3> -<p>Enter the attribute under the cursor.</p> - -<h3>detail (D)</h3> -<p>Show a detail view of the object under the cursor. This shows the name, -type, doc string and value of the object attributes (and it might show more -attributes than in the list view, depending on the object).</p> - -<h3>detailattr (Shift-D)</h3> -<p>Show a detail view of the attribute under the cursor.</p> - -<h3>pickrows (M)</h3> -<p>Pick multiple selected rows (M)</p> - -<h3>pickrowsattr (CTRL-M)</h3> -<p>From multiple selected rows pick the cells matching the attribute the cursor is in (CTRL-M)</p> - -<h3>find (CTRL-F)</h3> -<p>Find text</p> - -<h3>find_next (F3)</h3> -<p>Find next occurrence of the searchtext</p> - -<h3>find_previous (Shift-F3)</h3> -<p>Find previous occurrence of the searchtext </p> - -<h3>sortattrasc (V)</h3> -<p>Sort the objects (in ascending order) using the attribute under the cursor as the sort key.</p> - -<h3>sortattrdesc (Shift-V)</h3> -<p>Sort the objects (in descending order) using the attribute under the cursor as the sort key.</p> - -<h3>leave (Backspace, DEL, X)</h3> -<p>Close current tab (and all the tabs to the right of the current one).</h3> - -<h3>quit (ESC,Q)</h3> -<p>Quit igrid and return to the IPython prompt.</p> - - -<h2>Navigation</h2> - - -<h3>Jump to the last column of the current row (END, CTRL-E, CTRL-Right)</h3> - -<h3>Jump to the first column of the current row (HOME, CTRL-A, CTRL-Left)</h3> - -<h3>Move the cursor one column to the left (<)</h3> - -<h3>Move the cursor one column to the right (>)</h3> - -<h3>Jump to the first row in the current column (CTRL-Up)</h3> - -<h3>Jump to the last row in the current column (CTRL-Down)</h3> - -</body> -</html> diff --git a/IPython/deathrow/ipipe.py b/IPython/deathrow/ipipe.py deleted file mode 100644 index 2b9c822..0000000 --- a/IPython/deathrow/ipipe.py +++ /dev/null @@ -1,2328 +0,0 @@ -# -*- coding: iso-8859-1 -*- - -""" -``ipipe`` provides classes to be used in an interactive Python session. Doing a -``from ipipe import *`` is the preferred way to do this. The name of all -objects imported this way starts with ``i`` to minimize collisions. - -``ipipe`` supports "pipeline expressions", which is something resembling Unix -pipes. An example is:: - - >>> ienv | isort("key.lower()") - -This gives a listing of all environment variables sorted by name. - - -There are three types of objects in a pipeline expression: - -* ``Table``s: These objects produce items. Examples are ``ils`` (listing the - current directory, ``ienv`` (listing environment variables), ``ipwd`` (listing - user accounts) and ``igrp`` (listing user groups). A ``Table`` must be the - first object in a pipe expression. - -* ``Pipe``s: These objects sit in the middle of a pipe expression. They - transform the input in some way (e.g. filtering or sorting it). Examples are: - ``ifilter`` (which filters the input pipe), ``isort`` (which sorts the input - pipe) and ``ieval`` (which evaluates a function or expression for each object - in the input pipe). - -* ``Display``s: These objects can be put as the last object in a pipeline - expression. There are responsible for displaying the result of the pipeline - expression. If a pipeline expression doesn't end in a display object a default - display objects will be used. One example is ``ibrowse`` which is a ``curses`` - based browser. - - -Adding support for pipeline expressions to your own objects can be done through -three extensions points (all of them optional): - -* An object that will be displayed as a row by a ``Display`` object should - implement the method ``__xattrs__(self, mode)`` method or register an - implementation of the generic function ``xattrs``. For more info see ``xattrs``. - -* When an object ``foo`` is displayed by a ``Display`` object, the generic - function ``xrepr`` is used. - -* Objects that can be iterated by ``Pipe``s must iterable. For special cases, - where iteration for display is different than the normal iteration a special - implementation can be registered with the generic function ``xiter``. This - makes it possible to use dictionaries and modules in pipeline expressions, - for example:: - - >>> import sys - >>> sys | ifilter("isinstance(value, int)") | idump - key |value - api_version| 1012 - dllhandle | 503316480 - hexversion | 33817328 - maxint |2147483647 - maxunicode | 65535 - >>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()") - ... - - Note: The expression strings passed to ``ifilter()`` and ``isort()`` can - refer to the object to be filtered or sorted via the variable ``_`` and to any - of the attributes of the object, i.e.:: - - >>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()") - - does the same as:: - - >>> sys.modules | ifilter("value is not None") | isort("key.lower()") - - In addition to expression strings, it's possible to pass callables (taking - the object as an argument) to ``ifilter()``, ``isort()`` and ``ieval()``:: - - >>> sys | ifilter(lambda _:isinstance(_.value, int)) \ - ... | ieval(lambda _: (_.key, hex(_.value))) | idump - 0 |1 - api_version|0x3f4 - dllhandle |0x1e000000 - hexversion |0x20402f0 - maxint |0x7fffffff - maxunicode |0xffff -""" - -skip_doctest = True # ignore top-level docstring as a doctest. - -import sys, os, os.path, stat, glob, new, csv, datetime, types -import itertools, mimetypes, StringIO - -try: # Python 2.3 compatibility - import collections -except ImportError: - deque = list -else: - deque = collections.deque - -try: # Python 2.3 compatibility - set -except NameError: - import sets - set = sets.Set - -try: # Python 2.3 compatibility - sorted -except NameError: - def sorted(iterator, key=None, reverse=False): - items = list(iterator) - if key is not None: - items.sort(lambda i1, i2: cmp(key(i1), key(i2))) - else: - items.sort() - if reverse: - items.reverse() - return items - -try: # Python 2.4 compatibility - GeneratorExit -except NameError: - GeneratorExit = SystemExit - -try: - import pwd -except ImportError: - pwd = None - -try: - import grp -except ImportError: - grp = None - -from IPython.external import simplegeneric -from IPython.external import path - -try: - import IPython.utils.io - from IPython.utils import generics -except ImportError: - Term = None - generics = None - -from IPython.core import ipapi - - -__all__ = [ - "ifile", "ils", "iglob", "iwalk", "ipwdentry", "ipwd", "igrpentry", "igrp", - "icsv", "ix", "ichain", "isort", "ifilter", "ieval", "ienum", - "ienv", "ihist", "ialias", "icap", "idump", "iless" -] - - -os.stat_float_times(True) # enable microseconds - - -class AttrNamespace(object): - """ - Helper class that is used for providing a namespace for evaluating - expressions containing attribute names of an object. - """ - def __init__(self, wrapped): - self.wrapped = wrapped - - def __getitem__(self, name): - if name == "_": - return self.wrapped - try: - return getattr(self.wrapped, name) - except AttributeError: - raise KeyError(name) - -# Python 2.3 compatibility -# use eval workaround to find out which names are used in the -# eval string and put them into the locals. This works for most -# normal uses case, bizarre ones like accessing the locals() -# will fail -try: - eval("_", None, AttrNamespace(None)) -except TypeError: - real_eval = eval - def eval(codestring, _globals, _locals): - """ - eval(source[, globals[, locals]]) -> value - - Evaluate the source in the context of globals and locals. - The source may be a string representing a Python expression - or a code object as returned by compile(). - The globals must be a dictionary and locals can be any mappping. - - This function is a workaround for the shortcomings of - Python 2.3's eval. - """ - - if isinstance(codestring, basestring): - code = compile(codestring, "_eval", "eval") - else: - code = codestring - newlocals = {} - for name in code.co_names: - try: - newlocals[name] = _locals[name] - except KeyError: - pass - return real_eval(code, _globals, newlocals) - - -noitem = object() - - -def item(iterator, index, default=noitem): - """ - Return the ``index``th item from the iterator ``iterator``. - ``index`` must be an integer (negative integers are relative to the - end (i.e. the last items produced by the iterator)). - - If ``default`` is given, this will be the default value when - the iterator doesn't contain an item at this position. Otherwise an - ``IndexError`` will be raised. - - Note that using this function will partially or totally exhaust the - iterator. - """ - i = index - if i>=0: - for item in iterator: - if not i: - return item - i -= 1 - else: - i = -index - cache = deque() - for item in iterator: - cache.append(item) - if len(cache)>i: - cache.popleft() - if len(cache)==i: - return cache.popleft() - if default is noitem: - raise IndexError(index) - else: - return default - - -def getglobals(g): - """ - Return the global namespace that is used for expression strings in - ``ifilter`` and others. This is ``g`` or (if ``g`` is ``None``) IPython's - user namespace. - """ - if g is None: - if ipapi is not None: - api = ipapi.get() - if api is not None: - return api.user_ns - return globals() - return g - - -class Descriptor(object): - """ - A ``Descriptor`` object is used for describing the attributes of objects. - """ - def __hash__(self): - return hash(self.__class__) ^ hash(self.key()) - - def __eq__(self, other): - return self.__class__ is other.__class__ and self.key() == other.key() - - def __ne__(self, other): - return self.__class__ is not other.__class__ or self.key() != other.key() - - def key(self): - pass - - def name(self): - """ - Return the name of this attribute for display by a ``Display`` object - (e.g. as a column title). - """ - key = self.key() - if key is None: - return "_" - return str(key) - - def attrtype(self, obj): - """ - Return the type of this attribute (i.e. something like "attribute" or - "method"). - """ - - def valuetype(self, obj): - """ - Return the type of this attribute value of the object ``obj``. - """ - - def value(self, obj): - """ - Return the value of this attribute of the object ``obj``. - """ - - def doc(self, obj): - """ - Return the documentation for this attribute. - """ - - def shortdoc(self, obj): - """ - Return a short documentation for this attribute (defaulting to the - first line). - """ - doc = self.doc(obj) - if doc is not None: - doc = doc.strip().splitlines()[0].strip() - return doc - - def iter(self, obj): - """ - Return an iterator for this attribute of the object ``obj``. - """ - return xiter(self.value(obj)) - - -class SelfDescriptor(Descriptor): - """ - A ``SelfDescriptor`` describes the object itself. - """ - def key(self): - return None - - def attrtype(self, obj): - return "self" - - def valuetype(self, obj): - return type(obj) - - def value(self, obj): - return obj - - def __repr__(self): - return "Self" - -selfdescriptor = SelfDescriptor() # there's no need for more than one - - -class AttributeDescriptor(Descriptor): - """ - An ``AttributeDescriptor`` describes a simple attribute of an object. - """ - __slots__ = ("_name", "_doc") - - def __init__(self, name, doc=None): - self._name = name - self._doc = doc - - def key(self): - return self._name - - def doc(self, obj): - return self._doc - - def attrtype(self, obj): - return "attr" - - def valuetype(self, obj): - return type(getattr(obj, self._name)) - - def value(self, obj): - return getattr(obj, self._name) - - def __repr__(self): - if self._doc is None: - return "Attribute(%r)" % self._name - else: - return "Attribute(%r, %r)" % (self._name, self._doc) - - -class IndexDescriptor(Descriptor): - """ - An ``IndexDescriptor`` describes an "attribute" of an object that is fetched - via ``__getitem__``. - """ - __slots__ = ("_index",) - - def __init__(self, index): - self._index = index - - def key(self): - return self._index - - def attrtype(self, obj): - return "item" - - def valuetype(self, obj): - return type(obj[self._index]) - - def value(self, obj): - return obj[self._index] - - def __repr__(self): - return "Index(%r)" % self._index - - -class MethodDescriptor(Descriptor): - """ - A ``MethodDescriptor`` describes a method of an object that can be called - without argument. Note that this method shouldn't change the object. - """ - __slots__ = ("_name", "_doc") - - def __init__(self, name, doc=None): - self._name = name - self._doc = doc - - def key(self): - return self._name - - def doc(self, obj): - if self._doc is None: - return getattr(obj, self._name).__doc__ - return self._doc - - def attrtype(self, obj): - return "method" - - def valuetype(self, obj): - return type(self.value(obj)) - - def value(self, obj): - return getattr(obj, self._name)() - - def __repr__(self): - if self._doc is None: - return "Method(%r)" % self._name - else: - return "Method(%r, %r)" % (self._name, self._doc) - - -class IterAttributeDescriptor(Descriptor): - """ - An ``IterAttributeDescriptor`` works like an ``AttributeDescriptor`` but - doesn't return an attribute values (because this value might be e.g. a large - list). - """ - __slots__ = ("_name", "_doc") - - def __init__(self, name, doc=None): - self._name = name - self._doc = doc - - def key(self): - return self._name - - def doc(self, obj): - return self._doc - - def attrtype(self, obj): - return "iter" - - def valuetype(self, obj): - return noitem - - def value(self, obj): - return noitem - - def iter(self, obj): - return xiter(getattr(obj, self._name)) - - def __repr__(self): - if self._doc is None: - return "IterAttribute(%r)" % self._name - else: - return "IterAttribute(%r, %r)" % (self._name, self._doc) - - -class IterMethodDescriptor(Descriptor): - """ - An ``IterMethodDescriptor`` works like an ``MethodDescriptor`` but doesn't - return an attribute values (because this value might be e.g. a large list). - """ - __slots__ = ("_name", "_doc") - - def __init__(self, name, doc=None): - self._name = name - self._doc = doc - - def key(self): - return self._name - - def doc(self, obj): - if self._doc is None: - return getattr(obj, self._name).__doc__ - return self._doc - - def attrtype(self, obj): - return "itermethod" - - def valuetype(self, obj): - return noitem - - def value(self, obj): - return noitem - - def iter(self, obj): - return xiter(getattr(obj, self._name)()) - - def __repr__(self): - if self._doc is None: - return "IterMethod(%r)" % self._name - else: - return "IterMethod(%r, %r)" % (self._name, self._doc) - - -class FunctionDescriptor(Descriptor): - """ - A ``FunctionDescriptor`` turns a function into a descriptor. The function - will be called with the object to get the type and value of the attribute. - """ - __slots__ = ("_function", "_name", "_doc") - - def __init__(self, function, name=None, doc=None): - self._function = function - self._name = name - self._doc = doc - - def key(self): - return self._function - - def name(self): - if self._name is not None: - return self._name - return getattr(self._function, "__xname__", self._function.__name__) - - def doc(self, obj): - if self._doc is None: - return self._function.__doc__ - return self._doc - - def attrtype(self, obj): - return "function" - - def valuetype(self, obj): - return type(self._function(obj)) - - def value(self, obj): - return self._function(obj) - - def __repr__(self): - if self._doc is None: - return "Function(%r)" % self._name - else: - return "Function(%r, %r)" % (self._name, self._doc) - - -class Table(object): - """ - A ``Table`` is an object that produces items (just like a normal Python - iterator/generator does) and can be used as the first object in a pipeline - expression. The displayhook will open the default browser for such an object - (instead of simply printing the ``repr()`` result). - """ - - # We want to support ``foo`` and ``foo()`` in pipeline expression: - # So we implement the required operators (``|`` and ``+``) in the metaclass, - # instantiate the class and forward the operator to the instance - class __metaclass__(type): - def __iter__(self): - return iter(self()) - - def __or__(self, other): - return self() | other - - def __add__(self, other): - return self() + other - - def __radd__(self, other): - return other + self() - - def __getitem__(self, index): - return self()[index] - - def __getitem__(self, index): - return item(self, index) - - def __contains__(self, item): - for haveitem in self: - if item == haveitem: - return True - return False - - def __or__(self, other): - # autoinstantiate right hand side - if isinstance(other, type) and issubclass(other, (Table, Display)): - other = other() - # treat simple strings and functions as ``ieval`` instances - elif not isinstance(other, Display) and not isinstance(other, Table): - other = ieval(other) - # forward operations to the right hand side - return other.__ror__(self) - - def __add__(self, other): - # autoinstantiate right hand side - if isinstance(other, type) and issubclass(other, Table): - other = other() - return ichain(self, other) - - def __radd__(self, other): - # autoinstantiate left hand side - if isinstance(other, type) and issubclass(other, Table): - other = other() - return ichain(other, self) - - -class Pipe(Table): - """ - A ``Pipe`` is an object that can be used in a pipeline expression. It - processes the objects it gets from its input ``Table``/``Pipe``. Note that - a ``Pipe`` object can't be used as the first object in a pipeline - expression, as it doesn't produces items itself. - """ - class __metaclass__(Table.__metaclass__): - def __ror__(self, input): - return input | self() - - def __ror__(self, input): - # autoinstantiate left hand side - if isinstance(input, type) and issubclass(input, Table): - input = input() - self.input = input - return self - - -def xrepr(item, mode="default"): - """ - Generic function that adds color output and different display modes to ``repr``. - - The result of an ``xrepr`` call is iterable and consists of ``(style, string)`` - tuples. The ``style`` in this tuple must be a ``Style`` object from the - ``astring`` module. To reconfigure the output the first yielded tuple can be - a ``(aligment, full)`` tuple instead of a ``(style, string)`` tuple. - ``alignment`` can be -1 for left aligned, 0 for centered and 1 for right - aligned (the default is left alignment). ``full`` is a boolean that specifies - whether the complete output must be displayed or the ``Display`` object is - allowed to stop output after enough text has been produced (e.g. a syntax - highlighted text line would use ``True``, but for a large data structure - (i.e. a nested list, tuple or dictionary) ``False`` would be used). - The default is full output. - - There are four different possible values for ``mode`` depending on where - the ``Display`` object will display ``item``: - - ``"header"`` - ``item`` will be displayed in a header line (this is used by ``ibrowse``). - - ``"footer"`` - ``item`` will be displayed in a footer line (this is used by ``ibrowse``). - - ``"cell"`` - ``item`` will be displayed in a table cell/list. - - ``"default"`` - default mode. If an ``xrepr`` implementation recursively outputs objects, - ``"default"`` must be passed in the recursive calls to ``xrepr``. - - If no implementation is registered for ``item``, ``xrepr`` will try the - ``__xrepr__`` method on ``item``. If ``item`` doesn't have an ``__xrepr__`` - method it falls back to ``repr``/``__repr__`` for all modes. - """ - try: - func = item.__xrepr__ - except AttributeError: - yield (astyle.style_default, repr(item)) - else: - try: - for x in func(mode): - yield x - except (KeyboardInterrupt, SystemExit, GeneratorExit): - raise - except Exception: - yield (astyle.style_default, repr(item)) -xrepr = simplegeneric.generic(xrepr) - - -def xrepr_none(self, mode="default"): - yield (astyle.style_type_none, repr(self)) -xrepr.when_object(None)(xrepr_none) - - -def xrepr_noitem(self, mode="default"): - yield (2, True) - yield (astyle.style_nodata, "<?>") -xrepr.when_object(noitem)(xrepr_noitem) - - -def xrepr_bool(self, mode="default"): - yield (astyle.style_type_bool, repr(self)) -xrepr.when_type(bool)(xrepr_bool) - - -def xrepr_str(self, mode="default"): - if mode == "cell": - yield (astyle.style_default, repr(self.expandtabs(tab))[1:-1]) - else: - yield (astyle.style_default, repr(self)) -xrepr.when_type(str)(xrepr_str) - - -def xrepr_unicode(self, mode="default"): - if mode == "cell": - yield (astyle.style_default, repr(self.expandtabs(tab))[2:-1]) - else: - yield (astyle.style_default, repr(self)) -xrepr.when_type(unicode)(xrepr_unicode) - - -def xrepr_number(self, mode="default"): - yield (1, True) - yield (astyle.style_type_number, repr(self)) -xrepr.when_type(int)(xrepr_number) -xrepr.when_type(long)(xrepr_number) -xrepr.when_type(float)(xrepr_number) - - -def xrepr_complex(self, mode="default"): - yield (astyle.style_type_number, repr(self)) -xrepr.when_type(complex)(xrepr_number) - - -def xrepr_datetime(self, mode="default"): - if mode == "cell": - # Don't use strftime() here, as this requires year >= 1900 - yield (astyle.style_type_datetime, - "%04d-%02d-%02d %02d:%02d:%02d.%06d" % \ - (self.year, self.month, self.day, - self.hour, self.minute, self.second, - self.microsecond), - ) - else: - yield (astyle.style_type_datetime, repr(self)) -xrepr.when_type(datetime.datetime)(xrepr_datetime) - - -def xrepr_date(self, mode="default"): - if mode == "cell": - yield (astyle.style_type_datetime, - "%04d-%02d-%02d" % (self.year, self.month, self.day)) - else: - yield (astyle.style_type_datetime, repr(self)) -xrepr.when_type(datetime.date)(xrepr_date) - - -def xrepr_time(self, mode="default"): - if mode == "cell": - yield (astyle.style_type_datetime, - "%02d:%02d:%02d.%06d" % \ - (self.hour, self.minute, self.second, self.microsecond)) - else: - yield (astyle.style_type_datetime, repr(self)) -xrepr.when_type(datetime.time)(xrepr_time) - - -def xrepr_timedelta(self, mode="default"): - yield (astyle.style_type_datetime, repr(self)) -xrepr.when_type(datetime.timedelta)(xrepr_timedelta) - - -def xrepr_type(self, mode="default"): - if self.__module__ == "__builtin__": - yield (astyle.style_type_type, self.__name__) - else: - yield (astyle.style_type_type, "%s.%s" % (self.__module__, self.__name__)) -xrepr.when_type(type)(xrepr_type) - - -def xrepr_exception(self, mode="default"): - if self.__class__.__module__ == "exceptions": - classname = self.__class__.__name__ - else: - classname = "%s.%s" % \ - (self.__class__.__module__, self.__class__.__name__) - if mode == "header" or mode == "footer": - yield (astyle.style_error, "%s: %s" % (classname, self)) - else: - yield (astyle.style_error, classname) -xrepr.when_type(Exception)(xrepr_exception) - - -def xrepr_listtuple(self, mode="default"): - if mode == "header" or mode == "footer": - if self.__class__.__module__ == "__builtin__": - classname = self.__class__.__name__ - else: - classname = "%s.%s" % \ - (self.__class__.__module__,self.__class__.__name__) - yield (astyle.style_default, - "<%s object with %d items at 0x%x>" % \ - (classname, len(self), id(self))) - else: - yield (-1, False) - if isinstance(self, list): - yield (astyle.style_default, "[") - end = "]" - else: - yield (astyle.style_default, "(") - end = ")" - for (i, subself) in enumerate(self): - if i: - yield (astyle.style_default, ", ") - for part in xrepr(subself, "default"): - yield part - yield (astyle.style_default, end) -xrepr.when_type(list)(xrepr_listtuple) -xrepr.when_type(tuple)(xrepr_listtuple) - - -def xrepr_dict(self, mode="default"): - if mode == "header" or mode == "footer": - if self.__class__.__module__ == "__builtin__": - classname = self.__class__.__name__ - else: - classname = "%s.%s" % \ - (self.__class__.__module__,self.__class__.__name__) - yield (astyle.style_default, - "<%s object with %d items at 0x%x>" % \ - (classname, len(self), id(self))) - else: - yield (-1, False) - if isinstance(self, dict): - yield (astyle.style_default, "{") - end = "}" - else: - yield (astyle.style_default, "dictproxy((") - end = "})" - for (i, (key, value)) in enumerate(self.iteritems()): - if i: - yield (astyle.style_default, ", ") - for part in xrepr(key, "default"): - yield part - yield (astyle.style_default, ": ") - for part in xrepr(value, "default"): - yield part - yield (astyle.style_default, end) -xrepr.when_type(dict)(xrepr_dict) -xrepr.when_type(types.DictProxyType)(xrepr_dict) - - -def upgradexattr(attr): - """ - Convert an attribute descriptor string to a real descriptor object. - - If attr already is a descriptor object return it unmodified. A - ``SelfDescriptor`` will be returned if ``attr`` is ``None``. ``"foo"`` - returns an ``AttributeDescriptor`` for the attribute named ``"foo"``. - ``"foo()"`` returns a ``MethodDescriptor`` for the method named ``"foo"``. - ``"-foo"`` will return an ``IterAttributeDescriptor`` for the attribute - named ``"foo"`` and ``"-foo()"`` will return an ``IterMethodDescriptor`` - for the method named ``"foo"``. Furthermore integers will return the appropriate - ``IndexDescriptor`` and callables will return a ``FunctionDescriptor``. - """ - if attr is None: - return selfdescriptor - elif isinstance(attr, Descriptor): - return attr - elif isinstance(attr, basestring): - if attr.endswith("()"): - if attr.startswith("-"): - return IterMethodDescriptor(attr[1:-2]) - else: - return MethodDescriptor(attr[:-2]) - else: - if attr.startswith("-"): - return IterAttributeDescriptor(attr[1:]) - else: - return AttributeDescriptor(attr) - elif isinstance(attr, (int, long)): - return IndexDescriptor(attr) - elif callable(attr): - return FunctionDescriptor(attr) - else: - raise TypeError("can't handle descriptor %r" % attr) - - -def xattrs(item, mode="default"): - """ - Generic function that returns an iterable of attribute descriptors - to be used for displaying the attributes ob the object ``item`` in display - mode ``mode``. - - There are two possible modes: - - ``"detail"`` - The ``Display`` object wants to display a detailed list of the object - attributes. - - ``"default"`` - The ``Display`` object wants to display the object in a list view. - - If no implementation is registered for the object ``item`` ``xattrs`` falls - back to trying the ``__xattrs__`` method of the object. If this doesn't - exist either, ``dir(item)`` is used for ``"detail"`` mode and ``(None,)`` - for ``"default"`` mode. - - The implementation must yield attribute descriptors (see the class - ``Descriptor`` for more info). The ``__xattrs__`` method may also return - attribute descriptor strings (and ``None``) which will be converted to real - descriptors by ``upgradexattr()``. - """ - try: - func = item.__xattrs__ - except AttributeError: - if mode == "detail": - for attrname in dir(item): - yield AttributeDescriptor(attrname) - else: - yield selfdescriptor - else: - for attr in func(mode): - yield upgradexattr(attr) -xattrs = simplegeneric.generic(xattrs) - - -def xattrs_complex(self, mode="default"): - if mode == "detail": - return (AttributeDescriptor("real"), AttributeDescriptor("imag")) - return (selfdescriptor,) -xattrs.when_type(complex)(xattrs_complex) - - -def _isdict(item): - try: - itermeth = item.__class__.__iter__ - except (AttributeError, TypeError): - return False - return itermeth is dict.__iter__ or itermeth is types.DictProxyType.__iter__ - - -def _isstr(item): - if not isinstance(item, basestring): - return False - try: - itermeth = item.__class__.__iter__ - except AttributeError: - return True - return False # ``__iter__`` has been redefined - - -def xiter(item): - """ - Generic function that implements iteration for pipeline expression. If no - implementation is registered for ``item`` ``xiter`` falls back to ``iter``. - """ - try: - func = item.__xiter__ - except AttributeError: - if _isdict(item): - def items(item): - fields = ("key", "value") - for (key, value) in item.iteritems(): - yield Fields(fields, key=key, value=value) - return items(item) - elif isinstance(item, new.module): - def items(item): - fields = ("key", "value") - for key in sorted(item.__dict__): - yield Fields(fields, key=key, value=getattr(item, key)) - return items(item) - elif _isstr(item): - if not item: - raise ValueError("can't enter empty string") - lines = item.splitlines() - if len(lines) == 1: - def iterone(item): - yield item - return iterone(item) - else: - return iter(lines) - return iter(item) - else: - return iter(func()) # iter() just to be safe -xiter = simplegeneric.generic(xiter) - - -class ichain(Pipe): - """ - Chains multiple ``Table``s into one. - """ - - def __init__(self, *iters): - self.iters = iters - - def __iter__(self): - return itertools.chain(*self.iters) - - def __xrepr__(self, mode="default"): - if mode == "header" or mode == "footer": - for (i, item) in enumerate(self.iters): - if i: - yield (astyle.style_default, "+") - if isinstance(item, Pipe): - yield (astyle.style_default, "(") - for part in xrepr(item, mode): - yield part - if isinstance(item, Pipe): - yield (astyle.style_default, ")") - else: - yield (astyle.style_default, repr(self)) - - def __repr__(self): - args = ", ".join([repr(it) for it in self.iters]) - return "%s.%s(%s)" % \ - (self.__class__.__module__, self.__class__.__name__, args) - - -class ifile(path.path): - """ - file (or directory) object. - """ - - def getmode(self): - return self.stat().st_mode - mode = property(getmode, None, None, "Access mode") - - def gettype(self): - data = [ - (stat.S_ISREG, "file"), - (stat.S_ISDIR, "dir"), - (stat.S_ISCHR, "chardev"), - (stat.S_ISBLK, "blockdev"), - (stat.S_ISFIFO, "fifo"), - (stat.S_ISLNK, "symlink"), - (stat.S_ISSOCK,"socket"), - ] - lstat = self.lstat() - if lstat is not None: - types = set([text for (func, text) in data if func(lstat.st_mode)]) - else: - types = set() - m = self.mode - types.update([text for (func, text) in data if func(m)]) - return ", ".join(types) - type = property(gettype, None, None, "file type (file, directory, link, etc.)") - - def getmodestr(self): - m = self.mode - data = [ - (stat.S_IRUSR, "-r"), - (stat.S_IWUSR, "-w"), - (stat.S_IXUSR, "-x"), - (stat.S_IRGRP, "-r"), - (stat.S_IWGRP, "-w"), - (stat.S_IXGRP, "-x"), - (stat.S_IROTH, "-r"), - (stat.S_IWOTH, "-w"), - (stat.S_IXOTH, "-x"), - ] - return "".join([text[bool(m&bit)] for (bit, text) in data]) - - modestr = property(getmodestr, None, None, "Access mode as string") - - def getblocks(self): - return self.stat().st_blocks - blocks = property(getblocks, None, None, "File size in blocks") - - def getblksize(self): - return self.stat().st_blksize - blksize = property(getblksize, None, None, "Filesystem block size") - - def getdev(self): - return self.stat().st_dev - dev = property(getdev) - - def getnlink(self): - return self.stat().st_nlink - nlink = property(getnlink, None, None, "Number of links") - - def getuid(self): - return self.stat().st_uid - uid = property(getuid, None, None, "User id of file owner") - - def getgid(self): - return self.stat().st_gid - gid = property(getgid, None, None, "Group id of file owner") - - def getowner(self): - stat = self.stat() - try: - return pwd.getpwuid(stat.st_uid).pw_name - except KeyError: - return stat.st_uid - owner = property(getowner, None, None, "Owner name (or id)") - - def getgroup(self): - stat = self.stat() - try: - return grp.getgrgid(stat.st_gid).gr_name - except KeyError: - return stat.st_gid - group = property(getgroup, None, None, "Group name (or id)") - - def getadate(self): - return datetime.datetime.utcfromtimestamp(self.atime) - adate = property(getadate, None, None, "Access date") - - def getcdate(self): - return datetime.datetime.utcfromtimestamp(self.ctime) - cdate = property(getcdate, None, None, "Creation date") - - def getmdate(self): - return datetime.datetime.utcfromtimestamp(self.mtime) - mdate = property(getmdate, None, None, "Modification date") - - def mimetype(self): - """ - Return MIME type guessed from the extension. - """ - return mimetypes.guess_type(self.basename())[0] - - def encoding(self): - """ - Return guessed compression (like "compress" or "gzip"). - """ - return mimetypes.guess_type(self.basename())[1] - - def __repr__(self): - return "ifile(%s)" % path._base.__repr__(self) - - if sys.platform == "win32": - defaultattrs = (None, "type", "size", "modestr", "mdate") - else: - defaultattrs = (None, "type", "size", "modestr", "owner", "group", "mdate") - - def __xattrs__(self, mode="default"): - if mode == "detail": - return ( - "name", - "basename()", - "abspath()", - "realpath()", - "type", - "mode", - "modestr", - "stat()", - "lstat()", - "uid", - "gid", - "owner", - "group", - "dev", - "nlink", - "ctime", - "mtime", - "atime", - "cdate", - "mdate", - "adate", - "size", - "blocks", - "blksize", - "isdir()", - "islink()", - "mimetype()", - "encoding()", - "-listdir()", - "-dirs()", - "-files()", - "-walk()", - "-walkdirs()", - "-walkfiles()", - ) - else: - return self.defaultattrs - - -def xiter_ifile(self): - if self.isdir(): - yield (self / os.pardir).abspath() - for child in sorted(self.listdir()): - yield child - else: - f = self.open("rb") - for line in f: - yield line - f.close() -xiter.when_type(ifile)(xiter_ifile) - - -# We need to implement ``xrepr`` for ``ifile`` as a generic function, because -# otherwise ``xrepr_str`` would kick in. -def xrepr_ifile(self, mode="default"): - try: - if self.isdir(): - name = "idir" - style = astyle.style_dir - else: - name = "ifile" - style = astyle.style_file - except IOError: - name = "ifile" - style = astyle.style_default - if mode in ("cell", "header", "footer"): - abspath = repr(path._base(self.normpath())) - if abspath.startswith("u"): - abspath = abspath[2:-1] - else: - abspath = abspath[1:-1] - if mode == "cell": - yield (style, abspath) - else: - yield (style, "%s(%s)" % (name, abspath)) - else: - yield (style, repr(self)) -xrepr.when_type(ifile)(xrepr_ifile) - - -class ils(Table): - """ - List the current (or a specified) directory. - - Examples:: - - >>> ils - <class 'IPython.extensions.ipipe.ils'> - >>> ils("/usr/local/lib/python2.4") - IPython.extensions.ipipe.ils('/usr/local/lib/python2.4') - >>> ils("~") - IPython.extensions.ipipe.ils('/home/fperez') - # all-random - """ - def __init__(self, base=os.curdir, dirs=True, files=True): - self.base = os.path.expanduser(base) - self.dirs = dirs - self.files = files - - def __iter__(self): - base = ifile(self.base) - yield (base / os.pardir).abspath() - for child in sorted(base.listdir()): - if self.dirs: - if self.files: - yield child - else: - if child.isdir(): - yield child - elif self.files: - if not child.isdir(): - yield child - - def __xrepr__(self, mode="default"): - return xrepr(ifile(self.base), mode) - - def __repr__(self): - return "%s.%s(%r)" % \ - (self.__class__.__module__, self.__class__.__name__, self.base) - - -class iglob(Table): - """ - List all files and directories matching a specified pattern. - (See ``glob.glob()`` for more info.). - - Examples:: - - >>> iglob("*.py") - IPython.extensions.ipipe.iglob('*.py') - """ - def __init__(self, glob): - self.glob = glob - - def __iter__(self): - for name in glob.glob(self.glob): - yield ifile(name) - - def __xrepr__(self, mode="default"): - if mode == "header" or mode == "footer" or mode == "cell": - yield (astyle.style_default, - "%s(%r)" % (self.__class__.__name__, self.glob)) - else: - yield (astyle.style_default, repr(self)) - - def __repr__(self): - return "%s.%s(%r)" % \ - (self.__class__.__module__, self.__class__.__name__, self.glob) - - -class iwalk(Table): - """ - List all files and directories in a directory and it's subdirectory:: - - >>> iwalk - <class 'IPython.extensions.ipipe.iwalk'> - >>> iwalk("/usr/lib") - IPython.extensions.ipipe.iwalk('/usr/lib') - >>> iwalk("~") - IPython.extensions.ipipe.iwalk('/home/fperez') # random - - """ - def __init__(self, base=os.curdir, dirs=True, files=True): - self.base = os.path.expanduser(base) - self.dirs = dirs - self.files = files - - def __iter__(self): - for (dirpath, dirnames, filenames) in os.walk(self.base): - if self.dirs: - for name in sorted(dirnames): - yield ifile(os.path.join(dirpath, name)) - if self.files: - for name in sorted(filenames): - yield ifile(os.path.join(dirpath, name)) - - def __xrepr__(self, mode="default"): - if mode == "header" or mode == "footer" or mode == "cell": - yield (astyle.style_default, - "%s(%r)" % (self.__class__.__name__, self.base)) - else: - yield (astyle.style_default, repr(self)) - - def __repr__(self): - return "%s.%s(%r)" % \ - (self.__class__.__module__, self.__class__.__name__, self.base) - - -class ipwdentry(object): - """ - ``ipwdentry`` objects encapsulate entries in the Unix user account and - password database. - """ - def __init__(self, id): - self._id = id - self._entry = None - - def __eq__(self, other): - return self.__class__ is other.__class__ and self._id == other._id - - def __ne__(self, other): - return self.__class__ is not other.__class__ or self._id != other._id - - def _getentry(self): - if self._entry is None: - if isinstance(self._id, basestring): - self._entry = pwd.getpwnam(self._id) - else: - self._entry = pwd.getpwuid(self._id) - return self._entry - - def getname(self): - if isinstance(self._id, basestring): - return self._id - else: - return self._getentry().pw_name - name = property(getname, None, None, "User name") - - def getpasswd(self): - return self._getentry().pw_passwd - passwd = property(getpasswd, None, None, "Password") - - def getuid(self): - if isinstance(self._id, basestring): - return self._getentry().pw_uid - else: - return self._id - uid = property(getuid, None, None, "User id") - - def getgid(self): - return self._getentry().pw_gid - gid = property(getgid, None, None, "Primary group id") - - def getgroup(self): - return igrpentry(self.gid) - group = property(getgroup, None, None, "Group") - - def getgecos(self): - return self._getentry().pw_gecos - gecos = property(getgecos, None, None, "Information (e.g. full user name)") - - def getdir(self): - return self._getentry().pw_dir - dir = property(getdir, None, None, "$HOME directory") - - def getshell(self): - return self._getentry().pw_shell - shell = property(getshell, None, None, "Login shell") - - def __xattrs__(self, mode="default"): - return ("name", "passwd", "uid", "gid", "gecos", "dir", "shell") - - def __repr__(self): - return "%s.%s(%r)" % \ - (self.__class__.__module__, self.__class__.__name__, self._id) - - -class ipwd(Table): - """ - List all entries in the Unix user account and password database. - - Example:: - - >>> ipwd | isort("uid") - <IPython.extensions.ipipe.isort key='uid' reverse=False at 0x849efec> - # random - """ - def __iter__(self): - for entry in pwd.getpwall(): - yield ipwdentry(entry.pw_name) - - def __xrepr__(self, mode="default"): - if mode == "header" or mode == "footer" or mode == "cell": - yield (astyle.style_default, "%s()" % self.__class__.__name__) - else: - yield (astyle.style_default, repr(self)) - - -class igrpentry(object): - """ - ``igrpentry`` objects encapsulate entries in the Unix group database. - """ - def __init__(self, id): - self._id = id - self._entry = None - - def __eq__(self, other): - return self.__class__ is other.__class__ and self._id == other._id - - def __ne__(self, other): - return self.__class__ is not other.__class__ or self._id != other._id - - def _getentry(self): - if self._entry is None: - if isinstance(self._id, basestring): - self._entry = grp.getgrnam(self._id) - else: - self._entry = grp.getgrgid(self._id) - return self._entry - - def getname(self): - if isinstance(self._id, basestring): - return self._id - else: - return self._getentry().gr_name - name = property(getname, None, None, "Group name") - - def getpasswd(self): - return self._getentry().gr_passwd - passwd = property(getpasswd, None, None, "Password") - - def getgid(self): - if isinstance(self._id, basestring): - return self._getentry().gr_gid - else: - return self._id - gid = property(getgid, None, None, "Group id") - - def getmem(self): - return self._getentry().gr_mem - mem = property(getmem, None, None, "Members") - - def __xattrs__(self, mode="default"): - return ("name", "passwd", "gid", "mem") - - def __xrepr__(self, mode="default"): - if mode == "header" or mode == "footer" or mode == "cell": - yield (astyle.style_default, "group ") - try: - yield (astyle.style_default, self.name) - except KeyError: - if isinstance(self._id, basestring): - yield (astyle.style_default, self.name_id) - else: - yield (astyle.style_type_number, str(self._id)) - else: - yield (astyle.style_default, repr(self)) - - def __iter__(self): - for member in self.mem: - yield ipwdentry(member) - - def __repr__(self): - return "%s.%s(%r)" % \ - (self.__class__.__module__, self.__class__.__name__, self._id) - - -class igrp(Table): - """ - This ``Table`` lists all entries in the Unix group database. - """ - def __iter__(self): - for entry in grp.getgrall(): - yield igrpentry(entry.gr_name) - - def __xrepr__(self, mode="default"): - if mode == "header" or mode == "footer": - yield (astyle.style_default, "%s()" % self.__class__.__name__) - else: - yield (astyle.style_default, repr(self)) - - -class Fields(object): - def __init__(self, fieldnames, **fields): - self.__fieldnames = [upgradexattr(fieldname) for fieldname in fieldnames] - for (key, value) in fields.iteritems(): - setattr(self, key, value) - - def __xattrs__(self, mode="default"): - return self.__fieldnames - - def __xrepr__(self, mode="default"): - yield (-1, False) - if mode == "header" or mode == "cell": - yield (astyle.style_default, self.__class__.__name__) - yield (astyle.style_default, "(") - for (i, f) in enumerate(self.__fieldnames): - if i: - yield (astyle.style_default, ", ") - yield (astyle.style_default, f.name()) - yield (astyle.style_default, "=") - for part in xrepr(getattr(self, f), "default"): - yield part - yield (astyle.style_default, ")") - elif mode == "footer": - yield (astyle.style_default, self.__class__.__name__) - yield (astyle.style_default, "(") - for (i, f) in enumerate(self.__fieldnames): - if i: - yield (astyle.style_default, ", ") - yield (astyle.style_default, f.name()) - yield (astyle.style_default, ")") - else: - yield (astyle.style_default, repr(self)) - - -class FieldTable(Table, list): - def __init__(self, *fields): - Table.__init__(self) - list.__init__(self) - self.fields = fields - - def add(self, **fields): - self.append(Fields(self.fields, **fields)) - - def __xrepr__(self, mode="default"): - yield (-1, False) - if mode == "header" or mode == "footer": - yield (astyle.style_default, self.__class__.__name__) - yield (astyle.style_default, "(") - for (i, f) in enumerate(self.__fieldnames): - if i: - yield (astyle.style_default, ", ") - yield (astyle.style_default, f) - yield (astyle.style_default, ")") - else: - yield (astyle.style_default, repr(self)) - - def __repr__(self): - return "<%s.%s object with fields=%r at 0x%x>" % \ - (self.__class__.__module__, self.__class__.__name__, - ", ".join(map(repr, self.fields)), id(self)) - - -class List(list): - def __xattrs__(self, mode="default"): - return xrange(len(self)) - - def __xrepr__(self, mode="default"): - yield (-1, False) - if mode == "header" or mode == "cell" or mode == "footer" or mode == "default": - yield (astyle.style_default, self.__class__.__name__) - yield (astyle.style_default, "(") - for (i, item) in enumerate(self): - if i: - yield (astyle.style_default, ", ") - for part in xrepr(item, "default"): - yield part - yield (astyle.style_default, ")") - else: - yield (astyle.style_default, repr(self)) - - -class ienv(Table): - """ - List environment variables. - - Example:: - - >>> ienv - <class 'IPython.extensions.ipipe.ienv'> - """ - - def __iter__(self): - fields = ("key", "value") - for (key, value) in os.environ.iteritems(): - yield Fields(fields, key=key, value=value) - - def __xrepr__(self, mode="default"): - if mode == "header" or mode == "cell": - yield (astyle.style_default, "%s()" % self.__class__.__name__) - else: - yield (astyle.style_default, repr(self)) - - -class ihist(Table): - """ - IPython input history - - Example:: - - >>> ihist - <class 'IPython.extensions.ipipe.ihist'> - >>> ihist(True) # raw mode - <IPython.extensions.ipipe.ihist object at 0x849602c> # random - """ - def __init__(self, raw=True): - self.raw = raw - - def __iter__(self): - api = ipapi.get() - if self.raw: - for line in api.input_hist_raw: - yield line.rstrip("\n") - else: - for line in api.input_hist: - yield line.rstrip("\n") - - -class Alias(object): - """ - Entry in the alias table - """ - def __init__(self, name, args, command): - self.name = name - self.args = args - self.command = command - - def __xattrs__(self, mode="default"): - return ("name", "args", "command") - - -class ialias(Table): - """ - IPython alias list - - Example:: - - >>> ialias - <class 'IPython.extensions.ipipe.ialias'> - """ - def __iter__(self): - api = ipapi.get() - - for (name, (args, command)) in api.alias_manager.alias_table.iteritems(): - yield Alias(name, args, command) - - -class icsv(Pipe): - """ - This ``Pipe`` turns the input (with must be a pipe outputting lines - or an ``ifile``) into lines of CVS columns. - """ - def __init__(self, **csvargs): - """ - Create an ``icsv`` object. ``cvsargs`` will be passed through as - keyword arguments to ``cvs.reader()``. - """ - self.csvargs = csvargs - - def __iter__(self): - input = self.input - if isinstance(input, ifile): - input = input.open("rb") - reader = csv.reader(input, **self.csvargs) - for line in reader: - yield List(line) - - def __xrepr__(self, mode="default"): - yield (-1, False) - if mode == "header" or mode == "footer": - input = getattr(self, "input", None) - if input is not None: - for part in xrepr(input, mode): - yield part - yield (astyle.style_default, " | ") - yield (astyle.style_default, "%s(" % self.__class__.__name__) - for (i, (name, value)) in enumerate(self.csvargs.iteritems()): - if i: - yield (astyle.style_default, ", ") - yield (astyle.style_default, name) - yield (astyle.style_default, "=") - for part in xrepr(value, "default"): - yield part - yield (astyle.style_default, ")") - else: - yield (astyle.style_default, repr(self)) - - def __repr__(self): - args = ", ".join(["%s=%r" % item for item in self.csvargs.iteritems()]) - return "<%s.%s %s at 0x%x>" % \ - (self.__class__.__module__, self.__class__.__name__, args, id(self)) - - -class ix(Table): - """ - Execute a system command and list its output as lines - (similar to ``os.popen()``). - - Examples:: - - >>> ix("ps x") - IPython.extensions.ipipe.ix('ps x') - - >>> ix("find .") | ifile - <IPython.extensions.ipipe.ieval expr=<class 'IPython.extensions.ipipe.ifile'> at 0x8509d2c> - # random - """ - def __init__(self, cmd): - self.cmd = cmd - self._pipeout = None - - def __iter__(self): - (_pipein, self._pipeout) = os.popen4(self.cmd) - _pipein.close() - for l in self._pipeout: - yield l.rstrip("\r\n") - self._pipeout.close() - self._pipeout = None - - def __del__(self): - if self._pipeout is not None and not self._pipeout.closed: - self._pipeout.close() - self._pipeout = None - - def __xrepr__(self, mode="default"): - if mode == "header" or mode == "footer": - yield (astyle.style_default, - "%s(%r)" % (self.__class__.__name__, self.cmd)) - else: - yield (astyle.style_default, repr(self)) - - def __repr__(self): - return "%s.%s(%r)" % \ - (self.__class__.__module__, self.__class__.__name__, self.cmd) - - -class ifilter(Pipe): - """ - Filter an input pipe. Only objects where an expression evaluates to true - (and doesn't raise an exception) are listed. - - Examples:: - - >>> ils | ifilter("_.isfile() and size>1000") - >>> igrp | ifilter("len(mem)") - >>> sys.modules | ifilter(lambda _:_.value is not None) - # all-random - """ - - def __init__(self, expr, globals=None, errors="raiseifallfail"): - """ - Create an ``ifilter`` object. ``expr`` can be a callable or a string - containing an expression. ``globals`` will be used as the global - namespace for calling string expressions (defaulting to IPython's - user namespace). ``errors`` specifies how exception during evaluation - of ``expr`` are handled: - - ``"drop"`` - drop all items that have errors; - - ``"keep"`` - keep all items that have errors; - - ``"keeperror"`` - keep the exception of all items that have errors; - - ``"raise"`` - raise the exception; - - ``"raiseifallfail"`` - raise the first exception if all items have errors; otherwise drop - those with errors (this is the default). - """ - self.expr = expr - self.globals = globals - self.errors = errors - - def __iter__(self): - if callable(self.expr): - test = self.expr - else: - g = getglobals(self.globals) - expr = compile(self.expr, "ipipe-expression", "eval") - def test(item): - return eval(expr, g, AttrNamespace(item)) - - ok = 0 - exc_info = None - for item in xiter(self.input): - try: - if test(item): - yield item - ok += 1 - except (KeyboardInterrupt, SystemExit): - raise - except Exception as exc: - if self.errors == "drop": - pass # Ignore errors - elif self.errors == "keep": - yield item - elif self.errors == "keeperror": - yield exc - elif self.errors == "raise": - raise - elif self.errors == "raiseifallfail": - if exc_info is None: - exc_info = sys.exc_info() - if not ok and exc_info is not None: - raise exc_info[0], exc_info[1], exc_info[2] - - def __xrepr__(self, mode="default"): - if mode == "header" or mode == "footer": - input = getattr(self, "input", None) - if input is not None: - for part in xrepr(input, mode): - yield part - yield (astyle.style_default, " | ") - yield (astyle.style_default, "%s(" % self.__class__.__name__) - for part in xrepr(self.expr, "default"): - yield part - yield (astyle.style_default, ")") - else: - yield (astyle.style_default, repr(self)) - - def __repr__(self): - return "<%s.%s expr=%r at 0x%x>" % \ - (self.__class__.__module__, self.__class__.__name__, - self.expr, id(self)) - - -class ieval(Pipe): - """ - Evaluate an expression for each object in the input pipe. - - Examples:: - - >>> ils | ieval("_.abspath()") - # random - >>> sys.path | ieval(ifile) - # random - """ - - def __init__(self, expr, globals=None, errors="raiseifallfail"): - """ - Create an ``ieval`` object. ``expr`` can be a callable or a string - containing an expression. For the meaning of ``globals`` and - ``errors`` see ``ifilter``. - """ - self.expr = expr - self.globals = globals - self.errors = errors - - def __iter__(self): - if callable(self.expr): - do = self.expr - else: - g = getglobals(self.globals) - expr = compile(self.expr, "ipipe-expression", "eval") - def do(item): - return eval(expr, g, AttrNamespace(item)) - - ok = 0 - exc_info = None - for item in xiter(self.input): - try: - yield do(item) - except (KeyboardInterrupt, SystemExit): - raise - except Exception as exc: - if self.errors == "drop": - pass # Ignore errors - elif self.errors == "keep": - yield item - elif self.errors == "keeperror": - yield exc - elif self.errors == "raise": - raise - elif self.errors == "raiseifallfail": - if exc_info is None: - exc_info = sys.exc_info() - if not ok and exc_info is not None: - raise exc_info[0], exc_info[1], exc_info[2] - - def __xrepr__(self, mode="default"): - if mode == "header" or mode == "footer": - input = getattr(self, "input", None) - if input is not None: - for part in xrepr(input, mode): - yield part - yield (astyle.style_default, " | ") - yield (astyle.style_default, "%s(" % self.__class__.__name__) - for part in xrepr(self.expr, "default"): - yield part - yield (astyle.style_default, ")") - else: - yield (astyle.style_default, repr(self)) - - def __repr__(self): - return "<%s.%s expr=%r at 0x%x>" % \ - (self.__class__.__module__, self.__class__.__name__, - self.expr, id(self)) - - -class ienum(Pipe): - """ - Enumerate the input pipe (i.e. wrap each input object in an object - with ``index`` and ``object`` attributes). - - Examples:: - - >>> xrange(20) | ieval("_,_*_") | ienum | ifilter("index % 2 == 0") | ieval("object") - """ - skip_doctest = True - - def __iter__(self): - fields = ("index", "object") - for (index, object) in enumerate(xiter(self.input)): - yield Fields(fields, index=index, object=object) - - -class isort(Pipe): - """ - Sorts the input pipe. - - Examples:: - - >>> ils | isort("size") - <IPython.extensions.ipipe.isort key='size' reverse=False at 0x849ec2c> - >>> ils | isort("_.isdir(), _.lower()", reverse=True) - <IPython.extensions.ipipe.isort key='_.isdir(), _.lower()' reverse=True at 0x849eacc> - # all-random - """ - - def __init__(self, key=None, globals=None, reverse=False): - """ - Create an ``isort`` object. ``key`` can be a callable or a string - containing an expression (or ``None`` in which case the items - themselves will be sorted). If ``reverse`` is true the sort order - will be reversed. For the meaning of ``globals`` see ``ifilter``. - """ - self.key = key - self.globals = globals - self.reverse = reverse - - def __iter__(self): - if self.key is None: - items = sorted(xiter(self.input), reverse=self.reverse) - elif callable(self.key): - items = sorted(xiter(self.input), key=self.key, reverse=self.reverse) - else: - g = getglobals(self.globals) - key = compile(self.key, "ipipe-expression", "eval") - def realkey(item): - return eval(key, g, AttrNamespace(item)) - items = sorted(xiter(self.input), key=realkey, reverse=self.reverse) - for item in items: - yield item - - def __xrepr__(self, mode="default"): - if mode == "header" or mode == "footer": - input = getattr(self, "input", None) - if input is not None: - for part in xrepr(input, mode): - yield part - yield (astyle.style_default, " | ") - yield (astyle.style_default, "%s(" % self.__class__.__name__) - for part in xrepr(self.key, "default"): - yield part - if self.reverse: - yield (astyle.style_default, ", ") - for part in xrepr(True, "default"): - yield part - yield (astyle.style_default, ")") - else: - yield (astyle.style_default, repr(self)) - - def __repr__(self): - return "<%s.%s key=%r reverse=%r at 0x%x>" % \ - (self.__class__.__module__, self.__class__.__name__, - self.key, self.reverse, id(self)) - - -tab = 3 # for expandtabs() - -def _format(field): - if isinstance(field, str): - text = repr(field.expandtabs(tab))[1:-1] - elif isinstance(field, unicode): - text = repr(field.expandtabs(tab))[2:-1] - elif isinstance(field, datetime.datetime): - # Don't use strftime() here, as this requires year >= 1900 - text = "%04d-%02d-%02d %02d:%02d:%02d.%06d" % \ - (field.year, field.month, field.day, - field.hour, field.minute, field.second, field.microsecond) - elif isinstance(field, datetime.date): - text = "%04d-%02d-%02d" % (field.year, field.month, field.day) - else: - text = repr(field) - return text - - -class Display(object): - class __metaclass__(type): - def __ror__(self, input): - return input | self() - - def __init__(self, input=None): - self.input = input - - def __ror__(self, input): - self.input = input - return self - - def display(self): - pass - - -class iless(Display): - cmd = "less --quit-if-one-screen --LONG-PROMPT --LINE-NUMBERS --chop-long-lines --shift=8 --RAW-CONTROL-CHARS" - - def display(self): - try: - pager = os.popen(self.cmd, "w") - try: - for item in xiter(self.input): - first = False - for attr in xattrs(item, "default"): - if first: - first = False - else: - pager.write(" ") - attr = upgradexattr(attr) - if not isinstance(attr, SelfDescriptor): - pager.write(attr.name()) - pager.write("=") - pager.write(str(attr.value(item))) - pager.write("\n") - finally: - pager.close() - except Exception as exc: - print "%s: %s" % (exc.__class__.__name__, str(exc)) - - -class _RedirectIO(object): - def __init__(self,*args,**kwargs): - """ - Map the system output streams to self. - """ - self.stream = StringIO.StringIO() - self.stdout = sys.stdout - sys.stdout = self - self.stderr = sys.stderr - sys.stderr = self - - def write(self, text): - """ - Write both to screen and to self. - """ - self.stream.write(text) - self.stdout.write(text) - if "\n" in text: - self.stdout.flush() - - def writelines(self, lines): - """ - Write lines both to screen and to self. - """ - self.stream.writelines(lines) - self.stdout.writelines(lines) - self.stdout.flush() - - def restore(self): - """ - Restore the default system streams. - """ - self.stdout.flush() - self.stderr.flush() - sys.stdout = self.stdout - sys.stderr = self.stderr - - -class icap(Table): - """ - Execute a python string and capture any output to stderr/stdout. - - Examples:: - - >>> import time - >>> icap("for i in range(10): print i, time.sleep(0.1)") - - """ - skip_doctest = True - - def __init__(self, expr, globals=None): - self.expr = expr - self.globals = globals - log = _RedirectIO() - try: - exec(expr, getglobals(globals)) - finally: - log.restore() - self.stream = log.stream - - def __iter__(self): - self.stream.seek(0) - for line in self.stream: - yield line.rstrip("\r\n") - - def __xrepr__(self, mode="default"): - if mode == "header" or mode == "footer": - yield (astyle.style_default, - "%s(%r)" % (self.__class__.__name__, self.expr)) - else: - yield (astyle.style_default, repr(self)) - - def __repr__(self): - return "%s.%s(%r)" % \ - (self.__class__.__module__, self.__class__.__name__, self.expr) - - -def xformat(value, mode, maxlength): - align = None - full = True - width = 0 - text = astyle.Text() - for (style, part) in xrepr(value, mode): - # only consider the first result - if align is None: - if isinstance(style, int): - # (style, text) really is (alignment, stop) - align = style - full = part - continue - else: - align = -1 - full = True - if not isinstance(style, int): - text.append((style, part)) - width += len(part) - if width >= maxlength and not full: - text.append((astyle.style_ellisis, "...")) - width += 3 - break - if align is None: # default to left alignment - align = -1 - return (align, width, text) - - - -import astyle - -class idump(Display): - # The approximate maximum length of a column entry - maxattrlength = 200 - - # Style for column names - style_header = astyle.Style.fromstr("white:black:bold") - - def __init__(self, input=None, *attrs): - Display.__init__(self, input) - self.attrs = [upgradexattr(attr) for attr in attrs] - self.headerpadchar = " " - self.headersepchar = "|" - self.datapadchar = " " - self.datasepchar = "|" - - def display(self): - stream = Term.cout - allattrs = [] - attrset = set() - colwidths = {} - rows = [] - for item in xiter(self.input): - row = {} - attrs = self.attrs - if not attrs: - attrs = xattrs(item, "default") - for attr in attrs: - if attr not in attrset: - allattrs.append(attr) - attrset.add(attr) - colwidths[attr] = len(attr.name()) - try: - value = attr.value(item) - except (KeyboardInterrupt, SystemExit): - raise - except Exception as exc: - value = exc - (align, width, text) = xformat(value, "cell", self.maxattrlength) - colwidths[attr] = max(colwidths[attr], width) - # remember alignment, length and colored parts - row[attr] = (align, width, text) - rows.append(row) - - stream.write("\n") - for (i, attr) in enumerate(allattrs): - attrname = attr.name() - self.style_header(attrname).write(stream) - spc = colwidths[attr] - len(attrname) - if i < len(colwidths)-1: - stream.write(self.headerpadchar*spc) - stream.write(self.headersepchar) - stream.write("\n") - - for row in rows: - for (i, attr) in enumerate(allattrs): - (align, width, text) = row[attr] - spc = colwidths[attr] - width - if align == -1: - text.write(stream) - if i < len(colwidths)-1: - stream.write(self.datapadchar*spc) - elif align == 0: - spc = colwidths[attr] - width - spc1 = spc//2 - spc2 = spc-spc1 - stream.write(self.datapadchar*spc1) - text.write(stream) - if i < len(colwidths)-1: - stream.write(self.datapadchar*spc2) - else: - stream.write(self.datapadchar*spc) - text.write(stream) - if i < len(colwidths)-1: - stream.write(self.datasepchar) - stream.write("\n") - - -class AttributeDetail(Table): - """ - ``AttributeDetail`` objects are use for displaying a detailed list of object - attributes. - """ - def __init__(self, object, descriptor): - self.object = object - self.descriptor = descriptor - - def __iter__(self): - return self.descriptor.iter(self.object) - - def name(self): - return self.descriptor.name() - - def attrtype(self): - return self.descriptor.attrtype(self.object) - - def valuetype(self): - return self.descriptor.valuetype(self.object) - - def doc(self): - return self.descriptor.doc(self.object) - - def shortdoc(self): - return self.descriptor.shortdoc(self.object) - - def value(self): - return self.descriptor.value(self.object) - - def __xattrs__(self, mode="default"): - attrs = ("name()", "attrtype()", "valuetype()", "value()", "shortdoc()") - if mode == "detail": - attrs += ("doc()",) - return attrs - - def __xrepr__(self, mode="default"): - yield (-1, True) - valuetype = self.valuetype() - if valuetype is not noitem: - for part in xrepr(valuetype): - yield part - yield (astyle.style_default, " ") - yield (astyle.style_default, self.attrtype()) - yield (astyle.style_default, " ") - yield (astyle.style_default, self.name()) - yield (astyle.style_default, " of ") - for part in xrepr(self.object): - yield part - - -try: - from ibrowse import ibrowse -except ImportError: - # No curses (probably Windows) => try igrid - try: - from igrid import igrid - except ImportError: - # no wx either => use ``idump`` as the default display. - defaultdisplay = idump - else: - defaultdisplay = igrid - __all__.append("igrid") -else: - defaultdisplay = ibrowse - __all__.append("ibrowse") - - -# If we're running under IPython, register our objects with IPython's -# generic function ``result_display``, else install a displayhook -# directly as sys.displayhook -if generics is not None: - def display_display(obj): - return obj.display() - generics.result_display.when_type(Display)(display_display) - - def display_tableobject(obj): - return display_display(defaultdisplay(obj)) - generics.result_display.when_type(Table)(display_tableobject) - - def display_tableclass(obj): - return display_tableobject(obj()) - generics.result_display.when_type(Table.__metaclass__)(display_tableclass) -else: - def installdisplayhook(): - _originalhook = sys.displayhook - def displayhook(obj): - if isinstance(obj, type) and issubclass(obj, Table): - obj = obj() - if isinstance(obj, Table): - obj = defaultdisplay(obj) - if isinstance(obj, Display): - return obj.display() - else: - _originalhook(obj) - sys.displayhook = displayhook - installdisplayhook() diff --git a/IPython/deathrow/iplib.py b/IPython/deathrow/iplib.py deleted file mode 100644 index aae8ab9..0000000 --- a/IPython/deathrow/iplib.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python -# encoding: utf-8 -""" -A backwards compatibility layer for IPython.iplib. - -Previously, IPython had an IPython.iplib module. IPython.iplib has been moved -to IPython.core.iplib and is being refactored. This new module is provided -for backwards compatability. We strongly encourage everyone to start using -the new code in IPython.core.iplib. -""" - -#----------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#----------------------------------------------------------------------------- - -from warnings import warn - -msg = """ -This module (IPython.iplib) has been moved to a new location -(IPython.core.iplib) and is being refactored. Please update your code -to use the new IPython.core.iplib module""" - -warn(msg, category=DeprecationWarning, stacklevel=1) - -from IPython.core.iplib import * diff --git a/IPython/deathrow/ipy_constants.py b/IPython/deathrow/ipy_constants.py deleted file mode 100644 index fa27e6c..0000000 --- a/IPython/deathrow/ipy_constants.py +++ /dev/null @@ -1,669 +0,0 @@ -""" Module with physical constants for use with ipython, profile -"physics". - -Definition of Fundamental Physical Constants, CODATA Recommended Values - -Source, Peter J. Mohr and Barry N. Taylor, -CODATA Recommended Values of the Fundamental -Physical Constants, 1998 - -Website: physics.nist.gov/constants -""" -# License: BSD-like -# Copyright: Gael Varoquaux (gael.varoquaux@normalesup.org) - -# inspired by maxima's physconst.mac by Cliff Yapp - -#from math import * # math MUST be imported BEFORE PhysicalQInteractive -from IPython.extensions.PhysicalQInteractive import PhysicalQuantityInteractive - -# Math constants: - -# Pi mathematical constants -pi = 3.141592653589793238462643383279502884197169399375105820974944592 - -# Universal Constants -#------------------------------------------------------------------------- - -c = PhysicalQuantityInteractive(299792458 , 'm/s') -c.__doc__ = """speed of light in vacuum""" -c.__doc__ = "speed of light in vacuum" - -u_0 = PhysicalQuantityInteractive(4*pi*1E-7 , 'N/(A**2)') -u_0.__doc__ = """magnetic constant""" -mu_0 = PhysicalQuantityInteractive(4*pi*1E-7 , 'N/(A**2)') - -epsilon_0 = PhysicalQuantityInteractive(8.854187817E-12 , 'F/m') -epsilon_0.__doc__ = """electric constant """ - -Z_0 = PhysicalQuantityInteractive(376.730313461 , 'ohm') -Z_0.__doc__ = """characteristic impedance of vacuum """ - -G = PhysicalQuantityInteractive(6.673E-11 , 'm**3/(kg*s**2)') -G.__doc__ = """Newtonian constant of gravitation """ - - -h = PhysicalQuantityInteractive(6.62606876E-34 , 'J*s') -h.__doc__ = """Planck constant """ - - -h_eV = PhysicalQuantityInteractive(4.13566727E-15 , 'eV*s') -h_eV.__doc__ = """Planck constant in eVs """ - - -h_bar = PhysicalQuantityInteractive(1.054571596E-34 , 'J*s') -h_bar.__doc__ = """Hbar""" - - -h_bar_eV = PhysicalQuantityInteractive(6.58211889E-16 , 'eV*s') -h_bar_eV.__doc__ = """Hbar in eV""" - - -P_m = PhysicalQuantityInteractive(2.1767E-8 , 'kg') -P_m.__doc__ = """Planck mass""" - - -P_l = PhysicalQuantityInteractive(1.6160E-35 , 'm') -P_l.__doc__ = """Planck length """ - - -P_t = PhysicalQuantityInteractive(5.3906E-44 , 's') -P_t.__doc__ = """Planck time """ - -# Electromagnetic Constants -#------------------------------------------------------------------------ - -_e = PhysicalQuantityInteractive(1.602176462E-19 , 'C') -_e.__doc__ = """elementary charge""" -q = _e - - -capitalphi_0 = PhysicalQuantityInteractive(2.067833636E-15 , 'Wb') -capitalphi_0.__doc__ = """magnetic flux quantum """ -mfq_0 = PhysicalQuantityInteractive(2.067833636E-15 , 'Wb') - - -G_0 = PhysicalQuantityInteractive(7.748091696E-5 , 'S') -G_0.__doc__ = """conductance quantum """ - - -K_J = PhysicalQuantityInteractive(483597.898E9 , 'Hz/V') -K_J.__doc__ = """Josephson constant""" - - -R_K = PhysicalQuantityInteractive(25812.807572 , 'ohm') -R_K.__doc__ = """von Klitzing constant""" - - -u_B = PhysicalQuantityInteractive(927.400899E-26 , 'J/T') -u_B.__doc__ = """Bohr magneton""" - -ueVT_B = PhysicalQuantityInteractive(5.788381749E-5 , 'eV/T') -ueVT_B.__doc__ = """Bohr magneton in eV T-1""" - - -u_N = PhysicalQuantityInteractive(5.05078317E-27 , 'J/T') -u_N.__doc__ = """nuclear magneton """ - -ueVT_N = PhysicalQuantityInteractive(3.152451238E-8 , 'eV/T') -ueVT_N.__doc__ = """nuclear magneton in eV T-1 """ - -# Atomic and Nuclear Constants -# General -#------------------------------------------------------------------------- -# fine-structure constant -alpha = 7.297352533E-3 - - -Ry = PhysicalQuantityInteractive(10973731.568549 , '1/m') -Ry.__doc__ = """Rydberg constant """ -Ry_INF = PhysicalQuantityInteractive(10973731.568549 , '1/m') - - -a_0 = PhysicalQuantityInteractive(0.5291772083E-10 , 'm') -a_0.__doc__ = """Bohr radius """ - - -E_h = PhysicalQuantityInteractive(4.35974381E-18 , 'J') -E_h.__doc__ = """Hartree energy """ - -Eev_h = PhysicalQuantityInteractive(27.2113834 , 'eV') -Eev_h.__doc__ = """Hartree energy in eV """ - - -qcir2 = PhysicalQuantityInteractive(3.636947516E-4 , 'm**2/s') -qcir2.__doc__ = """quantum of circulation h/(2me) """ - -qcir = PhysicalQuantityInteractive(7.273895032E-4 , 'm**2/s') -qcir.__doc__ = """quantum of circulation h/(me) """ - -# Electroweak -#------------------------------------------------------------------------- - -Fcc = PhysicalQuantityInteractive(1.16639E-5 , '1/GeV**2') -Fcc.__doc__ = """Fermi coupling constant """ -# weak mixing angled W (on-shell scheme) -wma_W = 0.2224 - -# Electron, e- -#------------------------------------------------------------------------- - -m_e = PhysicalQuantityInteractive(9.10938188E-31 , 'kg') -m_e.__doc__ = """electron mass """ - -m_e_u = PhysicalQuantityInteractive(5.485799110E-4 , 'amu') -m_e_u.__doc__ = """electron mass (electron relative atomic mass times amu)""" - -me_J = PhysicalQuantityInteractive(8.18710414E-14 , 'J') -me_J.__doc__ = """electron mass - energy equivalent """ - -me_MeV = PhysicalQuantityInteractive(0.510998902 , 'MeV') -me_MeV.__doc__ = """electron mass - energy equivalent in MeV""" - -# electron-muon mass ratio -memu = 4.83633210E-3 - -# electron-tau mass ratio -metau = 2.87555E-4 - -# electron-proton mass ratio -memp = 5.446170232E-4 - -# electron-neutron mass ratio -memn = 5.438673462E-4 - -# electron-deuteron mass ratio -memd = 2.7244371170E-4 - -# electron to alpha particle mass ratio -memalpha = 1.3709335611E-4 - - -echargeemass = PhysicalQuantityInteractive(-1.758820174E11 , 'C/kg') -echargeemass.__doc__ = """electron charge to mass quotient """ - - -Molar_e = PhysicalQuantityInteractive(5.485799110E-7 , 'kg/mol') -Molar_e.__doc__ = """electron molar mass """ - - -lambdaC = PhysicalQuantityInteractive(2.426310215E-12 , 'm') -lambdaC.__doc__ = """Compton wavelength """ - - -r_e = PhysicalQuantityInteractive(2.817940285E-15 , 'm') -r_e.__doc__ = """classical electron radius """ - - -sigma_e = PhysicalQuantityInteractive(0.665245854E-28 , 'm**2') -sigma_e.__doc__ = """Thomson cross section """ - - -u_e = PhysicalQuantityInteractive(-928.476362E-26 , 'J/T') -u_e.__doc__ = """electron magnetic moment """ - -# electron magnetic moment to Bohr magneton ratio -ueuB = -1.0011596521869 - -# electron magnetic moment to nuclear magneton ratio -ueuN = -1838.2819660 - -# electron magnetic moment anomaly |ue|/uB - 1 -a_e = 1.1596521869E-3 - -# electron g-factor -g_e = -2.0023193043737 - -# electron-muon magnetic moment ratio -ueuu = 206.7669720 - -# electron-proton magnetic moment ratio -ueup = -658.2106875 - -# electron to shielded proton magnetic moment ratio (H2O, sphere, 25 C) -ueusp = -658.2275954 - -# electron-neutron magnetic moment ratio -ueun = 960.92050 - -# electron-deuteron magnetic moment ratio -ueud = -2143.923498 - -# electron to shielded helione magnetic moment ratio (gas, sphere, 25 C) -ueush = 864.058255 - - -gamma_e = PhysicalQuantityInteractive(1.760859794E11 , '1/(s*T)') -gamma_e.__doc__ = """electron gyromagnetic ratio """ - -# Muon, u- -#------------------------------------------------------------------------- - -m_u = PhysicalQuantityInteractive(1.88353109E-28 , 'kg') -m_u.__doc__ = """muon mass """ - -mu_u = PhysicalQuantityInteractive(0.1134289168 , 'amu') -mu_u.__doc__ = """muon mass in muon relative atomic mass times amu """ - - -muc2_J = PhysicalQuantityInteractive(1.69283332E-11 , 'J') -muc2_J.__doc__ = """energy equivalent """ - -muc2_MeV = PhysicalQuantityInteractive(105.6583568 , 'MeV') -muc2_MeV.__doc__ = """energy equivalent in MeV """ - -# muon-electron mass ratio -mume = 206.7682657 - -# muon-tau mass ratio -mum = 5.94572E-2 - -# muon-proton mass ratio -mump = 0.1126095173 - -# muon-neutron mass ratio -mumn = 0.1124545079 - - -Molar_u = PhysicalQuantityInteractive(0.1134289168E-3 , 'kg/mol') -Molar_u.__doc__ = """muon molar mass """ - - -lambda_C_u = PhysicalQuantityInteractive(11.73444197E-15 , 'm') -lambda_C_u.__doc__ = """muon Compton wavelength """ - - -uu = PhysicalQuantityInteractive(-4.49044813E-26 , 'J/T') -uu.__doc__ = """muon magnetic moment """ - -# ratio of muon magnetic moment to Bohr magneton ratio -uuuB = -4.84197085E-3 - -# ratio of muon magnetic moment to nuclear magneton ratio -uuuN = -8.89059770 - -# muon magnetic moment anomaly |uu|/(e /2mu) - 1 -a_u = 1.16591602E-3 - -# muon g-factor -2(1 + au) -g_u = -2.0023318320 - -# muon-proton magnetic moment ratio -uuup = -3.18334539 - -# Tau, tau- -#------------------------------------------------------------------------- - -m_tau = PhysicalQuantityInteractive(3.16788E-27 , 'kg') -m_tau.__doc__ = """tau mass """ - -mu_tau = PhysicalQuantityInteractive(1.90774 , 'amu') -mu_tau.__doc__ = """tau mass (tau relative atomic mass times amu) """ - - -mtauc2_J = PhysicalQuantityInteractive(2.84715E-10 , 'J') -mtauc2_J.__doc__ = """tau mass energy equivalent """ - - -mtauc2_MeV = PhysicalQuantityInteractive(1777.05 , 'MeV') -mtauc2_MeV.__doc__ = """tau mass energy equivalent in MeV """ - -# tau-electron mass ratio -mtaume = 3477.60 - -# tau-muon mass ratio -mtaumu = 16.8188 - -# tau-proton mass ratio -mtaump = 1.89396 - -# tau-neutron mass ratio -mtaumn = 1.89135 - - -Molar_tau = PhysicalQuantityInteractive(1.90774E-3 , 'kg/mol') -Molar_tau.__doc__ = """tau molar mass """ - - -lambda_C_tau = PhysicalQuantityInteractive(0.69770E-15 , 'm') -lambda_C_tau.__doc__ = """tau Compton wavelength """ - -# Proton, p -#------------------------------------------------------------------------- - -m_p = PhysicalQuantityInteractive(1.67262158E-27 , 'kg') -m_p.__doc__ = """proton mass """ - -mu_p = PhysicalQuantityInteractive(1.00727646688 , 'amu') -mu_p.__doc__ = """proton mass (proton relative atomic mass times amu) """ - - -mpc2_J = PhysicalQuantityInteractive(1.50327731E-10 , 'J') -mpc2_J.__doc__ = """energy equivalent """ - -mpc2_MeV = PhysicalQuantityInteractive(938.271998 , 'MeV') -mpc2_MeV.__doc__ = """energy equivalent in MeV """ - -# proton-electron mass ratio -mpme = 1836.1526675 - -# proton-muon mass ratio -mpmu = 8.88024408 - -# proton-tau mass ratio -mpmtau = 0.527994 - -# proton-neutron mass ratio -mpmn = 0.99862347855 - - -emp = PhysicalQuantityInteractive(9.57883408E7 , 'C/kg') -emp.__doc__ = """proton charge to mass quotient """ - - -Molar_p = PhysicalQuantityInteractive(1.00727646688E-3 , 'kg/mol') -Molar_p.__doc__ = """proton molar mass """ - - -lambda_C_p = PhysicalQuantityInteractive(1.321409847E-15 , 'm') -lambda_C_p.__doc__ = """proton Compton wavelength h/mpc """ - - -up = PhysicalQuantityInteractive(1.410606633E-26 , 'J/T') -up.__doc__ = """proton magnetic moment """ - -# proton magnetic moment to Bohr magneton ratio -upuB = 1.521032203E-3 - -# proton magnetic moment to nuclear magneton ratio -upuN = 2.792847337 - -# proton g-factor 2up/uN -g_p = 5.585694675 - -# proton-neutron magnetic moment ratio -upun = -1.45989805 - - -usp = PhysicalQuantityInteractive(1.410570399E-26 , 'J/T') -usp.__doc__ = """shielded proton magnetic moment (H2O, sphere, 25 C)""" - -# shielded proton magnetic moment to Bohr magneton ratio -uspuB = 1.520993132E-3 - -# shielded proton magnetic moment to nuclear magneton ratio -uspuN = 2.792775597 - -# proton magnetic shielding correction 1 - u p/up (H2O, sphere, 25 C) -spc = 25.687E-6 - - -gamma_p = PhysicalQuantityInteractive(2.67522212E8 , '1/(s*T)') -gamma_p.__doc__ = """proton gyromagnetic ratio """ - - -gamma_sp = PhysicalQuantityInteractive(2.67515341E8 , '1/(s*T)') -gamma_sp.__doc__ = """shielded proton gyromagnetic ratio (H2O, sphere, 25 C)""" - -# Neutron, n -#------------------------------------------------------------------------- - -m_n = PhysicalQuantityInteractive(1.67492716E-27 , 'kg') -m_n.__doc__ = """neutron mass """ - -mu_n = PhysicalQuantityInteractive(1.00866491578 , 'amu') -mu_n.__doc__ = """neutron mass (neutron relative atomic mass times amu) """ - - -mnc2_J = PhysicalQuantityInteractive(1.50534946E-10 , 'J') -mnc2_J.__doc__ = """neutron mass energy equivalent """ - - -mnc2_MeV = PhysicalQuantityInteractive(939.565330 , 'MeV') -mnc2_MeV.__doc__ = """neutron mass energy equivalent in MeV """ - -# neutron-electron mass ratio -mnme = 1838.6836550 - -# neutron-muon mass ratio -mnmu = 8.89248478 - -# neutron-tau mass ratio -mnm = 0.528722 - -# neutron-proton mass ratio -mnmp = 1.00137841887 - - -Molar_n = PhysicalQuantityInteractive(1.00866491578E-3 , 'kg/mol') -Molar_n.__doc__ = """neutron molar mass """ - - -lambda_C_n = PhysicalQuantityInteractive(1.319590898E-15 , 'm') -lambda_C_n.__doc__ = """neutron Compton wavelength""" - - -un = PhysicalQuantityInteractive(-0.96623640E-26 , 'J/T') -un.__doc__ = """neutron magnetic moment """ - -# neutron magnetic moment to Bohr magneton ratio -unuB = -1.04187563E-3 - -# neutron magnetic moment to nuclear magneton ratio -unuN = -1.91304272 - -# neutron g-factor -g_n = -3.82608545 - -# neutron-electron magnetic moment ratio -unue = 1.04066882E-3 - -# neutron-proton magnetic moment ratio -unup = -0.68497934 - -# neutron to shielded proton magnetic moment ratio (H2O, sphere, 25 C) -unusp = -0.68499694 - - -gamma_n = PhysicalQuantityInteractive(1.83247188E8 , '1/(s*T)') -gamma_n.__doc__ = """neutron gyromagnetic ratio """ - -# Deuteron, d -#------------------------------------------------------------------------- - -m_d = PhysicalQuantityInteractive(3.34358309E-27 , 'kg') -m_d.__doc__ = """deuteron mass """ - - -mu_d = PhysicalQuantityInteractive(2.01355321271 , 'amu') -mu_d.__doc__ = """deuteron mass (deuteron relative atomic mass times amu) """ - - -mdc2_J = PhysicalQuantityInteractive(3.00506262E-10 , 'J') -mdc2_J.__doc__ = """deuteron mass energy equivalent """ - - -mdc2_eV = PhysicalQuantityInteractive(1875.612762 , 'MeV') -mdc2_eV.__doc__ = """deuteron mass energy equivalent in MeV """ - -# deuteron-electron mass ratio -mdme = 3670.4829550 - -# deuteron-proton mass ratio -mdmp = 1.99900750083 - - -Molar_d = PhysicalQuantityInteractive(2.01355321271E-3 , 'kg/mol') -Molar_d.__doc__ = """deuteron molar mass """ - - -ud = PhysicalQuantityInteractive(0.433073457E-26 , 'J/T') -ud.__doc__ = """deuteron magnetic moment """ - -# deuteron magnetic moment to Bohr magneton ratio -uduB = 0.4669754556E-3 - -# deuteron magnetic moment to nuclear magneton ratio -uduN = 0.8574382284 - -# deuteron-electron magnetic moment ratio -udue = -4.664345537E-4 - -# deuteron-proton magnetic moment ratio -udup = 0.3070122083 - -# deuteron-neutron magnetic moment ratio -udun = -0.44820652 - -# Helion, h -#------------------------------------------------------------------------- - -m_h = PhysicalQuantityInteractive(5.00641174E-27 , 'kg') -m_h.__doc__ = """helion mass """ - - -mu_h = PhysicalQuantityInteractive(3.01493223469 , 'amu') -mu_h.__doc__ = """helion mass (helion relative atomic mass times amu) """ - - -mhc2_J = PhysicalQuantityInteractive(4.49953848E-10 , 'J') -mhc2_J.__doc__ = """helion mass energy equivalent """ - -mhc2_MeV = PhysicalQuantityInteractive(2808.39132 , 'MeV') -mhc2_MeV.__doc__ = """helion mass energy equivalent in MeV """ - -# helion-electron mass ratio -mhme = 5495.885238 - -# helion-proton mass ratio -mhmp = 2.99315265850 - - -Molar_h = PhysicalQuantityInteractive(3.01493223469E-3 , 'kg/mol') -Molar_h.__doc__ = """helion molar mass """ - - -ush = PhysicalQuantityInteractive(-1.074552967E-26 , 'J/T') -ush.__doc__ = """shielded helion magnetic moment (gas, sphere, 25 C)""" - -# shielded helion magnetic moment to Bohr magneton ratio -ushuB = -1.158671474E-3 - -# shielded helion magnetic moment to nuclear magneton ratio -ushuN = -2.127497718 - -# shielded helion to proton magnetic moment ratio (gas, sphere, 25 C) -ushup = -0.761766563 - -# shielded helion to shielded proton magnetic moment ratio (gas/H2O, spheres, 25 C) -ushusp = -0.7617861313 - - -gamma_h = PhysicalQuantityInteractive(2.037894764E8 , '1/(s*T)') -gamma_h.__doc__ = """shielded helion gyromagnetic (gas, sphere, 25 C) """ - -# Alpha particle, -#------------------------------------------------------------------------- - -m_alpha = PhysicalQuantityInteractive(6.64465598E-27 , 'kg') -m_alpha.__doc__ = """alpha particle mass """ - -mu_alpha = PhysicalQuantityInteractive(4.0015061747 , 'amu') -mu_alpha.__doc__ = """alpha particle mass (alpha particle relative atomic mass times amu) """ - - -malphac2_J = PhysicalQuantityInteractive(5.97191897E-10 , 'J') -malphac2_J.__doc__ = """alpha particle mass energy equivalent """ - - -malphac2_MeV = PhysicalQuantityInteractive(3727.37904 , 'MeV') -malphac2_MeV.__doc__ = """alpha particle mass energy equivalent in MeV """ - -# alpha particle to electron mass ratio -malphame = 7294.299508 - -# alpha particle to proton mass ratio -malphamp = 3.9725996846 - - -Molar_alpha = PhysicalQuantityInteractive(4.0015061747E-3 , 'kg/mol') -Molar_alpha.__doc__ = """alpha particle molar mass""" - -# PHYSICO-CHEMICAL -#------------------------------------------------------------------------- - -N_A = PhysicalQuantityInteractive(6.02214199E23 , '1/mol') -N_A.__doc__ = """Avogadro constant """ -L = PhysicalQuantityInteractive(6.02214199E23 , '1/mol') - - -m_u = PhysicalQuantityInteractive(1.66053873E-27 , 'kg') -m_u.__doc__ = """atomic mass constant mu = 112m(12C) = 1 u = 10E-3 kg mol-1/NA""" -# atomic mass constant mu = 112m(12C) = 1 u = 10E-3 kg mol-1/NA -amu = m_u - - -muc2_J = PhysicalQuantityInteractive(1.49241778E-10 , 'J') -muc2_J.__doc__ = """energy equivalent of the atomic mass constant""" - - -muc2_MeV = PhysicalQuantityInteractive(931.494013 , 'MeV') -muc2_MeV.__doc__ = """energy equivalent of the atomic mass constant in MeV """ - - -F = PhysicalQuantityInteractive(96485.3415 , 'C/mol') -F.__doc__ = """Faraday constant""" - - -N_Ah = PhysicalQuantityInteractive(3.990312689E-10 , 'J*s/mol') -N_Ah.__doc__ = """molar Planck constant """ - - -R = PhysicalQuantityInteractive(8.314472 , 'J/(mol*K)') -R.__doc__ = """molar gas constant """ - - -k_J = PhysicalQuantityInteractive(1.3806503E-23 , 'J/K') -k_J.__doc__ = """Boltzmann constant """ - - -k_eV = PhysicalQuantityInteractive(8.617342E-5 , 'eV/K') -k_eV.__doc__ = """Boltzmann constant in eV """ - - -n_0 = PhysicalQuantityInteractive(2.6867775E25 , '1/m**3') -n_0.__doc__ = """Loschmidt constant NA/Vm """ - - -Vm_1 = PhysicalQuantityInteractive(22.413996E-3 , 'm**3/mol') -Vm_1.__doc__ = """molar volume of ideal gas RT/p T = 273.15 K, p = 101.325 kPa """ - -Vm_2 = PhysicalQuantityInteractive(22.710981E-3 , 'm**3/mol') -Vm_2.__doc__ = """molar volume of ideal gas RT/p T = 273.15 K, p = 100 kPa """ - -# Sackur-Tetrode constant (absolute entropy constant) 52 + ln_(2 mukT1/h2)3/2kT1/p0 -# T1 = 1 K, p0 = 100 kPa -S_0R_1 = -1.1517048 -# T1 = 1 K, p0 = 101.325 kPa -S_0R_2 = -1.1648678 - - -sigma = PhysicalQuantityInteractive(5.670400E-8 , 'W/(m**2*K**4)') -sigma.__doc__ = """Stefan-Boltzmann constant """ - - -c_1 = PhysicalQuantityInteractive(3.74177107E-16 , 'W*m**2') -c_1.__doc__ = """first radiation constant""" - - -c_1L = PhysicalQuantityInteractive(1.191042722E-16 , 'W*m**2/sr') -c_1L.__doc__ = """first radiation constant for spectral radiance""" - - -c_2 = PhysicalQuantityInteractive(1.4387752E-2 , 'm*K') -c_2.__doc__ = """second radiation constant""" - - -b = PhysicalQuantityInteractive(2.8977686E-3 , 'm*K') -b.__doc__ = """Wien displacement law constant b = maxT = c2/4.965 114231... """ - diff --git a/IPython/deathrow/ipy_defaults.py b/IPython/deathrow/ipy_defaults.py deleted file mode 100644 index 4937422..0000000 --- a/IPython/deathrow/ipy_defaults.py +++ /dev/null @@ -1,62 +0,0 @@ -""" Set default options for IPython. - -Just import this module to get reasonable defaults for everything. - -These configurations used to be performed in ipythonrc (or ipythonrc.ini). -Therefore importing this in your config files makes ipython basically -ignore your ipythonrc. This is *not* imported by default, you need to import -this manually in one of your config files. - -You can further override these defaults in e.g. your ipy_user_config.py, -ipy_profile_PROFILENAME etc. - -""" - -import IPython.utils.rlineimpl as readline -from IPython.core import ipapi -ip = ipapi.get() - -o = ip.options - -o.colors = "Linux" -o.color_info=1 -o.confirm_exit=1 -o.pprint=1 -o.multi_line_specials=1 -o.xmode="Context" - - -o.prompt_in1='In [\#]: ' -o.prompt_in2 =' .\D.: ' -o.prompt_out = 'Out[\#]: ' -o.prompts_pad_left=1 - -o.autoindent = 1 - -o.readline_remove_delims="-/~" -o.readline_merge_completions=1 - -o.readline = 1 - -rlopts = """\ -tab: complete -"\C-l": possible-completions -set show-all-if-ambiguous on -"\C-o": tab-insert -"\M-i": " " -"\M-o": "\d\d\d\d" -"\M-I": "\d\d\d\d" -"\C-r": reverse-search-history -"\C-s": forward-search-history -"\C-p": history-search-backward -"\C-n": history-search-forward -"\e[A": history-search-backward -"\e[B": history-search-forward -"\C-k": kill-line -"\C-u": unix-line-discard""" - -if readline.have_readline: - for cmd in rlopts.split('\n'): - readline.parse_and_bind(cmd) - - diff --git a/IPython/deathrow/ipy_kitcfg.py b/IPython/deathrow/ipy_kitcfg.py deleted file mode 100644 index 57409c8..0000000 --- a/IPython/deathrow/ipy_kitcfg.py +++ /dev/null @@ -1,80 +0,0 @@ -import os,sys - -import ipy_rehashdir,glob -from ipy_rehashdir import selflaunch, PyLauncher - -def pylaunchers(): - """Create launchers for python scripts in cwd and store them in alias table - - This is useful if you want to invoke .py scripts from ipykit session, - just adding .py files in PATH does not work without file association. - - .ipy files will be run like macros. - - """ - fs = glob.glob('*.py') + glob.glob('*.ipy') - for f in fs: - l = PyLauncher(f) - n = os.path.splitext(f)[0] - ip.define_alias(n, l) - ip.magic('store '+n) - - -def exta_imports(): - # add some modules that you'd want to be bundled in the ipykit - # library zip file here. Do this if you get ImportErrors from scripts you - # try to launch with 'py' or pylaunchers. In theory you could include - # the whole stdlib here for full script coverage - - # note that this is never run, it's just here for py2exe - import distutils.dir_util - -def kitroot(): - return os.environ.get('IPYKITROOT', None) - -def main(): - - if not kitroot(): - print "Can't configure ipykit, IPYKITROOT should be set." - return - - os.environ["PATH"] = os.environ["PATH"] + ";" + kitroot() + "\\bin;" - ip.push("pylaunchers") - cmds = ip.db.get('syscmdlist', None) - if cmds is None: - ip.magic('rehashx') - cmds = ip.db.get('syscmdlist', []) - #print cmds - if 'sc1' in cmds: - print "Default editor: Sc1" - import ipy_editors - ipy_editors.scite('sc1') - - # for icp, imv, imkdir, etc. - import ipy_fsops - -greeting = """\n\n === Welcome to ipykit === - -%quickref - learn quickly about IPython. - -""" - -def ipython_firstrun(ip): - - print "First run of ipykit - configuring" - - ip.define_alias('py',selflaunch) - ip.define_alias('d','dir /w /og /on') - ip.magic('store py') - ip.magic('store d') - - bins = kitroot() +'/bin' - - print greeting - -def init_ipython(ipy): - global ip - ip = ipy - main() - - diff --git a/IPython/deathrow/ipy_legacy.py b/IPython/deathrow/ipy_legacy.py deleted file mode 100644 index aa7a148..0000000 --- a/IPython/deathrow/ipy_legacy.py +++ /dev/null @@ -1,62 +0,0 @@ -""" Legacy stuff - -Various stuff that are there for historical / familiarity reasons. - -This is automatically imported by default profile, though not other profiles -(e.g. 'sh' profile). - -Stuff that is considered obsolete / redundant is gradually moved here. - -""" - -from IPython.core import ipapi -ip = ipapi.get() - -import os,sys - -from IPython.utils.genutils import * - -# use rehashx - -def magic_rehash(self, parameter_s = ''): - """Update the alias table with all entries in $PATH. - - This version does no checks on execute permissions or whether the - contents of $PATH are truly files (instead of directories or something - else). For such a safer (but slower) version, use %rehashx.""" - - # This function (and rehashx) manipulate the alias_table directly - # rather than calling magic_alias, for speed reasons. A rehash on a - # typical Linux box involves several thousand entries, so efficiency - # here is a top concern. - - path = filter(os.path.isdir,os.environ.get('PATH','').split(os.pathsep)) - alias_table = self.shell.alias_table - for pdir in path: - for ff in os.listdir(pdir): - # each entry in the alias table must be (N,name), where - # N is the number of positional arguments of the alias. - alias_table[ff] = (0,ff) - # Make sure the alias table doesn't contain keywords or builtins - self.shell.alias_table_validate() - # Call again init_auto_alias() so we get 'rm -i' and other modified - # aliases since %rehash will probably clobber them - self.shell.init_auto_alias() - -ip.define_magic("rehash", magic_rehash) - -# Exit -def magic_Quit(self, parameter_s=''): - """Exit IPython without confirmation (like %Exit).""" - - self.shell.ask_exit() - -ip.define_magic("Quit", magic_Quit) - - -# make it autocallable fn if you really need it -def magic_p(self, parameter_s=''): - """Just a short alias for Python's 'print'.""" - exec 'print ' + parameter_s in self.shell.user_ns - -ip.define_magic("p", magic_p) diff --git a/IPython/deathrow/ipy_p4.py b/IPython/deathrow/ipy_p4.py deleted file mode 100644 index 0bda2fe..0000000 --- a/IPython/deathrow/ipy_p4.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Add %p4 magic for pythonic p4 (Perforce) usage. -""" - -from IPython.core import ipapi -ip = ipapi.get() - -import os,sys,marshal - -import ipy_stock_completers - -def p4_f(self, parameter_s=''): - cmd = 'p4 -G ' + parameter_s - fobj = os.popen(cmd) - out = [] - while 1: - try: - out.append(marshal.load(fobj)) - except EOFError: - break - - return out - -def p4d(fname): - return os.popen('p4 where ' + fname).read().split()[0] - -ip.push("p4d") - -ip.define_magic('p4', p4_f) - -p4_commands = """\ -add admin annotate branch branches change changes changelist -changelists client clients counter counters delete depot depots -describe diff diff2 dirs edit filelog files fix fixes flush fstat -group groups have help info integrate integrated job jobs jobspec -label labels labelsync lock logger login logout monitor obliterate -opened passwd print protect rename reopen resolve resolved revert -review reviews set submit sync tag tickets triggers typemap unlock -user users verify workspace workspaces where""" - -def p4_completer(self,event): - return ipy_stock_completers.vcs_completer(p4_commands, event) - -ip.set_hook('complete_command', p4_completer, str_key = '%p4') -ip.set_hook('complete_command', p4_completer, str_key = 'p4') - diff --git a/IPython/deathrow/ipy_profile_none.py b/IPython/deathrow/ipy_profile_none.py deleted file mode 100644 index 195aa87..0000000 --- a/IPython/deathrow/ipy_profile_none.py +++ /dev/null @@ -1,4 +0,0 @@ -""" Config file for 'default' profile """ - -# get various stuff that are there for historical / familiarity reasons -import ipy_legacy \ No newline at end of file diff --git a/IPython/deathrow/ipy_profile_numpy.py b/IPython/deathrow/ipy_profile_numpy.py deleted file mode 100644 index 6659884..0000000 --- a/IPython/deathrow/ipy_profile_numpy.py +++ /dev/null @@ -1,24 +0,0 @@ -""" IPython 'numpy' profile, to preload NumPy. - -This profile loads the math/cmath modules as well as all of numpy. - -It exposes numpy via the 'np' shorthand as well for convenience. -""" - -from IPython.core import ipapi -import ipy_defaults - -def main(): - ip = ipapi.get() - - try: - ip.ex("import math,cmath") - ip.ex("import numpy") - ip.ex("import numpy as np") - - ip.ex("from numpy import *") - - except ImportError: - print "Unable to start NumPy profile, is numpy installed?" - -main() diff --git a/IPython/deathrow/ipy_profile_scipy.py b/IPython/deathrow/ipy_profile_scipy.py deleted file mode 100644 index 25defe4..0000000 --- a/IPython/deathrow/ipy_profile_scipy.py +++ /dev/null @@ -1,29 +0,0 @@ -""" IPython 'scipy' profile, preloads NumPy and SciPy. - -This profile loads the math/cmath modules as well as all of numpy and scipy. - -It exposes numpy and scipy via the 'np' and 'sp' shorthands as well for -convenience. -""" - -from IPython.core import ipapi -import ipy_defaults - -def main(): - ip = ipapi.get() - - try: - ip.ex("import math,cmath") - ip.ex("import numpy") - ip.ex("import scipy") - - ip.ex("import numpy as np") - ip.ex("import scipy as sp") - - ip.ex("from numpy import *") - ip.ex("from scipy import *") - - except ImportError: - print "Unable to start scipy profile, are numpy and scipy installed?" - -main() diff --git a/IPython/deathrow/ipy_profile_sh.py b/IPython/deathrow/ipy_profile_sh.py deleted file mode 100644 index f394ef1..0000000 --- a/IPython/deathrow/ipy_profile_sh.py +++ /dev/null @@ -1,268 +0,0 @@ -"""Shell mode for IPython. - -Start ipython in shell mode by invoking "ipython -p sh" - -(the old version, "ipython -p pysh" still works but this is the more "modern" -shell mode and is recommended for users who don't care about pysh-mode -compatibility) -""" - -from IPython.core import ipapi -from IPython.core.error import TryNext -import os,re,textwrap - -# The import below effectively obsoletes your old-style ipythonrc[.ini], -# so consider yourself warned! - -import ipy_defaults - -def main(): - ip = ipapi.get() - o = ip.options - # autocall to "full" mode (smart mode is default, I like full mode) - - o.autocall = 2 - - # Jason Orendorff's path class is handy to have in user namespace - # if you are doing shell-like stuff - try: - ip.ex("from IPython.external.path import path" ) - except ImportError: - pass - - # beefed up %env is handy in shell mode - import envpersist - - # To see where mycmd resides (in path/aliases), do %which mycmd - import ipy_which - - # tab completers for hg, svn, ... - import ipy_app_completers - - # To make executables foo and bar in mybin usable without PATH change, do: - # %rehashdir c:/mybin - # %store foo - # %store bar - import ipy_rehashdir - - # does not work without subprocess module! - #import ipy_signals - - ip.ex('import os') - ip.ex("def up(): os.chdir('..')") - ip.user_ns['LA'] = LastArgFinder() - - # You can assign to _prompt_title variable - # to provide some extra information for prompt - # (e.g. the current mode, host/username...) - - ip.user_ns['_prompt_title'] = '' - - # Nice prompt - o.prompt_in1= r'\C_Green${_prompt_title}\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#> ' - o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green> ' - o.prompt_out= '<\#> ' - - from IPython.core import release - - import sys - # Non-chatty banner - o.banner = "IPython %s [on Py %s]\n" % (release.version,sys.version.split(None,1)[0]) - - - ip.default_option('cd','-q') - ip.default_option('macro', '-r') - # If you only rarely want to execute the things you %edit... - #ip.default_option('edit','-x') - - - o.prompts_pad_left="1" - # Remove all blank lines in between prompts, like a normal shell. - o.separate_in="0" - o.separate_out="0" - o.separate_out2="0" - - # now alias all syscommands - - db = ip.db - - syscmds = db.get("syscmdlist",[] ) - if not syscmds: - print textwrap.dedent(""" - System command list not initialized, probably the first run... - running %rehashx to refresh the command list. Run %rehashx - again to refresh command list (after installing new software etc.) - """) - ip.magic('rehashx') - syscmds = db.get("syscmdlist") - - # lowcase aliases on win32 only - if os.name == 'posix': - mapper = lambda s:s - else: - def mapper(s): return s.lower() - - for cmd in syscmds: - # print "sys",cmd #dbg - noext, ext = os.path.splitext(cmd) - if ext.lower() == '.exe': - cmd = noext - - key = mapper(cmd) - if key not in ip.alias_manager.alias_table: - # Dots will be removed from alias names, since ipython - # assumes names with dots to be python code - - ip.define_alias(key.replace('.',''), cmd) - - # win32 is crippled w/o cygwin, try to help it a little bit - if sys.platform == 'win32': - if 'cygwin' in os.environ['PATH'].lower(): - # use the colors of cygwin ls (recommended) - ip.define_alias('d', 'ls -F --color=auto') - else: - # get icp, imv, imkdir, igrep, irm,... - ip.load('ipy_fsops') - - # and the next best thing to real 'ls -F' - ip.define_alias('d','dir /w /og /on') - - ip.set_hook('input_prefilter', slash_prefilter_f) - extend_shell_behavior(ip) - -class LastArgFinder: - """ Allow $LA to work as "last argument of previous command", like $! in bash - - To call this in normal IPython code, do LA() - """ - def __call__(self, hist_idx = None): - ip = ipapi.get() - if hist_idx is None: - return str(self) - return ip.input_hist_raw[hist_idx].strip().split()[-1] - def __str__(self): - ip = ipapi.get() - for cmd in reversed(ip.input_hist_raw): - parts = cmd.strip().split() - if len(parts) < 2 or parts[-1] in ['$LA', 'LA()']: - continue - return parts[-1] - return "" - -def slash_prefilter_f(self,line): - """ ./foo, ~/foo and /bin/foo now run foo as system command - - Removes the need for doing !./foo, !~/foo or !/bin/foo - """ - from IPython.utils import genutils - if re.match('(?:[.~]|/[a-zA-Z_0-9]+)/', line): - return "get_ipython().system(" + genutils.make_quoted_expr(line)+")" - raise TryNext - -# XXX You do not need to understand the next function! -# This should probably be moved out of profile - -def extend_shell_behavior(ip): - - # Instead of making signature a global variable tie it to IPSHELL. - # In future if it is required to distinguish between different - # shells we can assign a signature per shell basis - ip.__sig__ = 0xa005 - # mark the IPSHELL with this signature - ip.user_ns['__builtins__'].__dict__['__sig__'] = ip.__sig__ - - from IPython.external.Itpl import ItplNS - from IPython.utils.genutils import shell - # utility to expand user variables via Itpl - # xxx do something sensible with depth? - ip.var_expand = lambda cmd, lvars=None, depth=2: \ - str(ItplNS(cmd, ip.user_ns, get_locals())) - - def get_locals(): - """ Substituting a variable through Itpl deep inside the IPSHELL stack - requires the knowledge of all the variables in scope upto the last - IPSHELL frame. This routine simply merges all the local variables - on the IPSHELL stack without worrying about their scope rules - """ - import sys - # note lambda expression constitues a function call - # hence fno should be incremented by one - getsig = lambda fno: sys._getframe(fno+1).f_globals \ - ['__builtins__'].__dict__['__sig__'] - getlvars = lambda fno: sys._getframe(fno+1).f_locals - # trackback until we enter the IPSHELL - frame_no = 1 - sig = ip.__sig__ - fsig = ~sig - while fsig != sig : - try: - fsig = getsig(frame_no) - except (AttributeError, KeyError): - frame_no += 1 - except ValueError: - # stack is depleted - # call did not originate from IPSHELL - return {} - first_frame = frame_no - # walk further back until we exit from IPSHELL or deplete stack - try: - while(sig == getsig(frame_no+1)): - frame_no += 1 - except (AttributeError, KeyError, ValueError): - pass - # merge the locals from top down hence overriding - # any re-definitions of variables, functions etc. - lvars = {} - for fno in range(frame_no, first_frame-1, -1): - lvars.update(getlvars(fno)) - #print '\n'*5, first_frame, frame_no, '\n', lvars, '\n'*5 #dbg - return lvars - - def _runlines(lines): - """Run a string of one or more lines of source. - - This method is capable of running a string containing multiple source - lines, as if they had been entered at the IPython prompt. Since it - exposes IPython's processing machinery, the given strings can contain - magic calls (%magic), special shell access (!cmd), etc.""" - - # We must start with a clean buffer, in case this is run from an - # interactive IPython session (via a magic, for example). - ip.resetbuffer() - lines = lines.split('\n') - more = 0 - command = '' - for line in lines: - # skip blank lines so we don't mess up the prompt counter, but do - # NOT skip even a blank line if we are in a code block (more is - # true) - # if command is not empty trim the line - if command != '' : - line = line.strip() - # add the broken line to the command - if line and line[-1] == '\\' : - command += line[0:-1] + ' ' - more = True - continue - else : - # add the last (current) line to the command - command += line - if command or more: - # push to raw history, so hist line numbers stay in sync - ip.input_hist_raw.append("# " + command + "\n") - - more = ip.push_line(ip.prefilter(command,more)) - command = '' - # IPython's runsource returns None if there was an error - # compiling the code. This allows us to stop processing right - # away, so the user gets the error message at the right place. - if more is None: - break - # final newline in case the input didn't have it, so that the code - # actually does get executed - if more: - ip.push_line('\n') - - ip.runlines = _runlines - -main() diff --git a/IPython/deathrow/ipy_profile_zope.py b/IPython/deathrow/ipy_profile_zope.py deleted file mode 100644 index d8cbfe4..0000000 --- a/IPython/deathrow/ipy_profile_zope.py +++ /dev/null @@ -1,324 +0,0 @@ -# -*- coding: utf-8 -*- -""" An ipython profile for zope and plone. - -Some ideas stolen from http://www.tomster.org. - - -Authors -------- -- Stefan Eletzhofer <stefan.eletzhofer@inquant.de> -""" - -# File: ipy_profile_zope.py -# -# Copyright (c) InQuant GmbH -# -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. - -from IPython.core import ipapi -from IPython.core import release -from types import StringType -import sys -import os -import textwrap - -sys_oldstdin = sys.stdin - -# The import below effectively obsoletes your old-style ipythonrc[.ini], -# so consider yourself warned! -# import ipy_defaults - -_marker = [] -def shasattr(obj, attr, acquire=False): - """ See Archetypes/utils.py - """ - if not acquire: - obj = obj.aq_base - return getattr(obj, attr, _marker) is not _marker - -class ZopeDebug(object): - def __init__(self): - - self.instancehome = os.environ.get( "INSTANCE_HOME" ) - - configfile = os.environ.get( "CONFIG_FILE" ) - if configfile is None and self.instancehome is not None: - configfile = os.path.join( self.instancehome, "etc", "zope.conf" ) - - if configfile is None: - raise RuntimeError( "CONFIG_FILE env not set" ) - - print "CONFIG_FILE=", configfile - print "INSTANCE_HOME=", self.instancehome - - self.configfile = configfile - - try: - from Zope2 import configure - except ImportError: - from Zope import configure - - configure( configfile ) - - try: - import Zope2 - app = Zope2.app() - except ImportError: - import Zope - app = Zope.app() - - from Testing.makerequest import makerequest - self.app = makerequest( app ) - - try: - self._make_permissive() - print "Permissive security installed" - except: - print "Permissive security NOT installed" - - self._pwd = self.portal or self.app - - try: - from zope.component import getSiteManager - from zope.component import getGlobalSiteManager - from zope.app.component.hooks import setSite - - if self.portal is not None: - setSite( self.portal ) - - gsm = getGlobalSiteManager() - sm = getSiteManager() - - if sm is gsm: - print "ERROR SETTING SITE!" - except: - pass - - - @property - def utils(self): - class Utils(object): - commit = self.commit - sync = self.sync - objectInfo = self.objectInfo - ls = self.ls - pwd = self.pwd - cd = self.cd - su = self.su - getCatalogInfo = self.getCatalogInfo - - @property - def cwd(self): - return self.pwd() - - return Utils() - - @property - def namespace(self): - return dict( utils=self.utils, app=self.app, portal=self.portal ) - - @property - def portal(self): - portals = self.app.objectValues( "Plone Site" ) - if len(portals): - return portals[0] - else: - raise KeyError( "No Plone Site found.") - - def pwd(self): - return self._pwd - - def _make_permissive(self): - """ - Make a permissive security manager with all rights. Hell, - we're developers, aren't we? Security is for whimps. :) - """ - from Products.CMFCore.tests.base.security import PermissiveSecurityPolicy - import AccessControl - from AccessControl.SecurityManagement import newSecurityManager - from AccessControl.SecurityManager import setSecurityPolicy - - _policy = PermissiveSecurityPolicy() - self.oldpolicy = setSecurityPolicy(_policy) - newSecurityManager(None, AccessControl.User.system) - - def su(self, username): - """ Change to named user. - """ - # TODO Make it easy to change back to permissive security. - user = self.portal.acl_users.getUser(username) - if not user: - print "Can't find %s in %s" % (username, self.portal.acl_users) - return - - from AccessControl import ZopeSecurityPolicy - import AccessControl - from AccessControl.SecurityManagement import newSecurityManager, getSecurityManager - from AccessControl.SecurityManager import setSecurityPolicy - - _policy = ZopeSecurityPolicy - self.oldpolicy = setSecurityPolicy(_policy) - wrapped_user = user.__of__(self.portal.acl_users) - newSecurityManager(None, user) - print 'User changed.' - return getSecurityManager().getUser() - - def getCatalogInfo(self, obj=None, catalog='portal_catalog', query=None, sort_on='created', sort_order='reverse' ): - """ Inspect portal_catalog. Pass an object or object id for a - default query on that object, or pass an explicit query. - """ - if obj and query: - print "Ignoring %s, using query." % obj - - catalog = self.portal.get(catalog) - if not catalog: - return 'No catalog' - - indexes = catalog._catalog.indexes - if not query: - if type(obj) is StringType: - cwd = self.pwd() - obj = cwd.unrestrictedTraverse( obj ) - # If the default in the signature is mutable, its value will - # persist across invocations. - query = {} - if indexes.get('path'): - from string import join - path = join(obj.getPhysicalPath(), '/') - query.update({'path': path}) - if indexes.get('getID'): - query.update({'getID': obj.id, }) - if indexes.get('UID') and shasattr(obj, 'UID'): - query.update({'UID': obj.UID(), }) - if indexes.get(sort_on): - query.update({'sort_on': sort_on, 'sort_order': sort_order}) - if not query: - return 'Empty query' - results = catalog(**query) - - result_info = [] - for r in results: - rid = r.getRID() - if rid: - result_info.append( - {'path': catalog.getpath(rid), - 'metadata': catalog.getMetadataForRID(rid), - 'indexes': catalog.getIndexDataForRID(rid), } - ) - else: - result_info.append({'missing': rid}) - - if len(result_info) == 1: - return result_info[0] - return result_info - - def commit(self): - """ - Commit the transaction. - """ - try: - import transaction - transaction.get().commit() - except ImportError: - get_transaction().commit() - - def sync(self): - """ - Sync the app's view of the zodb. - """ - self.app._p_jar.sync() - - def objectInfo( self, o ): - """ - Return a descriptive string of an object - """ - Title = "" - t = getattr( o, 'Title', None ) - if t: - Title = t() - return {'id': o.getId(), - 'Title': Title, - 'portal_type': getattr( o, 'portal_type', o.meta_type), - 'folderish': o.isPrincipiaFolderish - } - - def cd( self, path ): - """ - Change current dir to a specific folder. - - cd( ".." ) - cd( "/plone/Members/admin" ) - cd( portal.Members.admin ) - etc. - """ - if type(path) is not StringType: - path = '/'.join(path.getPhysicalPath()) - cwd = self.pwd() - x = cwd.unrestrictedTraverse( path ) - if x is None: - raise KeyError( "Can't cd to %s" % path ) - - print "%s -> %s" % ( self.pwd().getId(), x.getId() ) - self._pwd = x - - def ls( self, x=None ): - """ - List object(s) - """ - if type(x) is StringType: - cwd = self.pwd() - x = cwd.unrestrictedTraverse( x ) - if x is None: - x = self.pwd() - if x.isPrincipiaFolderish: - return [self.objectInfo(o) for id, o in x.objectItems()] - else: - return self.objectInfo( x ) - -zope_debug = None - -def ipy_set_trace(): - from IPython.core import debugger - debugger.Pdb().set_trace() - -def main(): - global zope_debug - ip = ipapi.get() - o = ip.options - # autocall to "full" mode (smart mode is default, I like full mode) - - SOFTWARE_HOME = os.environ.get( "SOFTWARE_HOME" ) - sys.path.append( SOFTWARE_HOME ) - print "SOFTWARE_HOME=%s\n" % SOFTWARE_HOME - - zope_debug = ZopeDebug() - - # <HACK ALERT> - import pdb; - pdb.set_trace = ipy_set_trace - # </HACK ALERT> - - # I like my banner minimal. - o.banner = "ZOPE Py %s IPy %s\n" % (sys.version.split('\n')[0],release.version) - - print textwrap.dedent("""\ - ZOPE mode iPython shell. - - Bound names: - app - portal - utils.{ %s } - - Uses the $SOFTWARE_HOME and $CONFIG_FILE environment - variables. - """ % ( ",".join([ x for x in dir(zope_debug.utils) if not x.startswith("_") ] ) ) ) - - - sys.stdin = sys_oldstdin - ip.user_ns.update( zope_debug.namespace ) - - -main() -# vim: set ft=python ts=4 sw=4 expandtab : diff --git a/IPython/deathrow/ipy_traits_completer.py b/IPython/deathrow/ipy_traits_completer.py deleted file mode 100644 index f609270..0000000 --- a/IPython/deathrow/ipy_traits_completer.py +++ /dev/null @@ -1,219 +0,0 @@ -"""Traits-aware tab completion. - -This module provides a custom tab-completer that intelligently hides the names -that the enthought.traits library (http://code.enthought.com/traits) -automatically adds to all objects that inherit from its base HasTraits class. - - -Activation -========== - -To use this, put in your ~/.ipython/ipy_user_conf.py file: - - from ipy_traits_completer import activate - activate([complete_threshold]) - -The optional complete_threshold argument is the minimal length of text you need -to type for tab-completion to list names that are automatically generated by -traits. The default value is 3. Note that at runtime, you can change this -value simply by doing: - - import ipy_traits_completer - ipy_traits_completer.COMPLETE_THRESHOLD = 4 - - -Usage -===== - -The system works as follows. If t is an empty object that HasTraits, then -(assuming the threshold is at the default value of 3): - -In [7]: t.ed<TAB> - -doesn't show anything at all, but: - -In [7]: t.edi<TAB> -t.edit_traits t.editable_traits - -shows these two names that come from traits. This allows you to complete on -the traits-specific names by typing at least 3 letters from them (or whatever -you set your threshold to), but to otherwise not see them in normal completion. - - -Notes -===== - - - This requires Python 2.4 to work (I use sets). I don't think anyone is - using traits with 2.3 anyway, so that's OK. - - - Imports from enthought.traits are deferred until an object with a class that - looks like it subclasses from HasTraits comes along. This test is done by - looking at the name of the class and its superclasses. -""" - -############################################################################# -# IPython imports -from IPython.core.error import TryNext -from IPython.core.ipapi import get as ipget -from IPython.utils.dir2 import dir2 -try: - set -except: - from sets import Set as set - -############################################################################# -# Module constants - -# The completion threshold -# This is currently implemented as a module global, since this sytem isn't -# likely to be modified at runtime by multiple instances. If needed in the -# future, we can always make it local to the completer as a function attribute. -COMPLETE_THRESHOLD = 3 - -# Set of names that Traits automatically adds to ANY traits-inheriting object. -# These are the names we'll filter out. -TRAIT_NAMES = None -def get_trait_names(): - global TRAIT_NAMES - from enthought.traits.api import HasTraits - if TRAIT_NAMES is None: - TRAIT_NAMES = set( dir2(HasTraits()) ) - set( dir2(object()) ) - else: - return TRAIT_NAMES - -############################################################################# -# Code begins - -def looks_like_isinstance(obj, classname): - """ Return True if the object has a class or superclass with the given class - name. - - Ignores old-style classes. - """ - from types import InstanceType - - t = type(obj) - if t is InstanceType: - # Old-style classes. - return False - elif t.__name__ == classname: - return True - for klass in t.__mro__: - if klass.__name__ == classname: - return True - return False - -def trait_completer(self,event): - """A custom IPython tab-completer that is traits-aware. - - It tries to hide the internal traits attributes, and reveal them only when - it can reasonably guess that the user really is after one of them. - """ - - #print '\nevent is:',event # dbg - symbol_parts = event.symbol.split('.') - base = '.'.join(symbol_parts[:-1]) - #print 'base:',base # dbg - - oinfo = self._ofind(base) - if not oinfo['found']: - raise TryNext - - obj = oinfo['obj'] - # OK, we got the object. See if it's traits, else punt - if not looks_like_isinstance(obj, 'HasTraits'): - raise TryNext - - # Defer import until here so as not to require Traits until we get something - # that looks like it might be a HasTraits instance. - from enthought.traits.api import HasTraits - if not isinstance(obj, HasTraits): - raise TryNext - - # it's a traits object, don't show the tr* attributes unless the completion - # begins with 'tr' - attrs = dir2(obj) - # Now, filter out the attributes that start with the user's request - attr_start = symbol_parts[-1] - if attr_start: - attrs = [a for a in attrs if a.startswith(attr_start)] - - # Let's also respect the user's readline_omit__names setting: - omit__names = ipget().options.readline_omit__names - if omit__names == 1: - attrs = [a for a in attrs if not a.startswith('__')] - elif omit__names == 2: - attrs = [a for a in attrs if not a.startswith('_')] - - #print '\nastart:<%r>' % attr_start # dbg - - if len(attr_start)<COMPLETE_THRESHOLD: - attrs = list(set(attrs) - get_trait_names()) - - # The base of the completion, so we can form the final results list - bdot = base+'.' - - tcomp = [bdot+a for a in attrs] - #print 'tcomp:',tcomp - return tcomp - -def activate(complete_threshold = COMPLETE_THRESHOLD): - """Activate the Traits completer. - - :Keywords: - complete_threshold : int - The minimum number of letters that a user must type in order to - activate completion of traits-private names.""" - - if not (isinstance(complete_threshold,int) and - complete_threshold>0): - e='complete_threshold must be a positive integer, not %r' % \ - complete_threshold - raise ValueError(e) - - # Set the module global - global COMPLETE_THRESHOLD - COMPLETE_THRESHOLD = complete_threshold - - # Activate the traits aware completer - ip = ipget() - ip.set_hook('complete_command', trait_completer, re_key = '.*') - - -############################################################################# -if __name__ == '__main__': - # Testing/debugging - from enthought.traits.api import HasTraits - - # A sorted list of the names we'll filter out - TNL = list(get_trait_names()) - TNL.sort() - - # Make a few objects for testing - class TClean(HasTraits): pass - class Bunch(object): pass - # A clean traits object - t = TClean() - # A nested object containing t - f = Bunch() - f.t = t - # And a naked new-style object - o = object() - - ip = ipget().IP - - # A few simplistic tests - - # Reset the threshold to the default, in case the test is running inside an - # instance of ipython that changed it - import ipy_traits_completer - ipy_traits_completer.COMPLETE_THRESHOLD = 3 - - assert ip.complete('t.ed') ==[] - - # For some bizarre reason, these fail on the first time I run them, but not - # afterwards. Traits does some really weird stuff at object instantiation - # time... - ta = ip.complete('t.edi') - assert ta == ['t.edit_traits', 't.editable_traits'] - print 'Tests OK' diff --git a/IPython/deathrow/ipy_vimserver.py b/IPython/deathrow/ipy_vimserver.py deleted file mode 100644 index cbe6d9f..0000000 --- a/IPython/deathrow/ipy_vimserver.py +++ /dev/null @@ -1,245 +0,0 @@ -""" Integration with gvim, by Erich Heine - -Provides a %vim magic command, and reuses the same vim session. Uses -unix domain sockets for communication between vim and IPython. ipy.vim is -available in doc/examples of the IPython distribution. - -Slightly touched up email announcement (and description how to use it) by -Erich Heine is here: - -Ive recently been playing with ipython, and like it quite a bit. I did -however discover a bit of frustration, namely with editor interaction. -I am a gvim user, and using the command edit on a new file causes -ipython to try and run that file as soon as the text editor opens -up. The -x command of course fixes this, but its still a bit annoying, -switching windows to do a run file, then back to the text -editor. Being a heavy tab user in gvim, another annoyance is not being -able to specify weather a new tab is how I choose to open the file. - -Not being one to shirk my open source duties (and seeing this as a -good excuse to poke around ipython internals), Ive created a script -for having gvim and ipython work very nicely together. Ive attached -both to this email (hoping of course that the mailing list allows such -things). - -There are 2 files: - -ipy_vimserver.py -- this file contains the ipython stuff -ipy.vim -- this file contains the gvim stuff - -In combination they allow for a few functionalities: - -#1. the vim magic command. This is a fancy wrapper around the edit -magic, that allows for a new option, -t, which opens the text in a new -gvim tab. Otherwise it works the same as edit -x. (it internally -calls edit -x). This magic command also juggles vim server management, -so when it is called when there is not a gvim running, it creates a -new gvim instance, named after the ipython session name. Once such a -gvim instance is running, it will be used for subsequent uses of the -vim command. - -#2. ipython - gvim interaction. Once a file has been opened with the -vim magic (and a session set up, see below), pressing the F5 key in -vim will cause the calling ipython instance to execute run -filename.py. (if you typo like I do, this is very useful) - -#3. ipython server - this is a thread wich listens on a unix domain -socket, and runs commands sent to that socket. - -Note, this only works on POSIX systems, that allow for AF_UNIX type -sockets. It has only been tested on linux (a fairly recent debian -testing distro). - -To install it put, the ipserver.py in your favorite locaion for -sourcing ipython scripts. I put the ipy.vim in -~/.vim/after/ftplugin/python/. - -To use (this can be scripted im sure, but i usually have 2 or 3 -ipythons and corresponding gvims open): - -import ipy_vimserver -ipy_vimserver.setup('sessionname') - -(Editors note - you can probably add these to your ipy_user_conf.py) - -Then use ipython as you normally would, until you need to edit -something. Instead of edit, use the vim magic. Thats it! - -""" - -from IPython.core import ipapi -from IPython.core.error import TryNext - -import socket, select -import os, threading, subprocess -import re - -try: - ERRCONDS = select.POLLHUP|select.POLLERR -except AttributeError: - raise ImportError("Vim server not supported on this platform - select " - "missing necessary POLLHUP/POLLERR functionality") - -SERVER = None -ip = ipapi.get() - -# this listens to a unix domain socket in a separate thread, so that comms -# between a vim instance and ipython can happen in a fun and productive way -class IpyServer(threading.Thread): - def __init__(self, sname): - super(IpyServer, self).__init__() - self.keep_running = True - self.__sname = sname - self.socket = socket.socket(socket.AF_UNIX) - self.poller = select.poll() - self.current_conns = dict() - self.setDaemon(True) - - def listen(self): - self.socket.bind(self.__sname) - self.socket.listen(1) - - def __handle_error(self, socket): - if socket == self.socket.fileno(): - self.keep_running = False - for a in self.current_conns.values(): - a.close() - return False - else: - y = self.current_conns[socket] - del self.current_conns[socket] - y.close() - self.poller.unregister(socket) - - def serve_me(self): - self.listen() - self.poller.register(self.socket,select.POLLIN|ERRCONDS) - - while self.keep_running: - try: - avail = self.poller.poll(1) - except: - continue - - if not avail: continue - - for sock, conds in avail: - if conds & (ERRCONDS): - if self.__handle_error(sock): continue - else: break - - if sock == self.socket.fileno(): - y = self.socket.accept()[0] - self.poller.register(y, select.POLLIN|ERRCONDS) - self.current_conns[y.fileno()] = y - else: y = self.current_conns.get(sock) - - self.handle_request(y) - - os.remove(self.__sname) - - run = serve_me - - def stop(self): - self.keep_running = False - - def handle_request(self,sock): - sock.settimeout(1) - while self.keep_running: - try: - x = sock.recv(4096) - except socket.timeout: - pass - else: - break - self.do_it(x) - - def do_it(self, data): - data = data.split('\n') - cmds = list() - for line in data: - cmds.append(line) - ip.runlines(cmds) - - -# try to help ensure that the unix domain socket is cleaned up proper -def shutdown_server(self): - if SERVER: - SERVER.stop() - SERVER.join(3) - raise TryNext - -ip.set_hook('shutdown_hook', shutdown_server, 10) - -# this fun function exists to make setup easier for all, and makes the -# vimhook function ready for instance specific communication -def setup(sessionname='',socketdir=os.path.expanduser('~/.ipython/')): - global SERVER - - if sessionname: - session = sessionname - elif os.environ.get('IPY_SESSION'): - session = os.environ.get('IPY_SESSION') - else: - session = 'IPYS' - vimhook.vimserver=session - vimhook.ipyserver = os.path.join(socketdir, session) - if not SERVER: - SERVER = IpyServer(vimhook.ipyserver) - SERVER.start() - - - -# calls gvim, with all ops happening on the correct gvim instance for this -# ipython instance. it then calls edit -x (since gvim will return right away) -# things of note: it sets up a special environment, so that the ipy.vim script -# can connect back to the ipython instance and do fun things, like run the file -def vimhook(self, fname, line): - env = os.environ.copy() - vserver = vimhook.vimserver.upper() - check = subprocess.Popen('gvim --serverlist', stdout = subprocess.PIPE, - shell=True) - check.wait() - cval = [l for l in check.stdout.readlines() if vserver in l] - - if cval: - vimargs = '--remote%s' % (vimhook.extras,) - else: - vimargs = '' - vimhook.extras = '' - - env['IPY_SESSION'] = vimhook.vimserver - env['IPY_SERVER'] = vimhook.ipyserver - - if line is None: line = '' - else: line = '+' + line - vim_cmd = 'gvim --servername %s %s %s %s' % (vimhook.vimserver, vimargs, - line, fname) - subprocess.call(vim_cmd, env=env, shell=True) - - -#default values to keep it sane... -vimhook.vimserver = '' -vimhook.ipyserver = '' - -ip.set_hook('editor',vimhook) - -# this is set up so more vim specific commands can be added, instead of just -# the current -t. all thats required is a compiled regex, a call to do_arg(pat) -# and the logic to deal with the new feature -newtab = re.compile(r'-t(?:\s|$)') -def vim(self, argstr): - def do_arg(pat, rarg): - x = len(pat.findall(argstr)) - if x: - a = pat.sub('',argstr) - return rarg, a - else: return '', argstr - - t, argstr = do_arg(newtab, '-tab') - vimhook.extras = t - argstr = 'edit -x ' + argstr - ip.magic(argstr) - -ip.define_magic('vim', vim) - diff --git a/IPython/deathrow/ipython-wx b/IPython/deathrow/ipython-wx deleted file mode 100755 index 5741eff..0000000 --- a/IPython/deathrow/ipython-wx +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -"""wxIPython -- An enhanced Interactive Python GUI fonrtend -This script starts the Wx graphical frontend. -This is experimental so far. -Currently it support only ipython0 instance. Will be upgraded to ipython1 one. -""" - -from IPython.gui.wx import wxIPython - -wxIPython.main() diff --git a/IPython/deathrow/ipythonx b/IPython/deathrow/ipythonx deleted file mode 100755 index ef189c4..0000000 --- a/IPython/deathrow/ipythonx +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -"""IPythonX -- An enhanced Interactive Python - -This script starts the Wx graphical frontend. This is experimental so -far. -""" - -from IPython.frontend.wx import ipythonx - -ipythonx.main() diff --git a/IPython/deathrow/numeric_formats.py b/IPython/deathrow/numeric_formats.py deleted file mode 100644 index b6b2d29..0000000 --- a/IPython/deathrow/numeric_formats.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Extension for printing Numeric Arrays in flexible ways. -""" - -from Numeric import ArrayType - -def num_display(self,arg): - """Display method for printing which treats Numeric arrays specially. - """ - - # Non-numpy variables are printed using the system default - if type(arg) != ArrayType: - self._display(arg) - return - # Otherwise, we do work. - format = __IPYTHON__.runtime_rc.numarray_print_format - print 'NumPy array, format:',format - # Here is where all the printing logic needs to be implemented - print arg # nothing yet :) - - -def magic_format(self,parameter_s=''): - """Specifies format of numerical output. - - This command is similar to Ocave's format command. - """ - - valid_formats = ['long','short'] - - if parameter_s in valid_formats: - self.runtime_rc.numarray_print_format = parameter_s - print 'Numeric output format is now:',parameter_s - else: - print 'Invalid format:',parameter_s - print 'Valid formats:',valid_formats - -# setup default format -__IPYTHON__.runtime_rc.numarray_print_format = 'long' - -# Bind our new functions to the interpreter -__IPYTHON__.__class__.magic_format = magic_format -__IPYTHON__.hooks.display = num_display diff --git a/IPython/deathrow/numutils.py b/IPython/deathrow/numutils.py deleted file mode 100644 index 42012a5..0000000 --- a/IPython/deathrow/numutils.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -""" -A set of convenient utilities for numerical work. - -Most of this module requires Numerical Python or is meant to be used with it. -See http://www.pfdubois.com/numpy for details. -""" - -#***************************************************************************** -# Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#***************************************************************************** - -__all__ = ['sum_flat','mean_flat','rms_flat','base_repr','binary_repr', - 'amin','amax','amap','zeros_like','empty_like', - 'frange','diagonal_matrix','identity', - 'fromfunction_kw','log2','ispower2', - 'norm','l1norm','l2norm','exp_safe', - 'inf','infty','Infinity', - 'Numeric'] - -#**************************************************************************** -# required modules -import __main__ -import math -import operator -import sys - -import Numeric -from Numeric import * - -#***************************************************************************** -# Globals - -# useful for testing infinities in results of array divisions (which don't -# raise an exception) -# Python, LaTeX and Mathematica names. -inf = infty = Infinity = (array([1])/0.0)[0] - -#**************************************************************************** -# function definitions -exp_safe_MIN = math.log(2.2250738585072014e-308) -exp_safe_MAX = 1.7976931348623157e+308 - -def exp_safe(x): - """Compute exponentials which safely underflow to zero. - - Slow but convenient to use. Note that NumArray will introduce proper - floating point exception handling with access to the underlying - hardware.""" - - if type(x) is ArrayType: - return exp(clip(x,exp_safe_MIN,exp_safe_MAX)) - else: - return math.exp(x) - -def amap(fn,*args): - """amap(function, sequence[, sequence, ...]) -> array. - - Works like map(), but it returns an array. This is just a convenient - shorthand for Numeric.array(map(...))""" - return array(map(fn,*args)) - -def amin(m,axis=0): - """amin(m,axis=0) returns the minimum of m along dimension axis. - """ - return minimum.reduce(asarray(m),axis) - -def amax(m,axis=0): - """amax(m,axis=0) returns the maximum of m along dimension axis. - """ - return maximum.reduce(asarray(m),axis) - -def zeros_like(a): - """Return an array of zeros of the shape and typecode of a. - - If you don't explicitly need the array to be zeroed, you should instead - use empty_like(), which is faster as it only allocates memory.""" - - return zeros(a.shape,a.typecode()) - -def empty_like(a): - """Return an empty (uninitialized) array of the shape and typecode of a. - - Note that this does NOT initialize the returned array. If you require - your array to be initialized, you should use zeros_like(). - - This requires Numeric.empty(), which appeared in Numeric 23.7.""" - - return empty(a.shape,a.typecode()) - -def sum_flat(a): - """Return the sum of all the elements of a, flattened out. - - It uses a.flat, and if a is not contiguous, a call to ravel(a) is made.""" - - if a.iscontiguous(): - return Numeric.sum(a.flat) - else: - return Numeric.sum(ravel(a)) - -def mean_flat(a): - """Return the mean of all the elements of a, flattened out.""" - - return sum_flat(a)/float(size(a)) - -def rms_flat(a): - """Return the root mean square of all the elements of a, flattened out.""" - - return math.sqrt(sum_flat(absolute(a)**2)/float(size(a))) - -def l1norm(a): - """Return the l1 norm of a, flattened out. - - Implemented as a separate function (not a call to norm() for speed). - - Ref: http://mathworld.wolfram.com/L1-Norm.html""" - - return sum_flat(absolute(a)) - -def l2norm(a): - """Return the l2 norm of a, flattened out. - - Implemented as a separate function (not a call to norm() for speed). - - Ref: http://mathworld.wolfram.com/L2-Norm.html""" - - return math.sqrt(sum_flat(absolute(a)**2)) - -def norm(a,p=2): - """norm(a,p=2) -> l-p norm of a.flat - - Return the l-p norm of a, considered as a flat array. This is NOT a true - matrix norm, since arrays of arbitrary rank are always flattened. - - p can be a number or one of the strings ('inf','Infinity') to get the - L-infinity norm. - - Ref: http://mathworld.wolfram.com/VectorNorm.html - http://mathworld.wolfram.com/L-Infinity-Norm.html""" - - if p in ('inf','Infinity'): - return max(absolute(a).flat) - else: - return (sum_flat(absolute(a)**p))**(1.0/p) - -def frange(xini,xfin=None,delta=None,**kw): - """frange([start,] stop[, step, keywords]) -> array of floats - - Return a Numeric array() containing a progression of floats. Similar to - arange(), but defaults to a closed interval. - - frange(x0, x1) returns [x0, x0+1, x0+2, ..., x1]; start defaults to 0, and - the endpoint *is included*. This behavior is different from that of - range() and arange(). This is deliberate, since frange will probably be - more useful for generating lists of points for function evaluation, and - endpoints are often desired in this use. The usual behavior of range() can - be obtained by setting the keyword 'closed=0', in this case frange() - basically becomes arange(). - - When step is given, it specifies the increment (or decrement). All - arguments can be floating point numbers. - - frange(x0,x1,d) returns [x0,x0+d,x0+2d,...,xfin] where xfin<=x1. - - frange can also be called with the keyword 'npts'. This sets the number of - points the list should contain (and overrides the value 'step' might have - been given). arange() doesn't offer this option. - - Examples: - >>> frange(3) - array([ 0., 1., 2., 3.]) - >>> frange(3,closed=0) - array([ 0., 1., 2.]) - >>> frange(1,6,2) - array([1, 3, 5]) - >>> frange(1,6.5,npts=5) - array([ 1. , 2.375, 3.75 , 5.125, 6.5 ]) - """ - - #defaults - kw.setdefault('closed',1) - endpoint = kw['closed'] != 0 - - # funny logic to allow the *first* argument to be optional (like range()) - # This was modified with a simpler version from a similar frange() found - # at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66472 - if xfin == None: - xfin = xini + 0.0 - xini = 0.0 - - if delta == None: - delta = 1.0 - - # compute # of points, spacing and return final list - try: - npts=kw['npts'] - delta=(xfin-xini)/float(npts-endpoint) - except KeyError: - # round() gets npts right even with the vagaries of floating point. - npts=int(round((xfin-xini)/delta+endpoint)) - - return arange(npts)*delta+xini - -def diagonal_matrix(diag): - """Return square diagonal matrix whose non-zero elements are given by the - input array.""" - - return diag*identity(len(diag)) - -def identity(n,rank=2,typecode='l'): - """identity(n,r) returns the identity matrix of shape (n,n,...,n) (rank r). - - For ranks higher than 2, this object is simply a multi-index Kronecker - delta: - / 1 if i0=i1=...=iR, - id[i0,i1,...,iR] = -| - \ 0 otherwise. - - Optionally a typecode may be given (it defaults to 'l'). - - Since rank defaults to 2, this function behaves in the default case (when - only n is given) like the Numeric identity function.""" - - iden = zeros((n,)*rank,typecode=typecode) - for i in range(n): - idx = (i,)*rank - iden[idx] = 1 - return iden - -def base_repr (number, base = 2, padding = 0): - """Return the representation of a number in any given base.""" - chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' - if number < base: \ - return (padding - 1) * chars [0] + chars [int (number)] - max_exponent = int (math.log (number)/math.log (base)) - max_power = long (base) ** max_exponent - lead_digit = int (number/max_power) - return chars [lead_digit] + \ - base_repr (number - max_power * lead_digit, base, \ - max (padding - 1, max_exponent)) - -def binary_repr(number, max_length = 1025): - """Return the binary representation of the input number as a string. - - This is more efficient than using base_repr with base 2. - - Increase the value of max_length for very large numbers. Note that on - 32-bit machines, 2**1023 is the largest integer power of 2 which can be - converted to a Python float.""" - - assert number < 2L << max_length - shifts = map (operator.rshift, max_length * [number], \ - range (max_length - 1, -1, -1)) - digits = map (operator.mod, shifts, max_length * [2]) - if not digits.count (1): return 0 - digits = digits [digits.index (1):] - return ''.join (map (repr, digits)).replace('L','') - -def log2(x,ln2 = math.log(2.0)): - """Return the log(x) in base 2. - - This is a _slow_ function but which is guaranteed to return the correct - integer value if the input is an ineger exact power of 2.""" - - try: - bin_n = binary_repr(x)[1:] - except (AssertionError,TypeError): - return math.log(x)/ln2 - else: - if '1' in bin_n: - return math.log(x)/ln2 - else: - return len(bin_n) - -def ispower2(n): - """Returns the log base 2 of n if n is a power of 2, zero otherwise. - - Note the potential ambiguity if n==1: 2**0==1, interpret accordingly.""" - - bin_n = binary_repr(n)[1:] - if '1' in bin_n: - return 0 - else: - return len(bin_n) - -def fromfunction_kw(function, dimensions, **kwargs): - """Drop-in replacement for fromfunction() from Numerical Python. - - Allows passing keyword arguments to the desired function. - - Call it as (keywords are optional): - fromfunction_kw(MyFunction, dimensions, keywords) - - The function MyFunction() is responsible for handling the dictionary of - keywords it will recieve.""" - - return function(tuple(indices(dimensions)),**kwargs) - -#**************************** end file <numutils.py> ************************ diff --git a/IPython/deathrow/oldfrontend/asyncfrontendbase.py b/IPython/deathrow/oldfrontend/asyncfrontendbase.py deleted file mode 100644 index ba912aa..0000000 --- a/IPython/deathrow/oldfrontend/asyncfrontendbase.py +++ /dev/null @@ -1,82 +0,0 @@ -""" -Base front end class for all async frontends. -""" -__docformat__ = "restructuredtext en" - -# Tell nose to skip this module -__test__ = {} - -#------------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports -#------------------------------------------------------------------------------- - -# Third-party -from twisted.python.failure import Failure -from zope.interface import implements, classProvides - -# From IPython -from IPython.frontend.frontendbase import (FrontEndBase, IFrontEnd, - IFrontEndFactory) -from IPython.kernel.core.history import FrontEndHistory -from IPython.kernel.engineservice import IEngineCore - -import uuid - -#----------------------------------------------------------------------------- -# Classes and functions -#----------------------------------------------------------------------------- - -class AsyncFrontEndBase(FrontEndBase): - """ - Overrides FrontEndBase to wrap execute in a deferred result. - All callbacks are made as callbacks on the deferred result. - """ - - implements(IFrontEnd) - classProvides(IFrontEndFactory) - - def __init__(self, engine=None, history=None): - assert(engine==None or IEngineCore.providedBy(engine)) - self.engine = IEngineCore(engine) - if history is None: - self.history = FrontEndHistory(input_cache=['']) - else: - self.history = history - - def execute(self, block, blockID=None): - """Execute the block and return the deferred result. - - Parameters: - block : {str, AST} - blockID : any - Caller may provide an ID to identify this block. - result['blockID'] := blockID - - Result: - Deferred result of self.interpreter.execute - """ - - if(not self.is_complete(block)): - return Failure(Exception("Block is not compilable")) - - if(blockID == None): - blockID = uuid.uuid4() - - d = self.engine.execute(block) - d.addCallback(self._add_history, block=block) - d.addCallbacks(self._add_block_id_for_result, - errback=self._add_block_id_for_failure, - callbackArgs=(blockID,), - errbackArgs=(blockID,)) - d.addBoth(self.update_cell_prompt, blockID=blockID) - d.addCallbacks(self.render_result, - errback=self.render_error) - - return d diff --git a/IPython/deathrow/oldfrontend/cocoa/cocoa_frontend.py b/IPython/deathrow/oldfrontend/cocoa/cocoa_frontend.py deleted file mode 100644 index a7ee199..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/cocoa_frontend.py +++ /dev/null @@ -1,560 +0,0 @@ -# encoding: utf-8 -# -*- test-case-name: IPython.frontend.cocoa.tests.test_cocoa_frontend -*- - -"""PyObjC classes to provide a Cocoa frontend to the -IPython.kernel.engineservice.IEngineBase. - -To add an IPython interpreter to a cocoa app, instantiate an -IPythonCocoaController in a XIB and connect its textView outlet to an -NSTextView instance in your UI. That's it. - -Author: Barry Wark -""" - -__docformat__ = "restructuredtext en" - -#----------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#----------------------------------------------------------------------------- - -#----------------------------------------------------------------------------- -# Imports -#----------------------------------------------------------------------------- - -import sys -import objc -import uuid - -from Foundation import NSObject, NSMutableArray, NSMutableDictionary,\ - NSLog, NSNotificationCenter, NSMakeRange,\ - NSLocalizedString, NSIntersectionRange,\ - NSString, NSAutoreleasePool - -from AppKit import NSApplicationWillTerminateNotification, NSBeep,\ - NSTextView, NSRulerView, NSVerticalRuler - -from pprint import saferepr - -import IPython -from IPython.kernel.engineservice import ThreadedEngineService -from IPython.frontend.asyncfrontendbase import AsyncFrontEndBase - -from twisted.internet.threads import blockingCallFromThread -from twisted.python.failure import Failure - -#----------------------------------------------------------------------------- -# Classes to implement the Cocoa frontend -#----------------------------------------------------------------------------- - -# TODO: -# 1. use MultiEngineClient and out-of-process engine rather than -# ThreadedEngineService? -# 2. integrate Xgrid launching of engines - -class AutoreleasePoolWrappedThreadedEngineService(ThreadedEngineService): - """Wrap all blocks in an NSAutoreleasePool""" - - def wrapped_execute(self, msg, lines): - """wrapped_execute""" - try: - p = NSAutoreleasePool.alloc().init() - result = super(AutoreleasePoolWrappedThreadedEngineService, - self).wrapped_execute(msg, lines) - finally: - p.drain() - - return result - - - -class Cell(NSObject): - """ - Representation of the prompts, input and output of a cell in the - frontend - """ - - blockNumber = objc.ivar().unsigned_long() - blockID = objc.ivar() - inputBlock = objc.ivar() - output = objc.ivar() - - - -class CellBlock(object): - """ - Storage for information about text ranges relating to a single cell - """ - - - def __init__(self, inputPromptRange, inputRange=None, outputPromptRange=None, - outputRange=None): - super(CellBlock, self).__init__() - self.inputPromptRange = inputPromptRange - self.inputRange = inputRange - self.outputPromptRange = outputPromptRange - self.outputRange = outputRange - - def update_ranges_for_insertion(self, text, textRange): - """Update ranges for text insertion at textRange""" - - for r in [self.inputPromptRange,self.inputRange, - self.outputPromptRange, self.outputRange]: - if(r == None): - continue - intersection = NSIntersectionRange(r,textRange) - if(intersection.length == 0): #ranges don't intersect - if r.location >= textRange.location: - r.location += len(text) - else: #ranges intersect - if(r.location > textRange.location): - offset = len(text) - intersection.length - r.length -= offset - r.location += offset - elif(r.location == textRange.location): - r.length += len(text) - intersection.length - else: - r.length -= intersection.length - - - def update_ranges_for_deletion(self, textRange): - """Update ranges for text deletion at textRange""" - - for r in [self.inputPromptRange,self.inputRange, - self.outputPromptRange, self.outputRange]: - if(r==None): - continue - intersection = NSIntersectionRange(r, textRange) - if(intersection.length == 0): #ranges don't intersect - if r.location >= textRange.location: - r.location -= textRange.length - else: #ranges intersect - if(r.location > textRange.location): - offset = intersection.length - r.length -= offset - r.location += offset - elif(r.location == textRange.location): - r.length += intersection.length - else: - r.length -= intersection.length - - def __repr__(self): - return 'CellBlock('+ str((self.inputPromptRange, - self.inputRange, - self.outputPromptRange, - self.outputRange)) + ')' - - - - -class IPythonCocoaController(NSObject, AsyncFrontEndBase): - userNS = objc.ivar() #mirror of engine.user_ns (key=>str(value)) - waitingForEngine = objc.ivar().bool() - textView = objc.IBOutlet() - - def init(self): - self = super(IPythonCocoaController, self).init() - AsyncFrontEndBase.__init__(self, - engine=AutoreleasePoolWrappedThreadedEngineService()) - if(self != None): - self._common_init() - - return self - - def _common_init(self): - """_common_init""" - - self.userNS = NSMutableDictionary.dictionary() - self.waitingForEngine = False - - self.lines = {} - self.tabSpaces = 4 - self.tabUsesSpaces = True - self.currentBlockID = self.next_block_ID() - self.blockRanges = {} # blockID=>CellBlock - - - def awakeFromNib(self): - """awakeFromNib""" - - self._common_init() - - # Start the IPython engine - self.engine.startService() - NSLog('IPython engine started') - - # Register for app termination - nc = NSNotificationCenter.defaultCenter() - nc.addObserver_selector_name_object_( - self, - 'appWillTerminate:', - NSApplicationWillTerminateNotification, - None) - - self.textView.setDelegate_(self) - self.textView.enclosingScrollView().setHasVerticalRuler_(True) - r = NSRulerView.alloc().initWithScrollView_orientation_( - self.textView.enclosingScrollView(), - NSVerticalRuler) - self.verticalRulerView = r - self.verticalRulerView.setClientView_(self.textView) - self._start_cli_banner() - self.start_new_block() - - - def appWillTerminate_(self, notification): - """appWillTerminate""" - - self.engine.stopService() - - - def complete(self, token): - """Complete token in engine's user_ns - - Parameters - ---------- - token : string - - Result - ------ - Deferred result of - IPython.kernel.engineservice.IEngineBase.complete - """ - - return self.engine.complete(token) - - - def execute(self, block, blockID=None): - self.waitingForEngine = True - self.willChangeValueForKey_('commandHistory') - d = super(IPythonCocoaController, self).execute(block, - blockID) - d.addBoth(self._engine_done) - d.addCallback(self._update_user_ns) - - return d - - - def push_(self, namespace): - """Push dictionary of key=>values to python namespace""" - - self.waitingForEngine = True - self.willChangeValueForKey_('commandHistory') - d = self.engine.push(namespace) - d.addBoth(self._engine_done) - d.addCallback(self._update_user_ns) - - - def pull_(self, keys): - """Pull keys from python namespace""" - - self.waitingForEngine = True - result = blockingCallFromThread(self.engine.pull, keys) - self.waitingForEngine = False - - @objc.signature('v@:@I') - def executeFileAtPath_encoding_(self, path, encoding): - """Execute file at path in an empty namespace. Update the engine - user_ns with the resulting locals.""" - - lines,err = NSString.stringWithContentsOfFile_encoding_error_( - path, - encoding, - None) - self.engine.execute(lines) - - - def _engine_done(self, x): - self.waitingForEngine = False - self.didChangeValueForKey_('commandHistory') - return x - - def _update_user_ns(self, result): - """Update self.userNS from self.engine's namespace""" - d = self.engine.keys() - d.addCallback(self._get_engine_namespace_values_for_keys) - - return result - - - def _get_engine_namespace_values_for_keys(self, keys): - d = self.engine.pull(keys) - d.addCallback(self._store_engine_namespace_values, keys=keys) - - - def _store_engine_namespace_values(self, values, keys=[]): - assert(len(values) == len(keys)) - self.willChangeValueForKey_('userNS') - for (k,v) in zip(keys,values): - self.userNS[k] = saferepr(v) - self.didChangeValueForKey_('userNS') - - - def update_cell_prompt(self, result, blockID=None): - print self.blockRanges - if(isinstance(result, Failure)): - prompt = self.input_prompt() - - else: - prompt = self.input_prompt(number=result['number']) - - r = self.blockRanges[blockID].inputPromptRange - self.insert_text(prompt, - textRange=r, - scrollToVisible=False - ) - - return result - - - def render_result(self, result): - blockID = result['blockID'] - inputRange = self.blockRanges[blockID].inputRange - del self.blockRanges[blockID] - - #print inputRange,self.current_block_range() - self.insert_text('\n' + - self.output_prompt(number=result['number']) + - result.get('display',{}).get('pprint','') + - '\n\n', - textRange=NSMakeRange(inputRange.location+inputRange.length, - 0)) - return result - - - def render_error(self, failure): - print failure - blockID = failure.blockID - inputRange = self.blockRanges[blockID].inputRange - self.insert_text('\n' + - self.output_prompt() + - '\n' + - failure.getErrorMessage() + - '\n\n', - textRange=NSMakeRange(inputRange.location + - inputRange.length, - 0)) - self.start_new_block() - return failure - - - def _start_cli_banner(self): - """Print banner""" - - banner = """IPython1 %s -- An enhanced Interactive Python.""" % \ - IPython.__version__ - - self.insert_text(banner + '\n\n') - - - def start_new_block(self): - """""" - - self.currentBlockID = self.next_block_ID() - self.blockRanges[self.currentBlockID] = self.new_cell_block() - self.insert_text(self.input_prompt(), - textRange=self.current_block_range().inputPromptRange) - - - - def next_block_ID(self): - - return uuid.uuid4() - - def new_cell_block(self): - """A new CellBlock at the end of self.textView.textStorage()""" - - return CellBlock(NSMakeRange(self.textView.textStorage().length(), - 0), #len(self.input_prompt())), - NSMakeRange(self.textView.textStorage().length(),# + len(self.input_prompt()), - 0)) - - - def current_block_range(self): - return self.blockRanges.get(self.currentBlockID, - self.new_cell_block()) - - def current_block(self): - """The current block's text""" - - return self.text_for_range(self.current_block_range().inputRange) - - def text_for_range(self, textRange): - """text_for_range""" - - ts = self.textView.textStorage() - return ts.string().substringWithRange_(textRange) - - def current_line(self): - block = self.text_for_range(self.current_block_range().inputRange) - block = block.split('\n') - return block[-1] - - - def insert_text(self, string=None, textRange=None, scrollToVisible=True): - """Insert text into textView at textRange, updating blockRanges - as necessary - """ - if(textRange == None): - #range for end of text - textRange = NSMakeRange(self.textView.textStorage().length(), 0) - - - self.textView.replaceCharactersInRange_withString_( - textRange, string) - - for r in self.blockRanges.itervalues(): - r.update_ranges_for_insertion(string, textRange) - - self.textView.setSelectedRange_(textRange) - if(scrollToVisible): - self.textView.scrollRangeToVisible_(textRange) - - - - def replace_current_block_with_string(self, textView, string): - textView.replaceCharactersInRange_withString_( - self.current_block_range().inputRange, - string) - self.current_block_range().inputRange.length = len(string) - r = NSMakeRange(textView.textStorage().length(), 0) - textView.scrollRangeToVisible_(r) - textView.setSelectedRange_(r) - - - def current_indent_string(self): - """returns string for indent or None if no indent""" - - return self._indent_for_block(self.current_block()) - - - def _indent_for_block(self, block): - lines = block.split('\n') - if(len(lines) > 1): - currentIndent = len(lines[-1]) - len(lines[-1].lstrip()) - if(currentIndent == 0): - currentIndent = self.tabSpaces - - if(self.tabUsesSpaces): - result = ' ' * currentIndent - else: - result = '\t' * (currentIndent/self.tabSpaces) - else: - result = None - - return result - - - # NSTextView delegate methods... - def textView_doCommandBySelector_(self, textView, selector): - assert(textView == self.textView) - NSLog("textView_doCommandBySelector_: "+selector) - - - if(selector == 'insertNewline:'): - indent = self.current_indent_string() - if(indent): - line = indent + self.current_line() - else: - line = self.current_line() - - if(self.is_complete(self.current_block())): - self.execute(self.current_block(), - blockID=self.currentBlockID) - self.start_new_block() - - return True - - return False - - elif(selector == 'moveUp:'): - prevBlock = self.get_history_previous(self.current_block()) - if(prevBlock != None): - self.replace_current_block_with_string(textView, prevBlock) - else: - NSBeep() - return True - - elif(selector == 'moveDown:'): - nextBlock = self.get_history_next() - if(nextBlock != None): - self.replace_current_block_with_string(textView, nextBlock) - else: - NSBeep() - return True - - elif(selector == 'moveToBeginningOfParagraph:'): - textView.setSelectedRange_(NSMakeRange( - self.current_block_range().inputRange.location, - 0)) - return True - elif(selector == 'moveToEndOfParagraph:'): - textView.setSelectedRange_(NSMakeRange( - self.current_block_range().inputRange.location + \ - self.current_block_range().inputRange.length, 0)) - return True - elif(selector == 'deleteToEndOfParagraph:'): - if(textView.selectedRange().location <= \ - self.current_block_range().location): - raise NotImplemented() - - return False # don't actually handle the delete - - elif(selector == 'insertTab:'): - if(len(self.current_line().strip()) == 0): #only white space - return False - else: - self.textView.complete_(self) - return True - - elif(selector == 'deleteBackward:'): - #if we're at the beginning of the current block, ignore - if(textView.selectedRange().location == \ - self.current_block_range().inputRange.location): - return True - else: - for r in self.blockRanges.itervalues(): - deleteRange = textView.selectedRange - if(deleteRange.length == 0): - deleteRange.location -= 1 - deleteRange.length = 1 - r.update_ranges_for_deletion(deleteRange) - return False - return False - - - def textView_shouldChangeTextInRanges_replacementStrings_(self, - textView, ranges, replacementStrings): - """ - Delegate method for NSTextView. - - Refuse change text in ranges not at end, but make those changes at - end. - """ - - assert(len(ranges) == len(replacementStrings)) - allow = True - for r,s in zip(ranges, replacementStrings): - r = r.rangeValue() - if(textView.textStorage().length() > 0 and - r.location < self.current_block_range().inputRange.location): - self.insert_text(s) - allow = False - - return allow - - def textView_completions_forPartialWordRange_indexOfSelectedItem_(self, - textView, words, charRange, index): - try: - ts = textView.textStorage() - token = ts.string().substringWithRange_(charRange) - completions = blockingCallFromThread(self.complete, token) - except: - completions = objc.nil - NSBeep() - - return (completions,0) - - diff --git a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/English.lproj/InfoPlist.strings b/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/English.lproj/InfoPlist.strings deleted file mode 100644 index d6f816ac81381ebb9f19e1608db0a9eb2eea2bf7..0000000000000000000000000000000000000000 GIT binary patch literal 0 Hc$@<O00001 literal 188 zc$^)K!4APt6hzP3S2UK5s8~tFh7E~Wu&^##q_j<or2fcH;^bxW?#!DzcYfc5n20qM zM^bKFd6RL{d&v#0PDLq4a_(ID%hf~bkZ*bD7N)z9ib?2+4Lg=Rx!YT^b)VXsa_}l+ iVMFajW5bzC=$QHXe4KN0jp)?-pbG}-F(WZCHRTUFcOd=% diff --git a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/English.lproj/MainMenu.xib b/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/English.lproj/MainMenu.xib deleted file mode 100644 index 176e41f..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/English.lproj/MainMenu.xib +++ /dev/null @@ -1,3424 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<archive type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="7.01"> - <data> - <int key="IBDocument.SystemTarget">1050</int> - <string key="IBDocument.SystemVersion">9D34</string> - <string key="IBDocument.InterfaceBuilderVersion">629</string> - <string key="IBDocument.AppKitVersion">949.33</string> - <string key="IBDocument.HIToolboxVersion">352.00</string> - <object class="NSMutableArray" key="IBDocument.EditedObjectIDs"> - <bool key="EncodedWithXMLCoder">YES</bool> - <integer value="416"/> - <integer value="29"/> - </object> - <object class="NSArray" key="IBDocument.PluginDependencies"> - <bool key="EncodedWithXMLCoder">YES</bool> - <string id="885801228">com.apple.InterfaceBuilderKit</string> - <string id="113577022">com.apple.InterfaceBuilder.CocoaPlugin</string> - </object> - <object class="NSMutableArray" key="IBDocument.RootObjects" id="1048"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSCustomObject" id="1021"> - <string key="NSClassName" id="190635311">NSApplication</string> - </object> - <object class="NSCustomObject" id="1014"> - <string key="NSClassName">FirstResponder</string> - </object> - <object class="NSCustomObject" id="1050"> - <reference key="NSClassName" ref="190635311"/> - </object> - <object class="NSMenu" id="649796088"> - <string key="NSTitle">AMainMenu</string> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="694149608"> - <reference key="NSMenu" ref="649796088"/> - <string key="NSTitle" id="837240250">IPython1Sandbox</string> - <string key="NSKeyEquiv" id="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <object class="NSCustomResource" key="NSOnImage" id="271266416"> - <string key="NSClassName" id="375865337">NSImage</string> - <string key="NSResourceName">NSMenuCheckmark</string> - </object> - <object class="NSCustomResource" key="NSMixedImage" id="508123839"> - <reference key="NSClassName" ref="375865337"/> - <string key="NSResourceName">NSMenuMixedState</string> - </object> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="110575045"> - <reference key="NSTitle" ref="837240250"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="238522557"> - <reference key="NSMenu" ref="110575045"/> - <string key="NSTitle">About IPython1Sandbox</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="304266470"> - <reference key="NSMenu" ref="110575045"/> - <bool key="NSIsDisabled">YES</bool> - <bool key="NSIsSeparator">YES</bool> - <reference key="NSTitle" ref="255189770"/> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="609285721"> - <reference key="NSMenu" ref="110575045"/> - <string type="base64-UTF8" key="NSTitle">UHJlZmVyZW5jZXPigKY</string> - <string key="NSKeyEquiv">,</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="481834944"> - <reference key="NSMenu" ref="110575045"/> - <bool key="NSIsDisabled">YES</bool> - <bool key="NSIsSeparator">YES</bool> - <reference key="NSTitle" ref="255189770"/> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="1046388886"> - <reference key="NSMenu" ref="110575045"/> - <string key="NSTitle" id="642338826">Services</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="752062318"> - <reference key="NSTitle" ref="642338826"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - </object> - <string key="NSName">_NSServicesMenu</string> - </object> - </object> - <object class="NSMenuItem" id="646227648"> - <reference key="NSMenu" ref="110575045"/> - <bool key="NSIsDisabled">YES</bool> - <bool key="NSIsSeparator">YES</bool> - <reference key="NSTitle" ref="255189770"/> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="755159360"> - <reference key="NSMenu" ref="110575045"/> - <string key="NSTitle">Hide IPython1Sandbox</string> - <string key="NSKeyEquiv" id="940330891">h</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="342932134"> - <reference key="NSMenu" ref="110575045"/> - <string key="NSTitle">Hide Others</string> - <reference key="NSKeyEquiv" ref="940330891"/> - <int key="NSKeyEquivModMask">1572864</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="908899353"> - <reference key="NSMenu" ref="110575045"/> - <string key="NSTitle">Show All</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="1056857174"> - <reference key="NSMenu" ref="110575045"/> - <bool key="NSIsDisabled">YES</bool> - <bool key="NSIsSeparator">YES</bool> - <reference key="NSTitle" ref="255189770"/> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="632727374"> - <reference key="NSMenu" ref="110575045"/> - <string key="NSTitle">Quit IPython1Sandbox</string> - <string key="NSKeyEquiv">q</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - </object> - <string key="NSName">_NSAppleMenu</string> - </object> - </object> - <object class="NSMenuItem" id="379814623"> - <reference key="NSMenu" ref="649796088"/> - <string key="NSTitle" id="881404960">File</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="720053764"> - <reference key="NSTitle" ref="881404960"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="705341025"> - <reference key="NSMenu" ref="720053764"/> - <string key="NSTitle">New</string> - <string key="NSKeyEquiv">n</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="722745758"> - <reference key="NSMenu" ref="720053764"/> - <string type="base64-UTF8" key="NSTitle">T3BlbuKApg</string> - <string key="NSKeyEquiv">o</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="1025936716"> - <reference key="NSMenu" ref="720053764"/> - <string key="NSTitle" id="975517829">Open Recent</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="1065607017"> - <reference key="NSTitle" ref="975517829"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="759406840"> - <reference key="NSMenu" ref="1065607017"/> - <string key="NSTitle">Clear Menu</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - </object> - <string key="NSName">_NSRecentDocumentsMenu</string> - </object> - </object> - <object class="NSMenuItem" id="425164168"> - <reference key="NSMenu" ref="720053764"/> - <bool key="NSIsDisabled">YES</bool> - <bool key="NSIsSeparator">YES</bool> - <reference key="NSTitle" ref="255189770"/> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="776162233"> - <reference key="NSMenu" ref="720053764"/> - <string key="NSTitle">Close</string> - <string key="NSKeyEquiv">w</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="1023925487"> - <reference key="NSMenu" ref="720053764"/> - <string key="NSTitle">Save</string> - <string key="NSKeyEquiv">s</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="117038363"> - <reference key="NSMenu" ref="720053764"/> - <string type="base64-UTF8" key="NSTitle">U2F2ZSBBc+KApg</string> - <string key="NSKeyEquiv">S</string> - <int key="NSKeyEquivModMask">1179648</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="579971712"> - <reference key="NSMenu" ref="720053764"/> - <string key="NSTitle">Revert to Saved</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="1010469920"> - <reference key="NSMenu" ref="720053764"/> - <bool key="NSIsDisabled">YES</bool> - <bool key="NSIsSeparator">YES</bool> - <reference key="NSTitle" ref="255189770"/> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="294629803"> - <reference key="NSMenu" ref="720053764"/> - <string key="NSTitle">Page Setup...</string> - <string key="NSKeyEquiv">P</string> - <int key="NSKeyEquivModMask">1179648</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <reference key="NSToolTip" ref="255189770"/> - </object> - <object class="NSMenuItem" id="49223823"> - <reference key="NSMenu" ref="720053764"/> - <string type="base64-UTF8" key="NSTitle">UHJpbnTigKY</string> - <string key="NSKeyEquiv">p</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - </object> - </object> - </object> - <object class="NSMenuItem" id="952259628"> - <reference key="NSMenu" ref="649796088"/> - <string key="NSTitle" id="1037326483">Edit</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="789758025"> - <reference key="NSTitle" ref="1037326483"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="1058277027"> - <reference key="NSMenu" ref="789758025"/> - <string key="NSTitle">Undo</string> - <string key="NSKeyEquiv">z</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="790794224"> - <reference key="NSMenu" ref="789758025"/> - <string key="NSTitle">Redo</string> - <string key="NSKeyEquiv">Z</string> - <int key="NSKeyEquivModMask">1179648</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="1040322652"> - <reference key="NSMenu" ref="789758025"/> - <bool key="NSIsDisabled">YES</bool> - <bool key="NSIsSeparator">YES</bool> - <reference key="NSTitle" ref="255189770"/> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="296257095"> - <reference key="NSMenu" ref="789758025"/> - <string key="NSTitle">Cut</string> - <string key="NSKeyEquiv">x</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="860595796"> - <reference key="NSMenu" ref="789758025"/> - <string key="NSTitle">Copy</string> - <string key="NSKeyEquiv">c</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="29853731"> - <reference key="NSMenu" ref="789758025"/> - <string key="NSTitle">Paste</string> - <string key="NSKeyEquiv">v</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="437104165"> - <reference key="NSMenu" ref="789758025"/> - <string key="NSTitle">Delete</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="583158037"> - <reference key="NSMenu" ref="789758025"/> - <string key="NSTitle">Select All</string> - <string key="NSKeyEquiv">a</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="212016141"> - <reference key="NSMenu" ref="789758025"/> - <bool key="NSIsDisabled">YES</bool> - <bool key="NSIsSeparator">YES</bool> - <reference key="NSTitle" ref="255189770"/> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="892235320"> - <reference key="NSMenu" ref="789758025"/> - <string key="NSTitle" id="688083180">Find</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="963351320"> - <reference key="NSTitle" ref="688083180"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="447796847"> - <reference key="NSMenu" ref="963351320"/> - <string type="base64-UTF8" key="NSTitle">RmluZOKApg</string> - <string key="NSKeyEquiv" id="469505129">f</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <int key="NSTag">1</int> - </object> - <object class="NSMenuItem" id="326711663"> - <reference key="NSMenu" ref="963351320"/> - <string key="NSTitle">Find Next</string> - <string key="NSKeyEquiv" id="762398675">g</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <int key="NSTag">2</int> - </object> - <object class="NSMenuItem" id="270902937"> - <reference key="NSMenu" ref="963351320"/> - <string key="NSTitle">Find Previous</string> - <string key="NSKeyEquiv" id="819654342">G</string> - <int key="NSKeyEquivModMask">1179648</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <int key="NSTag">3</int> - </object> - <object class="NSMenuItem" id="159080638"> - <reference key="NSMenu" ref="963351320"/> - <string key="NSTitle">Use Selection for Find</string> - <string key="NSKeyEquiv">e</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <int key="NSTag">7</int> - </object> - <object class="NSMenuItem" id="88285865"> - <reference key="NSMenu" ref="963351320"/> - <string key="NSTitle">Jump to Selection</string> - <string key="NSKeyEquiv">j</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - </object> - </object> - </object> - <object class="NSMenuItem" id="972420730"> - <reference key="NSMenu" ref="789758025"/> - <string key="NSTitle" id="739167250">Spelling and Grammar</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="769623530"> - <reference key="NSTitle" ref="739167250"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="679648819"> - <reference key="NSMenu" ref="769623530"/> - <string type="base64-UTF8" key="NSTitle">U2hvdyBTcGVsbGluZ+KApg</string> - <string key="NSKeyEquiv">:</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="96193923"> - <reference key="NSMenu" ref="769623530"/> - <string key="NSTitle">Check Spelling</string> - <string key="NSKeyEquiv">;</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="948374510"> - <reference key="NSMenu" ref="769623530"/> - <string key="NSTitle">Check Spelling While Typing</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="967646866"> - <reference key="NSMenu" ref="769623530"/> - <string key="NSTitle">Check Grammar With Spelling</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - </object> - </object> - </object> - <object class="NSMenuItem" id="507821607"> - <reference key="NSMenu" ref="789758025"/> - <string key="NSTitle" id="904739598">Substitutions</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="698887838"> - <reference key="NSTitle" ref="904739598"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="605118523"> - <reference key="NSMenu" ref="698887838"/> - <string key="NSTitle">Smart Copy/Paste</string> - <reference key="NSKeyEquiv" ref="469505129"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <int key="NSTag">1</int> - </object> - <object class="NSMenuItem" id="197661976"> - <reference key="NSMenu" ref="698887838"/> - <string key="NSTitle">Smart Quotes</string> - <reference key="NSKeyEquiv" ref="762398675"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <int key="NSTag">2</int> - </object> - <object class="NSMenuItem" id="708854459"> - <reference key="NSMenu" ref="698887838"/> - <string key="NSTitle">Smart Links</string> - <reference key="NSKeyEquiv" ref="819654342"/> - <int key="NSKeyEquivModMask">1179648</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <int key="NSTag">3</int> - </object> - </object> - </object> - </object> - <object class="NSMenuItem" id="676164635"> - <reference key="NSMenu" ref="789758025"/> - <string key="NSTitle" id="812002426">Speech</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="785027613"> - <reference key="NSTitle" ref="812002426"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="731782645"> - <reference key="NSMenu" ref="785027613"/> - <string key="NSTitle">Start Speaking</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="680220178"> - <reference key="NSMenu" ref="785027613"/> - <string key="NSTitle">Stop Speaking</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - </object> - </object> - </object> - </object> - </object> - </object> - <object class="NSMenuItem" id="626404410"> - <reference key="NSMenu" ref="649796088"/> - <string key="NSTitle" id="241242548">Format</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="502084290"> - <reference key="NSTitle" ref="241242548"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="519768076"> - <reference key="NSMenu" ref="502084290"/> - <string key="NSTitle">Show Fonts</string> - <string key="NSKeyEquiv" id="806579634">t</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="1028416764"> - <reference key="NSMenu" ref="502084290"/> - <string key="NSTitle">Show Colors</string> - <string key="NSKeyEquiv">C</string> - <int key="NSKeyEquivModMask">1179648</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - </object> - </object> - </object> - <object class="NSMenuItem" id="586577488"> - <reference key="NSMenu" ref="649796088"/> - <string key="NSTitle" id="809723865">View</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="466310130"> - <reference key="NSTitle" ref="809723865"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="102151532"> - <reference key="NSMenu" ref="466310130"/> - <string key="NSTitle">Show Toolbar</string> - <reference key="NSKeyEquiv" ref="806579634"/> - <int key="NSKeyEquivModMask">1572864</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="237841660"> - <reference key="NSMenu" ref="466310130"/> - <string type="base64-UTF8" key="NSTitle">Q3VzdG9taXplIFRvb2xiYXLigKY</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - </object> - </object> - </object> - <object class="NSMenuItem" id="713487014"> - <reference key="NSMenu" ref="649796088"/> - <string key="NSTitle" id="64165424">Window</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="835318025"> - <reference key="NSTitle" ref="64165424"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="1011231497"> - <reference key="NSMenu" ref="835318025"/> - <string key="NSTitle">Minimize</string> - <string key="NSKeyEquiv">m</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="575023229"> - <reference key="NSMenu" ref="835318025"/> - <string key="NSTitle">Zoom</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="299356726"> - <reference key="NSMenu" ref="835318025"/> - <bool key="NSIsDisabled">YES</bool> - <bool key="NSIsSeparator">YES</bool> - <reference key="NSTitle" ref="255189770"/> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - <object class="NSMenuItem" id="625202149"> - <reference key="NSMenu" ref="835318025"/> - <string key="NSTitle">Bring All to Front</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - </object> - <string key="NSName">_NSWindowsMenu</string> - </object> - </object> - <object class="NSMenuItem" id="391199113"> - <reference key="NSMenu" ref="649796088"/> - <string key="NSTitle" id="461919786">Help</string> - <reference key="NSKeyEquiv" ref="255189770"/> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - <string key="NSAction">submenuAction:</string> - <object class="NSMenu" key="NSSubmenu" id="374024848"> - <reference key="NSTitle" ref="461919786"/> - <object class="NSMutableArray" key="NSMenuItems"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMenuItem" id="238773614"> - <reference key="NSMenu" ref="374024848"/> - <string key="NSTitle">IPython1Sandbox Help</string> - <string key="NSKeyEquiv">?</string> - <int key="NSKeyEquivModMask">1048576</int> - <int key="NSMnemonicLoc">2147483647</int> - <reference key="NSOnImage" ref="271266416"/> - <reference key="NSMixedImage" ref="508123839"/> - </object> - </object> - </object> - </object> - </object> - <string key="NSName">_NSMainMenu</string> - </object> - <object class="NSWindowTemplate" id="972006081"> - <int key="NSWindowStyleMask">15</int> - <int key="NSWindowBacking">2</int> - <string key="NSWindowRect">{{335, 413}, {725, 337}}</string> - <int key="NSWTFlags">1946157056</int> - <string key="NSWindowTitle">IPython1 (Cocoa)</string> - <string key="NSWindowClass">NSWindow</string> - <nil key="NSViewClass"/> - <object class="NSView" key="NSWindowView" id="439893737"> - <reference key="NSNextResponder"/> - <int key="NSvFlags">256</int> - <object class="NSMutableArray" key="NSSubviews"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSSplitView" id="741760375"> - <reference key="NSNextResponder" ref="439893737"/> - <int key="NSvFlags">274</int> - <object class="NSMutableArray" key="NSSubviews"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSBox" id="554641139"> - <reference key="NSNextResponder" ref="741760375"/> - <int key="NSvFlags">22</int> - <object class="NSMutableArray" key="NSSubviews"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSView" id="597872307"> - <reference key="NSNextResponder" ref="554641139"/> - <int key="NSvFlags">256</int> - <object class="NSMutableArray" key="NSSubviews"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSScrollView" id="188193463"> - <reference key="NSNextResponder" ref="597872307"/> - <int key="NSvFlags">274</int> - <object class="NSMutableArray" key="NSSubviews"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSClipView" id="638544389"> - <reference key="NSNextResponder" ref="188193463"/> - <int key="NSvFlags">2304</int> - <object class="NSMutableArray" key="NSSubviews"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSTextView" id="163417131"> - <reference key="NSNextResponder" ref="638544389"/> - <int key="NSvFlags">2322</int> - <object class="NSMutableSet" key="NSDragTypes"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMutableArray" key="set.sortedObjects"> - <bool key="EncodedWithXMLCoder">YES</bool> - <string>Apple HTML pasteboard type</string> - <string>Apple PDF pasteboard type</string> - <string>Apple PICT pasteboard type</string> - <string>Apple PNG pasteboard type</string> - <string>Apple URL pasteboard type</string> - <string>CorePasteboardFlavorType 0x6D6F6F76</string> - <string>CorePasteboardFlavorType 0x75726C20</string> - <string>NSColor pasteboard type</string> - <string>NSFilenamesPboardType</string> - <string>NSStringPboardType</string> - <string>NeXT Encapsulated PostScript v1.2 pasteboard type</string> - <string>NeXT RTFD pasteboard type</string> - <string>NeXT Rich Text Format v1.0 pasteboard type</string> - <string>NeXT TIFF v4.0 pasteboard type</string> - <string>NeXT font pasteboard type</string> - <string>NeXT ruler pasteboard type</string> - <string>WebURLsWithTitlesPboardType</string> - </object> - </object> - <string key="NSFrame">{{0, 38}, {433, 14}}</string> - <reference key="NSSuperview" ref="638544389"/> - <reference key="NSWindow"/> - <object class="NSTextContainer" key="NSTextContainer" id="662117317"> - <object class="NSLayoutManager" key="NSLayoutManager"> - <object class="NSTextStorage" key="NSTextStorage"> - <object class="NSMutableString" key="NSString"> - <characters key="NS.bytes"/> - </object> - <nil key="NSDelegate"/> - </object> - <object class="NSMutableArray" key="NSTextContainers"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="662117317"/> - </object> - <int key="NSLMFlags">6</int> - <nil key="NSDelegate"/> - </object> - <reference key="NSTextView" ref="163417131"/> - <double key="NSWidth">4.330000e+02</double> - <int key="NSTCFlags">1</int> - </object> - <object class="NSTextViewSharedData" key="NSSharedData"> - <int key="NSFlags">346991</int> - <object class="NSColor" key="NSBackgroundColor"> - <int key="NSColorSpace">2</int> - <bytes key="NSRGB">MSAwLjk1Mjk0MTI0IDAuODUwOTgwNDYAA</bytes> - </object> - <object class="NSColor" key="NSInsertionColor" id="555789289"> - <int key="NSColorSpace">3</int> - <bytes key="NSWhite">MAA</bytes> - </object> - <object class="NSDictionary" key="NSSelectedAttributes"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMutableArray" key="dict.sortedKeys"> - <bool key="EncodedWithXMLCoder">YES</bool> - <string>NSBackgroundColor</string> - <string id="19777717">NSColor</string> - </object> - <object class="NSMutableArray" key="dict.values"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSColor"> - <int key="NSColorSpace">6</int> - <string key="NSCatalogName" id="484387293">System</string> - <string key="NSColorName">selectedTextBackgroundColor</string> - <object class="NSColor" key="NSColor" id="377165725"> - <int key="NSColorSpace">3</int> - <bytes key="NSWhite">MC42NjY2NjY2OQA</bytes> - </object> - </object> - <object class="NSColor"> - <int key="NSColorSpace">6</int> - <reference key="NSCatalogName" ref="484387293"/> - <string key="NSColorName">selectedTextColor</string> - <reference key="NSColor" ref="555789289"/> - </object> - </object> - </object> - <nil key="NSMarkedAttributes"/> - <object class="NSDictionary" key="NSLinkAttributes"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMutableArray" key="dict.sortedKeys"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="19777717"/> - <string>NSUnderline</string> - </object> - <object class="NSMutableArray" key="dict.values"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSColor"> - <int key="NSColorSpace">1</int> - <bytes key="NSRGB">MCAwIDEAA</bytes> - </object> - <integer value="1" id="9"/> - </object> - </object> - <nil key="NSDefaultParagraphStyle"/> - </object> - <int key="NSTVFlags">6</int> - <string key="NSMaxSize">{480, 1e+07}</string> - <string key="NSMinize">{84, 0}</string> - <nil key="NSDelegate"/> - </object> - </object> - <string key="NSFrame">{{1, 1}, {433, 231}}</string> - <string key="NSBounds">{{0, 38}, {433, 231}}</string> - <reference key="NSSuperview" ref="188193463"/> - <reference key="NSWindow"/> - <reference key="NSNextKeyView" ref="163417131"/> - <reference key="NSDocView" ref="163417131"/> - <object class="NSColor" key="NSBGColor" id="521347521"> - <int key="NSColorSpace">3</int> - <bytes key="NSWhite">MQA</bytes> - </object> - <object class="NSCursor" key="NSCursor"> - <string key="NSHotSpot">{4, -5}</string> - <int key="NSCursorType">1</int> - </object> - <int key="NScvFlags">4</int> - </object> - <object class="NSScroller" id="418410897"> - <reference key="NSNextResponder" ref="188193463"/> - <int key="NSvFlags">-2147483392</int> - <string key="NSFrame">{{427, 1}, {15, 263}}</string> - <reference key="NSSuperview" ref="188193463"/> - <reference key="NSWindow"/> - <reference key="NSTarget" ref="188193463"/> - <string key="NSAction" id="688920982">_doScroller:</string> - <double key="NSPercent">3.389175e-01</double> - </object> - <object class="NSScroller" id="936733673"> - <reference key="NSNextResponder" ref="188193463"/> - <int key="NSvFlags">256</int> - <string key="NSFrame">{{-100, -100}, {87, 18}}</string> - <reference key="NSSuperview" ref="188193463"/> - <reference key="NSWindow"/> - <int key="NSsFlags">1</int> - <reference key="NSTarget" ref="188193463"/> - <reference key="NSAction" ref="688920982"/> - <double key="NSCurValue">1.000000e+00</double> - <double key="NSPercent">9.456522e-01</double> - </object> - </object> - <string key="NSFrame">{{18, 14}, {435, 233}}</string> - <reference key="NSSuperview" ref="597872307"/> - <reference key="NSWindow"/> - <reference key="NSNextKeyView" ref="638544389"/> - <int key="NSsFlags">530</int> - <reference key="NSVScroller" ref="418410897"/> - <reference key="NSHScroller" ref="936733673"/> - <reference key="NSContentView" ref="638544389"/> - </object> - </object> - <string key="NSFrame">{{1, 1}, {471, 257}}</string> - <reference key="NSSuperview" ref="554641139"/> - <reference key="NSWindow"/> - </object> - </object> - <string key="NSFrameSize">{473, 273}</string> - <reference key="NSSuperview" ref="741760375"/> - <reference key="NSWindow"/> - <string key="NSOffsets" id="1055927954">{0, 0}</string> - <object class="NSTextFieldCell" key="NSTitleCell"> - <int key="NSCellFlags">67239424</int> - <int key="NSCellFlags2">0</int> - <string key="NSContents">Console</string> - <object class="NSFont" key="NSSupport" id="26"> - <string key="NSName" id="378950370">LucidaGrande</string> - <double key="NSSize">1.100000e+01</double> - <int key="NSfFlags">3100</int> - </object> - <object class="NSColor" key="NSBackgroundColor" id="131515055"> - <int key="NSColorSpace">6</int> - <reference key="NSCatalogName" ref="484387293"/> - <string key="NSColorName">textBackgroundColor</string> - <reference key="NSColor" ref="521347521"/> - </object> - <object class="NSColor" key="NSTextColor"> - <int key="NSColorSpace">3</int> - <bytes key="NSWhite">MCAwLjgwMDAwMDAxAA</bytes> - </object> - </object> - <reference key="NSContentView" ref="597872307"/> - <int key="NSBorderType">1</int> - <int key="NSBoxType">0</int> - <int key="NSTitlePosition">2</int> - <bool key="NSTransparent">NO</bool> - </object> - <object class="NSBox" id="764100755"> - <reference key="NSNextResponder" ref="741760375"/> - <int key="NSvFlags">51</int> - <object class="NSMutableArray" key="NSSubviews"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSView" id="581281551"> - <reference key="NSNextResponder" ref="764100755"/> - <int key="NSvFlags">256</int> - <object class="NSMutableArray" key="NSSubviews"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSScrollView" id="516244966"> - <reference key="NSNextResponder" ref="581281551"/> - <int key="NSvFlags">274</int> - <object class="NSMutableArray" key="NSSubviews"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSClipView" id="119083427"> - <reference key="NSNextResponder" ref="516244966"/> - <int key="NSvFlags">2304</int> - <object class="NSMutableArray" key="NSSubviews"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSTableView" id="23853726"> - <reference key="NSNextResponder" ref="119083427"/> - <int key="NSvFlags">256</int> - <string key="NSFrameSize">{156, 200}</string> - <reference key="NSSuperview" ref="119083427"/> - <reference key="NSWindow"/> - <bool key="NSEnabled">YES</bool> - <object class="NSTableHeaderView" key="NSHeaderView" id="1048357090"> - <reference key="NSNextResponder" ref="746968320"/> - <int key="NSvFlags">256</int> - <string key="NSFrameSize">{156, 17}</string> - <reference key="NSSuperview" ref="746968320"/> - <reference key="NSWindow"/> - <reference key="NSTableView" ref="23853726"/> - </object> - <object class="_NSCornerView" key="NSCornerView" id="212282722"> - <reference key="NSNextResponder" ref="516244966"/> - <int key="NSvFlags">256</int> - <string key="NSFrame">{{157, 0}, {16, 17}}</string> - <reference key="NSSuperview" ref="516244966"/> - <reference key="NSWindow"/> - </object> - <object class="NSMutableArray" key="NSTableColumns"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSTableColumn" id="920426212"> - <double key="NSWidth">7.100000e+01</double> - <double key="NSMinWidth">4.000000e+01</double> - <double key="NSMaxWidth">1.000000e+03</double> - <object class="NSTableHeaderCell" key="NSHeaderCell"> - <int key="NSCellFlags">75628032</int> - <int key="NSCellFlags2">0</int> - <string key="NSContents">Variable</string> - <reference key="NSSupport" ref="26"/> - <object class="NSColor" key="NSBackgroundColor" id="890615311"> - <int key="NSColorSpace">3</int> - <bytes key="NSWhite">MC4zMzMzMzI5OQA</bytes> - </object> - <object class="NSColor" key="NSTextColor" id="866628999"> - <int key="NSColorSpace">6</int> - <reference key="NSCatalogName" ref="484387293"/> - <string key="NSColorName">headerTextColor</string> - <reference key="NSColor" ref="555789289"/> - </object> - </object> - <object class="NSTextFieldCell" key="NSDataCell" id="525071236"> - <int key="NSCellFlags">337772096</int> - <int key="NSCellFlags2">2048</int> - <string key="NSContents" id="456204663">Text Cell</string> - <object class="NSFont" key="NSSupport" id="8196371"> - <reference key="NSName" ref="378950370"/> - <double key="NSSize">1.300000e+01</double> - <int key="NSfFlags">1044</int> - </object> - <reference key="NSControlView" ref="23853726"/> - <object class="NSColor" key="NSBackgroundColor" id="224028609"> - <int key="NSColorSpace">6</int> - <reference key="NSCatalogName" ref="484387293"/> - <string key="NSColorName">controlBackgroundColor</string> - <reference key="NSColor" ref="377165725"/> - </object> - <object class="NSColor" key="NSTextColor" id="205104690"> - <int key="NSColorSpace">6</int> - <reference key="NSCatalogName" ref="484387293"/> - <string key="NSColorName">controlTextColor</string> - <reference key="NSColor" ref="555789289"/> - </object> - </object> - <int key="NSResizingMask">3</int> - <bool key="NSIsResizeable">YES</bool> - <bool key="NSIsEditable">YES</bool> - <reference key="NSTableView" ref="23853726"/> - </object> - <object class="NSTableColumn" id="857054683"> - <double key="NSWidth">7.900000e+01</double> - <double key="NSMinWidth">4.000000e+01</double> - <double key="NSMaxWidth">1.000000e+03</double> - <object class="NSTableHeaderCell" key="NSHeaderCell"> - <int key="NSCellFlags">75628032</int> - <int key="NSCellFlags2">0</int> - <string key="NSContents">Value</string> - <reference key="NSSupport" ref="26"/> - <reference key="NSBackgroundColor" ref="890615311"/> - <reference key="NSTextColor" ref="866628999"/> - </object> - <object class="NSTextFieldCell" key="NSDataCell" id="377147224"> - <int key="NSCellFlags">337772096</int> - <int key="NSCellFlags2">2048</int> - <reference key="NSContents" ref="456204663"/> - <reference key="NSSupport" ref="8196371"/> - <reference key="NSControlView" ref="23853726"/> - <reference key="NSBackgroundColor" ref="224028609"/> - <reference key="NSTextColor" ref="205104690"/> - </object> - <int key="NSResizingMask">3</int> - <bool key="NSIsResizeable">YES</bool> - <bool key="NSIsEditable">YES</bool> - <reference key="NSTableView" ref="23853726"/> - </object> - </object> - <double key="NSIntercellSpacingWidth">3.000000e+00</double> - <double key="NSIntercellSpacingHeight">2.000000e+00</double> - <reference key="NSBackgroundColor" ref="521347521"/> - <object class="NSColor" key="NSGridColor"> - <int key="NSColorSpace">6</int> - <reference key="NSCatalogName" ref="484387293"/> - <string key="NSColorName">gridColor</string> - <object class="NSColor" key="NSColor"> - <int key="NSColorSpace">3</int> - <bytes key="NSWhite">MC41AA</bytes> - </object> - </object> - <double key="NSRowHeight">1.700000e+01</double> - <int key="NSTvFlags">-692060160</int> - <int key="NSGridStyleMask">1</int> - <int key="NSColumnAutoresizingStyle">4</int> - <int key="NSDraggingSourceMaskForLocal">15</int> - <int key="NSDraggingSourceMaskForNonLocal">0</int> - <bool key="NSAllowsTypeSelect">YES</bool> - </object> - </object> - <string key="NSFrame">{{1, 17}, {156, 200}}</string> - <reference key="NSSuperview" ref="516244966"/> - <reference key="NSWindow"/> - <reference key="NSNextKeyView" ref="23853726"/> - <reference key="NSDocView" ref="23853726"/> - <reference key="NSBGColor" ref="224028609"/> - <int key="NScvFlags">4</int> - </object> - <object class="NSScroller" id="512953560"> - <reference key="NSNextResponder" ref="516244966"/> - <int key="NSvFlags">256</int> - <string key="NSFrame">{{157, 17}, {15, 200}}</string> - <reference key="NSSuperview" ref="516244966"/> - <reference key="NSWindow"/> - <reference key="NSTarget" ref="516244966"/> - <reference key="NSAction" ref="688920982"/> - <double key="NSPercent">9.961240e-01</double> - </object> - <object class="NSScroller" id="47103270"> - <reference key="NSNextResponder" ref="516244966"/> - <int key="NSvFlags">256</int> - <string key="NSFrame">{{1, 217}, {156, 15}}</string> - <reference key="NSSuperview" ref="516244966"/> - <reference key="NSWindow"/> - <int key="NSsFlags">1</int> - <reference key="NSTarget" ref="516244966"/> - <reference key="NSAction" ref="688920982"/> - <double key="NSPercent">7.179487e-01</double> - </object> - <object class="NSClipView" id="746968320"> - <reference key="NSNextResponder" ref="516244966"/> - <int key="NSvFlags">2304</int> - <object class="NSMutableArray" key="NSSubviews"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="1048357090"/> - </object> - <string key="NSFrame">{{1, 0}, {156, 17}}</string> - <reference key="NSSuperview" ref="516244966"/> - <reference key="NSWindow"/> - <reference key="NSNextKeyView" ref="1048357090"/> - <reference key="NSDocView" ref="1048357090"/> - <reference key="NSBGColor" ref="224028609"/> - <int key="NScvFlags">4</int> - </object> - <reference ref="212282722"/> - </object> - <string key="NSFrame">{{18, 14}, {173, 233}}</string> - <reference key="NSSuperview" ref="581281551"/> - <reference key="NSWindow"/> - <reference key="NSNextKeyView" ref="119083427"/> - <int key="NSsFlags">50</int> - <reference key="NSVScroller" ref="512953560"/> - <reference key="NSHScroller" ref="47103270"/> - <reference key="NSContentView" ref="119083427"/> - <reference key="NSHeaderClipView" ref="746968320"/> - <reference key="NSCornerView" ref="212282722"/> - <bytes key="NSScrollAmts">QSAAAEEgAABBmAAAQZgAAA</bytes> - </object> - </object> - <string key="NSFrame">{{1, 1}, {209, 257}}</string> - <reference key="NSSuperview" ref="764100755"/> - <reference key="NSWindow"/> - </object> - </object> - <string key="NSFrame">{{474, 0}, {211, 273}}</string> - <reference key="NSSuperview" ref="741760375"/> - <reference key="NSWindow"/> - <reference key="NSOffsets" ref="1055927954"/> - <object class="NSTextFieldCell" key="NSTitleCell"> - <int key="NSCellFlags">67239424</int> - <int key="NSCellFlags2">0</int> - <string key="NSContents">Workspace</string> - <reference key="NSSupport" ref="26"/> - <reference key="NSBackgroundColor" ref="131515055"/> - <object class="NSColor" key="NSTextColor"> - <int key="NSColorSpace">3</int> - <bytes key="NSWhite">MCAwLjgwMDAwMDAxAA</bytes> - </object> - </object> - <reference key="NSContentView" ref="581281551"/> - <int key="NSBorderType">1</int> - <int key="NSBoxType">0</int> - <int key="NSTitlePosition">2</int> - <bool key="NSTransparent">NO</bool> - </object> - </object> - <string key="NSFrame">{{20, 44}, {685, 273}}</string> - <reference key="NSSuperview" ref="439893737"/> - <reference key="NSWindow"/> - <bool key="NSIsVertical">YES</bool> - <int key="NSDividerStyle">2</int> - <string key="NSAutosaveName">ipython1_console_workspace_split</string> - </object> - <object class="NSProgressIndicator" id="74807016"> - <reference key="NSNextResponder" ref="439893737"/> - <int key="NSvFlags">1313</int> - <object class="NSPSMatrix" key="NSDrawMatrix"/> - <string key="NSFrame">{{689, 20}, {16, 16}}</string> - <reference key="NSSuperview" ref="439893737"/> - <reference key="NSWindow"/> - <int key="NSpiFlags">28938</int> - <double key="NSMinValue">1.600000e+01</double> - <double key="NSMaxValue">1.000000e+02</double> - </object> - </object> - <string key="NSFrameSize">{725, 337}</string> - <reference key="NSSuperview"/> - <reference key="NSWindow"/> - </object> - <string key="NSScreenRect">{{0, 0}, {1280, 778}}</string> - <string key="NSFrameAutosaveName">ipython1_sandbox</string> - </object> - <object class="NSCustomObject" id="610635028"> - <string key="NSClassName" id="982950837">IPython1SandboxAppDelegate</string> - </object> - <object class="NSDictionaryController" id="808393665"> - <object class="NSMutableArray" key="NSDeclaredKeys"> - <bool key="EncodedWithXMLCoder">YES</bool> - <string>keys</string> - <string id="181461860">key</string> - <string id="276523235">value</string> - </object> - <bool key="NSEditable">YES</bool> - <bool key="NSAvoidsEmptySelection">YES</bool> - <bool key="NSPreservesSelection">YES</bool> - <bool key="NSSelectsInsertedObjects">YES</bool> - <bool key="NSFilterRestrictsInsertion">YES</bool> - <object class="NSArray" key="NSSortDescriptors"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSSortDescriptor"> - <reference key="NSKey" ref="181461860"/> - <bool key="NSAscending">YES</bool> - <string key="NSSelector">compare:</string> - </object> - </object> - <bool key="NSClearsFilterPredicateOnInsertion">YES</bool> - <reference key="NSInitialKey" ref="181461860"/> - <reference key="NSInitialValue" ref="276523235"/> - </object> - <object class="NSCustomObject" id="631572152"> - <string key="NSClassName" id="695797635">IPythonCocoaController</string> - </object> - </object> - <object class="IBObjectContainer" key="IBDocument.Objects"> - <object class="NSMutableArray" key="connectionRecords"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">performMiniaturize:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="1011231497"/> - </object> - <int key="connectionID">37</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">arrangeInFront:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="625202149"/> - </object> - <int key="connectionID">39</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">print:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="49223823"/> - </object> - <int key="connectionID">86</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">runPageLayout:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="294629803"/> - </object> - <int key="connectionID">87</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">clearRecentDocuments:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="759406840"/> - </object> - <int key="connectionID">127</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">orderFrontStandardAboutPanel:</string> - <reference key="source" ref="1021"/> - <reference key="destination" ref="238522557"/> - </object> - <int key="connectionID">142</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">performClose:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="776162233"/> - </object> - <int key="connectionID">193</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">toggleContinuousSpellChecking:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="948374510"/> - </object> - <int key="connectionID">222</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">undo:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="1058277027"/> - </object> - <int key="connectionID">223</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">copy:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="860595796"/> - </object> - <int key="connectionID">224</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">checkSpelling:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="96193923"/> - </object> - <int key="connectionID">225</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">paste:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="29853731"/> - </object> - <int key="connectionID">226</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">stopSpeaking:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="680220178"/> - </object> - <int key="connectionID">227</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">cut:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="296257095"/> - </object> - <int key="connectionID">228</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">showGuessPanel:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="679648819"/> - </object> - <int key="connectionID">230</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">redo:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="790794224"/> - </object> - <int key="connectionID">231</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">selectAll:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="583158037"/> - </object> - <int key="connectionID">232</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">startSpeaking:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="731782645"/> - </object> - <int key="connectionID">233</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">delete:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="437104165"/> - </object> - <int key="connectionID">235</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">performZoom:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="575023229"/> - </object> - <int key="connectionID">240</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">performFindPanelAction:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="447796847"/> - </object> - <int key="connectionID">241</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">centerSelectionInVisibleArea:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="88285865"/> - </object> - <int key="connectionID">245</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">toggleGrammarChecking:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="967646866"/> - </object> - <int key="connectionID">347</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">toggleSmartInsertDelete:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="605118523"/> - </object> - <int key="connectionID">355</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">toggleAutomaticQuoteSubstitution:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="197661976"/> - </object> - <int key="connectionID">356</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">toggleAutomaticLinkDetection:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="708854459"/> - </object> - <int key="connectionID">357</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">showHelp:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="238773614"/> - </object> - <int key="connectionID">360</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">orderFrontColorPanel:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="1028416764"/> - </object> - <int key="connectionID">361</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">saveDocument:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="1023925487"/> - </object> - <int key="connectionID">362</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">saveDocumentAs:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="117038363"/> - </object> - <int key="connectionID">363</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">revertDocumentToSaved:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="579971712"/> - </object> - <int key="connectionID">364</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">runToolbarCustomizationPalette:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="237841660"/> - </object> - <int key="connectionID">365</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">toggleToolbarShown:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="102151532"/> - </object> - <int key="connectionID">366</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">hide:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="755159360"/> - </object> - <int key="connectionID">367</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">hideOtherApplications:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="342932134"/> - </object> - <int key="connectionID">368</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">terminate:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="632727374"/> - </object> - <int key="connectionID">369</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBActionConnection" key="connection"> - <string key="label">unhideAllApplications:</string> - <reference key="source" ref="1014"/> - <reference key="destination" ref="908899353"/> - </object> - <int key="connectionID">370</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBOutletConnection" key="connection"> - <string key="label" id="606168085">delegate</string> - <reference key="source" ref="1050"/> - <reference key="destination" ref="610635028"/> - </object> - <int key="connectionID">374</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBBindingConnection" key="connection"> - <string key="label" id="187454546">contentDictionary: userNS</string> - <reference key="source" ref="808393665"/> - <reference key="destination" ref="631572152"/> - <object class="NSNibBindingConnector" key="connector"> - <reference key="NSSource" ref="808393665"/> - <reference key="NSDestination" ref="631572152"/> - <reference key="NSLabel" ref="187454546"/> - <string key="NSBinding">contentDictionary</string> - <string key="NSKeyPath">userNS</string> - <int key="NSNibBindingConnectorVersion">2</int> - </object> - </object> - <int key="connectionID">424</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBBindingConnection" key="connection"> - <string key="label" id="688370141">value: arrangedObjects.value</string> - <reference key="source" ref="857054683"/> - <reference key="destination" ref="808393665"/> - <object class="NSNibBindingConnector" key="connector"> - <reference key="NSSource" ref="857054683"/> - <reference key="NSDestination" ref="808393665"/> - <reference key="NSLabel" ref="688370141"/> - <reference key="NSBinding" ref="276523235"/> - <string key="NSKeyPath">arrangedObjects.value</string> - <int key="NSNibBindingConnectorVersion">2</int> - </object> - </object> - <int key="connectionID">427</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBBindingConnection" key="connection"> - <string key="label" id="764859820">value: arrangedObjects.key</string> - <reference key="source" ref="920426212"/> - <reference key="destination" ref="808393665"/> - <object class="NSNibBindingConnector" key="connector"> - <reference key="NSSource" ref="920426212"/> - <reference key="NSDestination" ref="808393665"/> - <reference key="NSLabel" ref="764859820"/> - <reference key="NSBinding" ref="276523235"/> - <string key="NSKeyPath">arrangedObjects.key</string> - <int key="NSNibBindingConnectorVersion">2</int> - </object> - </object> - <int key="connectionID">428</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBOutletConnection" key="connection"> - <reference key="label" ref="606168085"/> - <reference key="source" ref="972006081"/> - <reference key="destination" ref="631572152"/> - </object> - <int key="connectionID">429</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBBindingConnection" key="connection"> - <string key="label" id="97087091">animate: waitingForEngine</string> - <reference key="source" ref="74807016"/> - <reference key="destination" ref="631572152"/> - <object class="NSNibBindingConnector" key="connector"> - <reference key="NSSource" ref="74807016"/> - <reference key="NSDestination" ref="631572152"/> - <reference key="NSLabel" ref="97087091"/> - <string key="NSBinding">animate</string> - <string key="NSKeyPath">waitingForEngine</string> - <int key="NSNibBindingConnectorVersion">2</int> - </object> - </object> - <int key="connectionID">437</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBBindingConnection" key="connection"> - <string key="label" id="289275654">filterPredicate: workspaceFilterPredicate</string> - <reference key="source" ref="808393665"/> - <reference key="destination" ref="610635028"/> - <object class="NSNibBindingConnector" key="connector"> - <reference key="NSSource" ref="808393665"/> - <reference key="NSDestination" ref="610635028"/> - <reference key="NSLabel" ref="289275654"/> - <string key="NSBinding">filterPredicate</string> - <string key="NSKeyPath">workspaceFilterPredicate</string> - <int key="NSNibBindingConnectorVersion">2</int> - </object> - </object> - <int key="connectionID">440</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBOutletConnection" key="connection"> - <string key="label">ipythonController</string> - <reference key="source" ref="610635028"/> - <reference key="destination" ref="631572152"/> - </object> - <int key="connectionID">441</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBOutletConnection" key="connection"> - <string key="label" id="684042788">textView</string> - <reference key="source" ref="631572152"/> - <reference key="destination" ref="163417131"/> - </object> - <int key="connectionID">444</int> - </object> - <object class="IBConnectionRecord"> - <object class="IBOutletConnection" key="connection"> - <string key="label">initialFirstResponder</string> - <reference key="source" ref="972006081"/> - <reference key="destination" ref="163417131"/> - </object> - <int key="connectionID">445</int> - </object> - </object> - <object class="IBMutableOrderedSet" key="objectRecords"> - <object class="NSArray" key="orderedObjects"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="IBObjectRecord"> - <int key="objectID">0</int> - <object class="NSArray" key="object" id="1049"> - <bool key="EncodedWithXMLCoder">YES</bool> - </object> - <reference key="children" ref="1048"/> - <nil key="parent"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">-2</int> - <reference key="object" ref="1021"/> - <reference key="parent" ref="1049"/> - <string type="base64-UTF8" key="objectName">RmlsZSdzIE93bmVyA</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">-1</int> - <reference key="object" ref="1014"/> - <reference key="parent" ref="1049"/> - <string key="objectName">First Responder</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">-3</int> - <reference key="object" ref="1050"/> - <reference key="parent" ref="1049"/> - <string key="objectName">Application</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">29</int> - <reference key="object" ref="649796088"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="713487014"/> - <reference ref="694149608"/> - <reference ref="391199113"/> - <reference ref="952259628"/> - <reference ref="379814623"/> - <reference ref="586577488"/> - <reference ref="626404410"/> - </object> - <reference key="parent" ref="1049"/> - <string key="objectName">MainMenu</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">19</int> - <reference key="object" ref="713487014"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="835318025"/> - </object> - <reference key="parent" ref="649796088"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">56</int> - <reference key="object" ref="694149608"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="110575045"/> - </object> - <reference key="parent" ref="649796088"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">103</int> - <reference key="object" ref="391199113"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="374024848"/> - </object> - <reference key="parent" ref="649796088"/> - <string key="objectName" id="508169456">1</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">217</int> - <reference key="object" ref="952259628"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="789758025"/> - </object> - <reference key="parent" ref="649796088"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">83</int> - <reference key="object" ref="379814623"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="720053764"/> - </object> - <reference key="parent" ref="649796088"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">81</int> - <reference key="object" ref="720053764"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="1023925487"/> - <reference ref="117038363"/> - <reference ref="49223823"/> - <reference ref="722745758"/> - <reference ref="705341025"/> - <reference ref="1025936716"/> - <reference ref="294629803"/> - <reference ref="776162233"/> - <reference ref="425164168"/> - <reference ref="579971712"/> - <reference ref="1010469920"/> - </object> - <reference key="parent" ref="379814623"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">75</int> - <reference key="object" ref="1023925487"/> - <reference key="parent" ref="720053764"/> - <string key="objectName">3</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">80</int> - <reference key="object" ref="117038363"/> - <reference key="parent" ref="720053764"/> - <string key="objectName">8</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">78</int> - <reference key="object" ref="49223823"/> - <reference key="parent" ref="720053764"/> - <string key="objectName">6</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">72</int> - <reference key="object" ref="722745758"/> - <reference key="parent" ref="720053764"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">82</int> - <reference key="object" ref="705341025"/> - <reference key="parent" ref="720053764"/> - <string key="objectName">9</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">124</int> - <reference key="object" ref="1025936716"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="1065607017"/> - </object> - <reference key="parent" ref="720053764"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">77</int> - <reference key="object" ref="294629803"/> - <reference key="parent" ref="720053764"/> - <string key="objectName">5</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">73</int> - <reference key="object" ref="776162233"/> - <reference key="parent" ref="720053764"/> - <reference key="objectName" ref="508169456"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">79</int> - <reference key="object" ref="425164168"/> - <reference key="parent" ref="720053764"/> - <string key="objectName">7</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">112</int> - <reference key="object" ref="579971712"/> - <reference key="parent" ref="720053764"/> - <string key="objectName">10</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">74</int> - <reference key="object" ref="1010469920"/> - <reference key="parent" ref="720053764"/> - <string key="objectName" id="464456376">2</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">125</int> - <reference key="object" ref="1065607017"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="759406840"/> - </object> - <reference key="parent" ref="1025936716"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">126</int> - <reference key="object" ref="759406840"/> - <reference key="parent" ref="1065607017"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">205</int> - <reference key="object" ref="789758025"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="437104165"/> - <reference ref="583158037"/> - <reference ref="1058277027"/> - <reference ref="212016141"/> - <reference ref="296257095"/> - <reference ref="29853731"/> - <reference ref="860595796"/> - <reference ref="1040322652"/> - <reference ref="790794224"/> - <reference ref="892235320"/> - <reference ref="972420730"/> - <reference ref="676164635"/> - <reference ref="507821607"/> - </object> - <reference key="parent" ref="952259628"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">202</int> - <reference key="object" ref="437104165"/> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">198</int> - <reference key="object" ref="583158037"/> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">207</int> - <reference key="object" ref="1058277027"/> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">214</int> - <reference key="object" ref="212016141"/> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">199</int> - <reference key="object" ref="296257095"/> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">203</int> - <reference key="object" ref="29853731"/> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">197</int> - <reference key="object" ref="860595796"/> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">206</int> - <reference key="object" ref="1040322652"/> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">215</int> - <reference key="object" ref="790794224"/> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">218</int> - <reference key="object" ref="892235320"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="963351320"/> - </object> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">216</int> - <reference key="object" ref="972420730"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="769623530"/> - </object> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">200</int> - <reference key="object" ref="769623530"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="948374510"/> - <reference ref="96193923"/> - <reference ref="679648819"/> - <reference ref="967646866"/> - </object> - <reference key="parent" ref="972420730"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">219</int> - <reference key="object" ref="948374510"/> - <reference key="parent" ref="769623530"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">201</int> - <reference key="object" ref="96193923"/> - <reference key="parent" ref="769623530"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">204</int> - <reference key="object" ref="679648819"/> - <reference key="parent" ref="769623530"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">220</int> - <reference key="object" ref="963351320"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="270902937"/> - <reference ref="88285865"/> - <reference ref="159080638"/> - <reference ref="326711663"/> - <reference ref="447796847"/> - </object> - <reference key="parent" ref="892235320"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">213</int> - <reference key="object" ref="270902937"/> - <reference key="parent" ref="963351320"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">210</int> - <reference key="object" ref="88285865"/> - <reference key="parent" ref="963351320"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">221</int> - <reference key="object" ref="159080638"/> - <reference key="parent" ref="963351320"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">208</int> - <reference key="object" ref="326711663"/> - <reference key="parent" ref="963351320"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">209</int> - <reference key="object" ref="447796847"/> - <reference key="parent" ref="963351320"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">106</int> - <reference key="object" ref="374024848"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="238773614"/> - </object> - <reference key="parent" ref="391199113"/> - <reference key="objectName" ref="464456376"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">111</int> - <reference key="object" ref="238773614"/> - <reference key="parent" ref="374024848"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">57</int> - <reference key="object" ref="110575045"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="238522557"/> - <reference ref="755159360"/> - <reference ref="908899353"/> - <reference ref="632727374"/> - <reference ref="646227648"/> - <reference ref="609285721"/> - <reference ref="481834944"/> - <reference ref="304266470"/> - <reference ref="1046388886"/> - <reference ref="1056857174"/> - <reference ref="342932134"/> - </object> - <reference key="parent" ref="694149608"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">58</int> - <reference key="object" ref="238522557"/> - <reference key="parent" ref="110575045"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">134</int> - <reference key="object" ref="755159360"/> - <reference key="parent" ref="110575045"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">150</int> - <reference key="object" ref="908899353"/> - <reference key="parent" ref="110575045"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">136</int> - <reference key="object" ref="632727374"/> - <reference key="parent" ref="110575045"/> - <string key="objectName">1111</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">144</int> - <reference key="object" ref="646227648"/> - <reference key="parent" ref="110575045"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">129</int> - <reference key="object" ref="609285721"/> - <reference key="parent" ref="110575045"/> - <string key="objectName">121</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">143</int> - <reference key="object" ref="481834944"/> - <reference key="parent" ref="110575045"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">236</int> - <reference key="object" ref="304266470"/> - <reference key="parent" ref="110575045"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">131</int> - <reference key="object" ref="1046388886"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="752062318"/> - </object> - <reference key="parent" ref="110575045"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">149</int> - <reference key="object" ref="1056857174"/> - <reference key="parent" ref="110575045"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">145</int> - <reference key="object" ref="342932134"/> - <reference key="parent" ref="110575045"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">130</int> - <reference key="object" ref="752062318"/> - <reference key="parent" ref="1046388886"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">24</int> - <reference key="object" ref="835318025"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="299356726"/> - <reference ref="625202149"/> - <reference ref="575023229"/> - <reference ref="1011231497"/> - </object> - <reference key="parent" ref="713487014"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">92</int> - <reference key="object" ref="299356726"/> - <reference key="parent" ref="835318025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">5</int> - <reference key="object" ref="625202149"/> - <reference key="parent" ref="835318025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">239</int> - <reference key="object" ref="575023229"/> - <reference key="parent" ref="835318025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">23</int> - <reference key="object" ref="1011231497"/> - <reference key="parent" ref="835318025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">295</int> - <reference key="object" ref="586577488"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="466310130"/> - </object> - <reference key="parent" ref="649796088"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">296</int> - <reference key="object" ref="466310130"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="102151532"/> - <reference ref="237841660"/> - </object> - <reference key="parent" ref="586577488"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">297</int> - <reference key="object" ref="102151532"/> - <reference key="parent" ref="466310130"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">298</int> - <reference key="object" ref="237841660"/> - <reference key="parent" ref="466310130"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">299</int> - <reference key="object" ref="626404410"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="502084290"/> - </object> - <reference key="parent" ref="649796088"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">300</int> - <reference key="object" ref="502084290"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="519768076"/> - <reference ref="1028416764"/> - </object> - <reference key="parent" ref="626404410"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">344</int> - <reference key="object" ref="519768076"/> - <reference key="parent" ref="502084290"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">345</int> - <reference key="object" ref="1028416764"/> - <reference key="parent" ref="502084290"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">211</int> - <reference key="object" ref="676164635"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="785027613"/> - </object> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">212</int> - <reference key="object" ref="785027613"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="680220178"/> - <reference ref="731782645"/> - </object> - <reference key="parent" ref="676164635"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">195</int> - <reference key="object" ref="680220178"/> - <reference key="parent" ref="785027613"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">196</int> - <reference key="object" ref="731782645"/> - <reference key="parent" ref="785027613"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">346</int> - <reference key="object" ref="967646866"/> - <reference key="parent" ref="769623530"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">348</int> - <reference key="object" ref="507821607"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="698887838"/> - </object> - <reference key="parent" ref="789758025"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">349</int> - <reference key="object" ref="698887838"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="605118523"/> - <reference ref="197661976"/> - <reference ref="708854459"/> - </object> - <reference key="parent" ref="507821607"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">350</int> - <reference key="object" ref="605118523"/> - <reference key="parent" ref="698887838"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">351</int> - <reference key="object" ref="197661976"/> - <reference key="parent" ref="698887838"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">354</int> - <reference key="object" ref="708854459"/> - <reference key="parent" ref="698887838"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">371</int> - <reference key="object" ref="972006081"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="439893737"/> - </object> - <reference key="parent" ref="1049"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">372</int> - <reference key="object" ref="439893737"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="741760375"/> - <reference ref="74807016"/> - </object> - <reference key="parent" ref="972006081"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">373</int> - <reference key="object" ref="610635028"/> - <reference key="parent" ref="1049"/> - <reference key="objectName" ref="982950837"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">385</int> - <reference key="object" ref="808393665"/> - <reference key="parent" ref="1049"/> - <string key="objectName">User Namespace Controller</string> - </object> - <object class="IBObjectRecord"> - <int key="objectID">421</int> - <reference key="object" ref="741760375"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="554641139"/> - <reference ref="764100755"/> - </object> - <reference key="parent" ref="439893737"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">420</int> - <reference key="object" ref="554641139"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="188193463"/> - </object> - <reference key="parent" ref="741760375"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">416</int> - <reference key="object" ref="188193463"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="418410897"/> - <reference ref="936733673"/> - <reference ref="163417131"/> - </object> - <reference key="parent" ref="554641139"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">417</int> - <reference key="object" ref="418410897"/> - <reference key="parent" ref="188193463"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">418</int> - <reference key="object" ref="936733673"/> - <reference key="parent" ref="188193463"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">419</int> - <reference key="object" ref="163417131"/> - <reference key="parent" ref="188193463"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">406</int> - <reference key="object" ref="764100755"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="516244966"/> - </object> - <reference key="parent" ref="741760375"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">407</int> - <reference key="object" ref="516244966"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="23853726"/> - <reference ref="47103270"/> - <reference ref="512953560"/> - <reference ref="1048357090"/> - </object> - <reference key="parent" ref="764100755"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">411</int> - <reference key="object" ref="23853726"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="857054683"/> - <reference ref="920426212"/> - </object> - <reference key="parent" ref="516244966"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">410</int> - <reference key="object" ref="47103270"/> - <reference key="parent" ref="516244966"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">409</int> - <reference key="object" ref="512953560"/> - <reference key="parent" ref="516244966"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">408</int> - <reference key="object" ref="1048357090"/> - <reference key="parent" ref="516244966"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">413</int> - <reference key="object" ref="857054683"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="377147224"/> - </object> - <reference key="parent" ref="23853726"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">412</int> - <reference key="object" ref="920426212"/> - <object class="NSMutableArray" key="children"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="525071236"/> - </object> - <reference key="parent" ref="23853726"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">415</int> - <reference key="object" ref="525071236"/> - <reference key="parent" ref="920426212"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">414</int> - <reference key="object" ref="377147224"/> - <reference key="parent" ref="857054683"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">422</int> - <reference key="object" ref="631572152"/> - <reference key="parent" ref="1049"/> - </object> - <object class="IBObjectRecord"> - <int key="objectID">436</int> - <reference key="object" ref="74807016"/> - <reference key="parent" ref="439893737"/> - </object> - </object> - </object> - <object class="NSMutableDictionary" key="flattenedProperties"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSMutableArray" key="dict.sortedKeys"> - <bool key="EncodedWithXMLCoder">YES</bool> - <string>-1.IBPluginDependency</string> - <string>-2.IBPluginDependency</string> - <string>-3.IBPluginDependency</string> - <string>103.IBPluginDependency</string> - <string>103.ImportedFromIB2</string> - <string>106.IBPluginDependency</string> - <string>106.ImportedFromIB2</string> - <string>106.editorWindowContentRectSynchronizationRect</string> - <string>111.IBPluginDependency</string> - <string>111.ImportedFromIB2</string> - <string>112.IBPluginDependency</string> - <string>112.ImportedFromIB2</string> - <string>124.IBPluginDependency</string> - <string>124.ImportedFromIB2</string> - <string>125.IBPluginDependency</string> - <string>125.ImportedFromIB2</string> - <string>125.editorWindowContentRectSynchronizationRect</string> - <string>126.IBPluginDependency</string> - <string>126.ImportedFromIB2</string> - <string>129.IBPluginDependency</string> - <string>129.ImportedFromIB2</string> - <string>130.IBPluginDependency</string> - <string>130.ImportedFromIB2</string> - <string>130.editorWindowContentRectSynchronizationRect</string> - <string>131.IBPluginDependency</string> - <string>131.ImportedFromIB2</string> - <string>134.IBPluginDependency</string> - <string>134.ImportedFromIB2</string> - <string>136.IBPluginDependency</string> - <string>136.ImportedFromIB2</string> - <string>143.IBPluginDependency</string> - <string>143.ImportedFromIB2</string> - <string>144.IBPluginDependency</string> - <string>144.ImportedFromIB2</string> - <string>145.IBPluginDependency</string> - <string>145.ImportedFromIB2</string> - <string>149.IBPluginDependency</string> - <string>149.ImportedFromIB2</string> - <string>150.IBPluginDependency</string> - <string>150.ImportedFromIB2</string> - <string>19.IBPluginDependency</string> - <string>19.ImportedFromIB2</string> - <string>195.IBPluginDependency</string> - <string>195.ImportedFromIB2</string> - <string>196.IBPluginDependency</string> - <string>196.ImportedFromIB2</string> - <string>197.IBPluginDependency</string> - <string>197.ImportedFromIB2</string> - <string>198.IBPluginDependency</string> - <string>198.ImportedFromIB2</string> - <string>199.IBPluginDependency</string> - <string>199.ImportedFromIB2</string> - <string>200.IBPluginDependency</string> - <string>200.ImportedFromIB2</string> - <string>200.editorWindowContentRectSynchronizationRect</string> - <string>201.IBPluginDependency</string> - <string>201.ImportedFromIB2</string> - <string>202.IBPluginDependency</string> - <string>202.ImportedFromIB2</string> - <string>203.IBPluginDependency</string> - <string>203.ImportedFromIB2</string> - <string>204.IBPluginDependency</string> - <string>204.ImportedFromIB2</string> - <string>205.IBPluginDependency</string> - <string>205.ImportedFromIB2</string> - <string>205.editorWindowContentRectSynchronizationRect</string> - <string>206.IBPluginDependency</string> - <string>206.ImportedFromIB2</string> - <string>207.IBPluginDependency</string> - <string>207.ImportedFromIB2</string> - <string>208.IBPluginDependency</string> - <string>208.ImportedFromIB2</string> - <string>209.IBPluginDependency</string> - <string>209.ImportedFromIB2</string> - <string>210.IBPluginDependency</string> - <string>210.ImportedFromIB2</string> - <string>211.IBPluginDependency</string> - <string>211.ImportedFromIB2</string> - <string>212.IBPluginDependency</string> - <string>212.ImportedFromIB2</string> - <string>212.editorWindowContentRectSynchronizationRect</string> - <string>213.IBPluginDependency</string> - <string>213.ImportedFromIB2</string> - <string>214.IBPluginDependency</string> - <string>214.ImportedFromIB2</string> - <string>215.IBPluginDependency</string> - <string>215.ImportedFromIB2</string> - <string>216.IBPluginDependency</string> - <string>216.ImportedFromIB2</string> - <string>217.IBPluginDependency</string> - <string>217.ImportedFromIB2</string> - <string>218.IBPluginDependency</string> - <string>218.ImportedFromIB2</string> - <string>219.IBPluginDependency</string> - <string>219.ImportedFromIB2</string> - <string>220.IBPluginDependency</string> - <string>220.ImportedFromIB2</string> - <string>220.editorWindowContentRectSynchronizationRect</string> - <string>221.IBPluginDependency</string> - <string>221.ImportedFromIB2</string> - <string>23.IBPluginDependency</string> - <string>23.ImportedFromIB2</string> - <string>236.IBPluginDependency</string> - <string>236.ImportedFromIB2</string> - <string>239.IBPluginDependency</string> - <string>239.ImportedFromIB2</string> - <string>24.IBPluginDependency</string> - <string>24.ImportedFromIB2</string> - <string>24.editorWindowContentRectSynchronizationRect</string> - <string>29.IBPluginDependency</string> - <string>29.ImportedFromIB2</string> - <string>29.WindowOrigin</string> - <string>29.editorWindowContentRectSynchronizationRect</string> - <string>295.IBPluginDependency</string> - <string>296.IBPluginDependency</string> - <string>296.editorWindowContentRectSynchronizationRect</string> - <string>297.IBPluginDependency</string> - <string>298.IBPluginDependency</string> - <string>299.IBPluginDependency</string> - <string>300.IBPluginDependency</string> - <string>300.editorWindowContentRectSynchronizationRect</string> - <string>344.IBPluginDependency</string> - <string>345.IBPluginDependency</string> - <string>346.IBPluginDependency</string> - <string>346.ImportedFromIB2</string> - <string>348.IBPluginDependency</string> - <string>348.ImportedFromIB2</string> - <string>349.IBPluginDependency</string> - <string>349.ImportedFromIB2</string> - <string>349.editorWindowContentRectSynchronizationRect</string> - <string>350.IBPluginDependency</string> - <string>350.ImportedFromIB2</string> - <string>351.IBPluginDependency</string> - <string>351.ImportedFromIB2</string> - <string>354.IBPluginDependency</string> - <string>354.ImportedFromIB2</string> - <string>371.IBPluginDependency</string> - <string>371.IBViewEditorWindowController.showingLayoutRectangles</string> - <string>371.IBWindowTemplateEditedContentRect</string> - <string>371.NSWindowTemplate.visibleAtLaunch</string> - <string>371.editorWindowContentRectSynchronizationRect</string> - <string>372.IBPluginDependency</string> - <string>373.IBPluginDependency</string> - <string>385.IBPluginDependency</string> - <string>407.IBPluginDependency</string> - <string>409.IBPluginDependency</string> - <string>410.IBPluginDependency</string> - <string>411.IBPluginDependency</string> - <string>412.IBPluginDependency</string> - <string>413.IBPluginDependency</string> - <string>414.IBPluginDependency</string> - <string>415.IBPluginDependency</string> - <string>416.IBPluginDependency</string> - <string>417.IBPluginDependency</string> - <string>418.IBPluginDependency</string> - <string>419.IBAttributePlaceholdersKey</string> - <string>419.IBPluginDependency</string> - <string>422.IBPluginDependency</string> - <string>436.IBPluginDependency</string> - <string>5.IBPluginDependency</string> - <string>5.ImportedFromIB2</string> - <string>56.IBPluginDependency</string> - <string>56.ImportedFromIB2</string> - <string>57.IBPluginDependency</string> - <string>57.ImportedFromIB2</string> - <string>57.editorWindowContentRectSynchronizationRect</string> - <string>58.IBPluginDependency</string> - <string>58.ImportedFromIB2</string> - <string>72.IBPluginDependency</string> - <string>72.ImportedFromIB2</string> - <string>73.IBPluginDependency</string> - <string>73.ImportedFromIB2</string> - <string>74.IBPluginDependency</string> - <string>74.ImportedFromIB2</string> - <string>75.IBPluginDependency</string> - <string>75.ImportedFromIB2</string> - <string>77.IBPluginDependency</string> - <string>77.ImportedFromIB2</string> - <string>78.IBPluginDependency</string> - <string>78.ImportedFromIB2</string> - <string>79.IBPluginDependency</string> - <string>79.ImportedFromIB2</string> - <string>80.IBPluginDependency</string> - <string>80.ImportedFromIB2</string> - <string>81.IBPluginDependency</string> - <string>81.ImportedFromIB2</string> - <string>81.editorWindowContentRectSynchronizationRect</string> - <string>82.IBPluginDependency</string> - <string>82.ImportedFromIB2</string> - <string>83.IBPluginDependency</string> - <string>83.ImportedFromIB2</string> - <string>92.IBPluginDependency</string> - <string>92.ImportedFromIB2</string> - </object> - <object class="NSMutableArray" key="dict.values"> - <bool key="EncodedWithXMLCoder">YES</bool> - <reference ref="113577022"/> - <reference ref="885801228"/> - <reference ref="885801228"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <string>{{596, 852}, {216, 23}}</string> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <string>{{522, 812}, {146, 23}}</string> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <string>{{436, 809}, {64, 6}}</string> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <string>{{608, 612}, {275, 83}}</string> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <string>{{365, 632}, {243, 243}}</string> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <string>{{608, 612}, {167, 43}}</string> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <string>{{608, 612}, {241, 103}}</string> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <string>{{525, 802}, {197, 73}}</string> - <reference ref="113577022"/> - <reference ref="9"/> - <string>{74, 862}</string> - <string>{{11, 736}, {489, 20}}</string> - <reference ref="113577022"/> - <reference ref="113577022"/> - <string>{{475, 832}, {234, 43}}</string> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <string>{{409, 832}, {176, 43}}</string> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <string>{{608, 612}, {215, 63}}</string> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <integer value="0"/> - <string>{{27, 368}, {725, 337}}</string> - <reference ref="9"/> - <string>{{27, 368}, {725, 337}}</string> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <object class="NSMutableDictionary"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSArray" key="dict.sortedKeys"> - <bool key="EncodedWithXMLCoder">YES</bool> - </object> - <object class="NSMutableArray" key="dict.values"> - <bool key="EncodedWithXMLCoder">YES</bool> - </object> - </object> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <string>{{23, 794}, {245, 183}}</string> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <string>{{323, 672}, {199, 203}}</string> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - <reference ref="113577022"/> - <reference ref="9"/> - </object> - </object> - <object class="NSMutableDictionary" key="unlocalizedProperties"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSArray" key="dict.sortedKeys"> - <bool key="EncodedWithXMLCoder">YES</bool> - </object> - <object class="NSMutableArray" key="dict.values"> - <bool key="EncodedWithXMLCoder">YES</bool> - </object> - </object> - <nil key="activeLocalization"/> - <object class="NSMutableDictionary" key="localizations"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSArray" key="dict.sortedKeys"> - <bool key="EncodedWithXMLCoder">YES</bool> - </object> - <object class="NSMutableArray" key="dict.values"> - <bool key="EncodedWithXMLCoder">YES</bool> - </object> - </object> - <nil key="sourceID"/> - <int key="maxID">445</int> - </object> - <object class="IBClassDescriber" key="IBDocument.Classes"> - <object class="NSMutableArray" key="referencedPartialClassDescriptions"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="IBPartialClassDescription"> - <reference key="className" ref="695797635"/> - <nil key="superclassName"/> - <object class="NSMutableDictionary" key="actions"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSArray" key="dict.sortedKeys"> - <bool key="EncodedWithXMLCoder">YES</bool> - </object> - <object class="NSMutableArray" key="dict.values"> - <bool key="EncodedWithXMLCoder">YES</bool> - </object> - </object> - <object class="NSMutableDictionary" key="outlets"> - <reference key="NS.key.0" ref="684042788"/> - <string key="NS.object.0">NSTextView</string> - </object> - <object class="IBClassDescriptionSource" key="sourceIdentifier"> - <string key="majorKey">IBUserSource</string> - <reference key="minorKey" ref="255189770"/> - </object> - </object> - <object class="IBPartialClassDescription"> - <string key="className">IPython1SandboxAppDelegate</string> - <string key="superclassName">NSObject</string> - <object class="NSMutableDictionary" key="actions"> - <bool key="EncodedWithXMLCoder">YES</bool> - <object class="NSArray" key="dict.sortedKeys"> - <bool key="EncodedWithXMLCoder">YES</bool> - </object> - <object class="NSMutableArray" key="dict.values"> - <bool key="EncodedWithXMLCoder">YES</bool> - </object> - </object> - <object class="NSMutableDictionary" key="outlets"> - <string key="NS.key.0">ipythonController</string> - <string key="NS.object.0">id</string> - </object> - <object class="IBClassDescriptionSource" key="sourceIdentifier"> - <string key="majorKey">IBProjectSource</string> - <string key="minorKey">IPython1SandboxAppDelegate.py</string> - </object> - </object> - </object> - </object> - <int key="IBDocument.localizationMode">0</int> - <string key="IBDocument.LastKnownRelativeProjectPath">../../IPython1Sandbox.xcodeproj</string> - <int key="IBDocument.defaultPropertyAccessControl">3</int> - <object class="NSMutableData" key="IBDocument.RunnableNib"> - <bytes key="NS.bytes">YnBsaXN0MDDUAAEAAgADAAQABQAGAAkAClgkdmVyc2lvblQkdG9wWSRhcmNoaXZlclgkb2JqZWN0cxIA -AYag0QAHAAhdSUIub2JqZWN0ZGF0YYABXxAPTlNLZXllZEFyY2hpdmVyrxEC/gALAAwAMQA1ADYAPAA9 -AEIAWABZAFoAWwALAGgAbQB7AIAAlQCZAKAApAC0ALoAzQDRAOYA+gD7APwA/QD+AP8BAAEBAQIBAwEE -AQUBBgEHAQgBCQEKAQsBDwEQARkBIQEmASoBLQExATUBOQE7AT0BTQFSAVUBWgFBAVQBYwFqAWsBbAFv -AXQBdQF4AYAAkAGBAYQBhwGIAYkBjgGPAZABkwGYAZkBmwGeAasBrAGtAbEBvAG9Ab4BwQHCAcQBxQHG -AdIB0wHbAdwB3wHkAeUB6AHtAfAB/AIAAgcCCwIdAiUCLwIzAlECUgJaAmQCZQJoAm4CbwJyAncCiAKP -ApACkwKYApkCnAKmAqcCrAKxArICtwK4ArsCwwLJAsoC0QLWAtcC2gLcAt0C5gLnAvAC8QL1AvYC9wL4 -AvkC/wMAAwIDAwMEAwcDFgMYAxsDHAMfAAsDIAMhAyIDJQNXA10DbQNzASkDdAN5A3oDewN+A4IDgwOG -A4cDiwOPA5YDmgObA5wDnQOhA6gDrAOtA64DrwOzA7wDwAPBA8IDwwPHA84D0gPTA9QD1QPZA+AD5APl -A+YD6gPxA/UD9gP3A/gD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WLtYvljB -WMRYx1jKWM1Y0FjTWNZY2VjcWN9Y4ljlWOhY61juWPFY9Fj3WPpY/VkAWQNZBlkJWQxZD1kSWRVZGFkb -WR5ZIVkkWSdZKlktWTBZM1k2WTlZPFk/WUJZRVlIWUtZTllRWVRZV1laWV1ZYFljWWZZaVlsWW9Zcll1 -WXhZe1l+WYFZhFmHWYpZjVmQWZNZllmZWZxZn1miWaVZqFmrWa5ZsVm0WbdZulm9WcBZw1nGWclZzFnP -WdJZ1VnYWdtZ3lnhWeRZ51nqWe1Z8FnzWfZZ+Vn8Wf9aAloFWghaC1oOWhFaFFoXWhpaHVogWiNaJlop -WixaL1oyWjRaN1o5WjtaPVpAWkNaRVpIWkpaTFpOWlBaU1pWWlhaWlpcWl9aYlpkWmZaaVprWm1acFpy -WnVaeFp6Wn1af1qBWoRah1qKWoxaj1qSWpRallqYWppanVqgWqJapFqmWqhaqlqsWq9asVqzWrxav1rC -WsVax1rKWs1az1rRWtRa1lrZWtxa31rhWuNa5VrnWula61ruWvBa8lr1Wvda+Vr7Wv1a/1sBWwRbBlsI -WwtbDVsPWxJbFVsYWxtbHVsfWyFbI1slWyhbK1stWzBbMls0WzZbOFs7Wz1bQFtCW0VbSFtKW0xbTltR -W1NbVltZW1xbXlthW2NbZVtoW2pbbFtuW3FbdFt2W3hbe1t+W4Bbg1uGW4hbi1uOW5Bbk1uVW5hbmluc -W55boVujW6VbrluwW7Fbulu9W75bx1vKW8tb1FvZAAAAAAAAAgIAAAAAAAALwwAAAAAAAAAAAAAAAAAA -W+g</bytes> - </object> - </data> -</archive> diff --git a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox.xcodeproj/project.pbxproj b/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox.xcodeproj/project.pbxproj deleted file mode 100644 index 92dec61..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox.xcodeproj/project.pbxproj +++ /dev/null @@ -1,293 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 44; - objects = { - -/* Begin PBXBuildFile section */ - 77631A270C06C501005415CB /* Python.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 77631A260C06C501005415CB /* Python.framework */; }; - 77631A3F0C0748CF005415CB /* main.py in Resources */ = {isa = PBXBuildFile; fileRef = 77631A3E0C0748CF005415CB /* main.py */; }; - 7790198F0C07548A00326F66 /* IPython1SandboxAppDelegate.py in Resources */ = {isa = PBXBuildFile; fileRef = 7790198E0C07548A00326F66 /* IPython1SandboxAppDelegate.py */; }; - 77C8C1F90C07829500965286 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 77C8C1F70C07829500965286 /* MainMenu.xib */; }; - 8D11072B0486CEB800E47090 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 089C165CFE840E0CC02AAC07 /* InfoPlist.strings */; }; - 8D11072D0486CEB800E47090 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; settings = {ATTRIBUTES = (); }; }; - 8D11072F0486CEB800E47090 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1058C7A1FEA54F0111CA2CBB /* Cocoa.framework */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 089C165DFE840E0CC02AAC07 /* English */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = "<group>"; }; - 1058C7A1FEA54F0111CA2CBB /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = /System/Library/Frameworks/Cocoa.framework; sourceTree = "<absolute>"; }; - 13E42FB307B3F0F600E4EEF1 /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = /System/Library/Frameworks/CoreData.framework; sourceTree = "<absolute>"; }; - 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; }; - 29B97324FDCFA39411CA2CEA /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = /System/Library/Frameworks/AppKit.framework; sourceTree = "<absolute>"; }; - 29B97325FDCFA39411CA2CEA /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = /System/Library/Frameworks/Foundation.framework; sourceTree = "<absolute>"; }; - 32CA4F630368D1EE00C91783 /* IPython1Sandbox_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IPython1Sandbox_Prefix.pch; sourceTree = "<group>"; }; - 4CA32F870D8879B100311764 /* IPythonCocoaController Tests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "IPythonCocoaController Tests-Info.plist"; sourceTree = "<group>"; }; - 77631A260C06C501005415CB /* Python.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Python.framework; path = /System/Library/Frameworks/Python.framework; sourceTree = "<absolute>"; }; - 77631A3E0C0748CF005415CB /* main.py */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.python; path = main.py; sourceTree = "<group>"; }; - 7790198E0C07548A00326F66 /* IPython1SandboxAppDelegate.py */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.python; path = IPython1SandboxAppDelegate.py; sourceTree = "<group>"; }; - 77C8C1F80C07829500965286 /* English */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = English; path = English.lproj/MainMenu.xib; sourceTree = "<group>"; }; - 8D1107310486CEB800E47090 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; - 8D1107320486CEB800E47090 /* IPython1Sandbox.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = IPython1Sandbox.app; sourceTree = BUILT_PRODUCTS_DIR; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 8D11072E0486CEB800E47090 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 8D11072F0486CEB800E47090 /* Cocoa.framework in Frameworks */, - 77631A270C06C501005415CB /* Python.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 080E96DDFE201D6D7F000001 /* Classes */ = { - isa = PBXGroup; - children = ( - 7790198E0C07548A00326F66 /* IPython1SandboxAppDelegate.py */, - ); - name = Classes; - sourceTree = "<group>"; - }; - 1058C7A0FEA54F0111CA2CBB /* Linked Frameworks */ = { - isa = PBXGroup; - children = ( - 77631A260C06C501005415CB /* Python.framework */, - 1058C7A1FEA54F0111CA2CBB /* Cocoa.framework */, - ); - name = "Linked Frameworks"; - sourceTree = "<group>"; - }; - 1058C7A2FEA54F0111CA2CBB /* Other Frameworks */ = { - isa = PBXGroup; - children = ( - 29B97324FDCFA39411CA2CEA /* AppKit.framework */, - 13E42FB307B3F0F600E4EEF1 /* CoreData.framework */, - 29B97325FDCFA39411CA2CEA /* Foundation.framework */, - ); - name = "Other Frameworks"; - sourceTree = "<group>"; - }; - 19C28FACFE9D520D11CA2CBB /* Products */ = { - isa = PBXGroup; - children = ( - 8D1107320486CEB800E47090 /* IPython1Sandbox.app */, - ); - name = Products; - sourceTree = "<group>"; - }; - 29B97314FDCFA39411CA2CEA /* IPython1Sandbox */ = { - isa = PBXGroup; - children = ( - 080E96DDFE201D6D7F000001 /* Classes */, - 29B97315FDCFA39411CA2CEA /* Other Sources */, - 29B97317FDCFA39411CA2CEA /* Resources */, - 29B97323FDCFA39411CA2CEA /* Frameworks */, - 19C28FACFE9D520D11CA2CBB /* Products */, - 4CA32F870D8879B100311764 /* IPythonCocoaController Tests-Info.plist */, - ); - name = IPython1Sandbox; - sourceTree = "<group>"; - }; - 29B97315FDCFA39411CA2CEA /* Other Sources */ = { - isa = PBXGroup; - children = ( - 32CA4F630368D1EE00C91783 /* IPython1Sandbox_Prefix.pch */, - 29B97316FDCFA39411CA2CEA /* main.m */, - 77631A3E0C0748CF005415CB /* main.py */, - ); - name = "Other Sources"; - sourceTree = "<group>"; - }; - 29B97317FDCFA39411CA2CEA /* Resources */ = { - isa = PBXGroup; - children = ( - 77C8C1F70C07829500965286 /* MainMenu.xib */, - 8D1107310486CEB800E47090 /* Info.plist */, - 089C165CFE840E0CC02AAC07 /* InfoPlist.strings */, - ); - name = Resources; - sourceTree = "<group>"; - }; - 29B97323FDCFA39411CA2CEA /* Frameworks */ = { - isa = PBXGroup; - children = ( - 1058C7A0FEA54F0111CA2CBB /* Linked Frameworks */, - 1058C7A2FEA54F0111CA2CBB /* Other Frameworks */, - ); - name = Frameworks; - sourceTree = "<group>"; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 8D1107260486CEB800E47090 /* IPython1Sandbox */ = { - isa = PBXNativeTarget; - buildConfigurationList = C01FCF4A08A954540054247B /* Build configuration list for PBXNativeTarget "IPython1Sandbox" */; - buildPhases = ( - 8D1107290486CEB800E47090 /* Resources */, - 8D11072C0486CEB800E47090 /* Sources */, - 8D11072E0486CEB800E47090 /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = IPython1Sandbox; - productInstallPath = "$(HOME)/Applications"; - productName = IPython1Sandbox; - productReference = 8D1107320486CEB800E47090 /* IPython1Sandbox.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 29B97313FDCFA39411CA2CEA /* Project object */ = { - isa = PBXProject; - buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "IPython1Sandbox" */; - compatibilityVersion = "Xcode 3.0"; - hasScannedForEncodings = 1; - mainGroup = 29B97314FDCFA39411CA2CEA /* IPython1Sandbox */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 8D1107260486CEB800E47090 /* IPython1Sandbox */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 8D1107290486CEB800E47090 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 8D11072B0486CEB800E47090 /* InfoPlist.strings in Resources */, - 77631A3F0C0748CF005415CB /* main.py in Resources */, - 7790198F0C07548A00326F66 /* IPython1SandboxAppDelegate.py in Resources */, - 77C8C1F90C07829500965286 /* MainMenu.xib in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 8D11072C0486CEB800E47090 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 8D11072D0486CEB800E47090 /* main.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXVariantGroup section */ - 089C165CFE840E0CC02AAC07 /* InfoPlist.strings */ = { - isa = PBXVariantGroup; - children = ( - 089C165DFE840E0CC02AAC07 /* English */, - ); - name = InfoPlist.strings; - sourceTree = "<group>"; - }; - 77C8C1F70C07829500965286 /* MainMenu.xib */ = { - isa = PBXVariantGroup; - children = ( - 77C8C1F80C07829500965286 /* English */, - ); - name = MainMenu.xib; - sourceTree = "<group>"; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - C01FCF4B08A954540054247B /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 1; - GCC_DYNAMIC_NO_PIC = NO; - GCC_ENABLE_FIX_AND_CONTINUE = YES; - GCC_MODEL_TUNING = G5; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = IPython1Sandbox_Prefix.pch; - INFOPLIST_FILE = Info.plist; - INSTALL_PATH = "$(HOME)/Applications"; - PRODUCT_NAME = IPython1Sandbox; - VERSIONING_SYSTEM = "apple-generic"; - WRAPPER_EXTENSION = app; - ZERO_LINK = YES; - }; - name = Debug; - }; - C01FCF4C08A954540054247B /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - GCC_MODEL_TUNING = G5; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = IPython1Sandbox_Prefix.pch; - INFOPLIST_FILE = Info.plist; - INSTALL_PATH = "$(HOME)/Applications"; - PRODUCT_NAME = IPython1Sandbox; - VERSIONING_SYSTEM = "apple-generic"; - WRAPPER_EXTENSION = app; - }; - name = Release; - }; - C01FCF4F08A954540054247B /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - PREBINDING = NO; - SDKROOT = "$(DEVELOPER_SDK_DIR)/MacOSX10.5.sdk"; - }; - name = Debug; - }; - C01FCF5008A954540054247B /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = ( - ppc, - i386, - ); - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - PREBINDING = NO; - SDKROOT = "$(DEVELOPER_SDK_DIR)/MacOSX10.5.sdk"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - C01FCF4A08A954540054247B /* Build configuration list for PBXNativeTarget "IPython1Sandbox" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - C01FCF4B08A954540054247B /* Debug */, - C01FCF4C08A954540054247B /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - C01FCF4E08A954540054247B /* Build configuration list for PBXProject "IPython1Sandbox" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - C01FCF4F08A954540054247B /* Debug */, - C01FCF5008A954540054247B /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 29B97313FDCFA39411CA2CEA /* Project object */; -} diff --git a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1SandboxAppDelegate.py b/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1SandboxAppDelegate.py deleted file mode 100644 index 361b7b5..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1SandboxAppDelegate.py +++ /dev/null @@ -1,39 +0,0 @@ -# -# IPython1SandboxAppDelegate.py -# IPython1Sandbox -# -# Created by Barry Wark on 3/4/08. -# Copyright __MyCompanyName__ 2008. All rights reserved. -# - -from Foundation import NSObject, NSPredicate -import objc -import threading - -from PyObjCTools import AppHelper - -from twisted.internet import reactor - -class IPython1SandboxAppDelegate(NSObject): - ipythonController = objc.IBOutlet() - - def applicationShouldTerminate_(self, sender): - if reactor.running: - reactor.addSystemEventTrigger( - 'after', 'shutdown', AppHelper.stopEventLoop) - reactor.stop() - return False - return True - - - def applicationDidFinishLaunching_(self, sender): - reactor.interleave(AppHelper.callAfter) - assert(reactor.running) - - - def workspaceFilterPredicate(self): - return NSPredicate.predicateWithFormat_("NOT (self.value BEGINSWITH '<')") - - - - diff --git a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox_Prefix.pch b/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox_Prefix.pch deleted file mode 100644 index 7ce12e2..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox_Prefix.pch +++ /dev/null @@ -1,7 +0,0 @@ -// -// Prefix header for all source files of the 'IPython1Sandbox' target in the 'IPython1Sandbox' project -// - -#ifdef __OBJC__ - #import <Cocoa/Cocoa.h> -#endif diff --git a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPythonCocoaController Tests-Info.plist b/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPythonCocoaController Tests-Info.plist deleted file mode 100644 index eb983f2..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPythonCocoaController Tests-Info.plist +++ /dev/null @@ -1,20 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> -<plist version="1.0"> -<dict> - <key>CFBundleDevelopmentRegion</key> - <string>English</string> - <key>CFBundleExecutable</key> - <string>${EXECUTABLE_NAME}</string> - <key>CFBundleIdentifier</key> - <string>com.yourcompany.IPythonCocoaController Tests</string> - <key>CFBundleInfoDictionaryVersion</key> - <string>6.0</string> - <key>CFBundlePackageType</key> - <string>BNDL</string> - <key>CFBundleSignature</key> - <string>????</string> - <key>CFBundleVersion</key> - <string>1.0</string> -</dict> -</plist> diff --git a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/Info.plist b/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/Info.plist deleted file mode 100644 index ed102a5..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/Info.plist +++ /dev/null @@ -1,30 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> -<plist version="1.0"> -<dict> - <key>CFBundleDevelopmentRegion</key> - <string>English</string> - <key>CFBundleExecutable</key> - <string>${EXECUTABLE_NAME}</string> - <key>CFBundleIconFile</key> - <string></string> - <key>CFBundleIdentifier</key> - <string>com.yourcompany.IPython1Sandbox</string> - <key>CFBundleInfoDictionaryVersion</key> - <string>6.0</string> - <key>CFBundleName</key> - <string>${PRODUCT_NAME}</string> - <key>CFBundlePackageType</key> - <string>APPL</string> - <key>CFBundleShortVersionString</key> - <string>0.1</string> - <key>CFBundleSignature</key> - <string>????</string> - <key>CFBundleVersion</key> - <string>1.0</string> - <key>NSMainNibFile</key> - <string>MainMenu</string> - <key>NSPrincipalClass</key> - <string>NSApplication</string> -</dict> -</plist> diff --git a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/main.m b/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/main.m deleted file mode 100644 index dcf8e84..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/main.m +++ /dev/null @@ -1,49 +0,0 @@ -// -// main.m -// IPython1Sandbox -// -// Created by Barry Wark on 3/4/08. -// Copyright __MyCompanyName__ 2008. All rights reserved. -// - -#import <Python/Python.h> -#import <Cocoa/Cocoa.h> - -int main(int argc, char *argv[]) -{ - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - NSBundle *mainBundle = [NSBundle mainBundle]; - NSString *resourcePath = [mainBundle resourcePath]; - NSArray *pythonPathArray = [NSArray arrayWithObjects: resourcePath, [resourcePath stringByAppendingPathComponent:@"PyObjC"], nil]; - - setenv("PYTHONPATH", [[pythonPathArray componentsJoinedByString:@":"] UTF8String], 1); - - NSArray *possibleMainExtensions = [NSArray arrayWithObjects: @"py", @"pyc", @"pyo", nil]; - NSString *mainFilePath = nil; - - for (NSString *possibleMainExtension in possibleMainExtensions) { - mainFilePath = [mainBundle pathForResource: @"main" ofType: possibleMainExtension]; - if ( mainFilePath != nil ) break; - } - - if ( !mainFilePath ) { - [NSException raise: NSInternalInconsistencyException format: @"%s:%d main() Failed to find the Main.{py,pyc,pyo} file in the application wrapper's Resources directory.", __FILE__, __LINE__]; - } - - Py_SetProgramName("/usr/bin/python"); - Py_Initialize(); - PySys_SetArgv(argc, (char **)argv); - - const char *mainFilePathPtr = [mainFilePath UTF8String]; - FILE *mainFile = fopen(mainFilePathPtr, "r"); - int result = PyRun_SimpleFile(mainFile, (char *)[[mainFilePath lastPathComponent] UTF8String]); - - if ( result != 0 ) - [NSException raise: NSInternalInconsistencyException - format: @"%s:%d main() PyRun_SimpleFile failed with file '%@'. See console for errors.", __FILE__, __LINE__, mainFilePath]; - - [pool drain]; - - return result; -} diff --git a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/main.py b/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/main.py deleted file mode 100644 index f01104d..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/main.py +++ /dev/null @@ -1,24 +0,0 @@ -# -# main.py -# IPython1Sandbox -# -# Created by Barry Wark on 3/4/08. -# Copyright __MyCompanyName__ 2008. All rights reserved. -# - -#import modules required by application -import objc -import Foundation -import AppKit - -from PyObjCTools import AppHelper - -from twisted.internet import _threadedselect -reactor = _threadedselect.install() - -# import modules containing classes required to start application and load MainMenu.nib -import IPython1SandboxAppDelegate -import IPython.frontend.cocoa.cocoa_frontend - -# pass control to AppKit -AppHelper.runEventLoop() diff --git a/IPython/deathrow/oldfrontend/cocoa/plugin/CocoaFrontendPlugin.xcodeproj/project.pbxproj b/IPython/deathrow/oldfrontend/cocoa/plugin/CocoaFrontendPlugin.xcodeproj/project.pbxproj deleted file mode 100644 index 525d6ef..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/plugin/CocoaFrontendPlugin.xcodeproj/project.pbxproj +++ /dev/null @@ -1,256 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 42; - objects = { - -/* Begin PBXContainerItemProxy section */ - 4C5B7ADB0E1A0BCD006CB905 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 4C96F4FE0E199AB500B03430 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 4C96F50C0E199AF100B03430; - remoteInfo = "Cocoa Frontend Plugin"; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXFileReference section */ - 4C5B7A8D0E1A0B4C006CB905 /* Plugin-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Plugin-Info.plist"; sourceTree = "<group>"; }; - 4C5B7AD30E1A0BC8006CB905 /* Placeholder (Do Not Use).bundle */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "Placeholder (Do Not Use).bundle"; sourceTree = BUILT_PRODUCTS_DIR; }; - 4C5B7AD40E1A0BC8006CB905 /* Placeholder (Do Not Use)-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Placeholder (Do Not Use)-Info.plist"; sourceTree = "<group>"; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 4C5B7AD10E1A0BC8006CB905 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 4C5B7A8C0E1A0B4C006CB905 /* Products */ = { - isa = PBXGroup; - children = ( - 4C5B7AD30E1A0BC8006CB905 /* Placeholder (Do Not Use).bundle */, - ); - name = Products; - sourceTree = "<group>"; - }; - 4C96F4FC0E199AB500B03430 = { - isa = PBXGroup; - children = ( - 4C5B7A8C0E1A0B4C006CB905 /* Products */, - 4C5B7A8D0E1A0B4C006CB905 /* Plugin-Info.plist */, - 4C5B7AD40E1A0BC8006CB905 /* Placeholder (Do Not Use)-Info.plist */, - ); - sourceTree = "<group>"; - }; -/* End PBXGroup section */ - -/* Begin PBXLegacyTarget section */ - 4C96F50C0E199AF100B03430 /* Cocoa Frontend Plugin */ = { - isa = PBXLegacyTarget; - buildArgumentsString = "$(ACTION)"; - buildConfigurationList = 4C96F5110E199B3300B03430 /* Build configuration list for PBXLegacyTarget "Cocoa Frontend Plugin" */; - buildPhases = ( - ); - buildToolPath = /usr/bin/make; - buildWorkingDirectory = ""; - dependencies = ( - ); - name = "Cocoa Frontend Plugin"; - passBuildSettingsInEnvironment = 1; - productName = "Cocoa Frontend Plugin"; - }; -/* End PBXLegacyTarget section */ - -/* Begin PBXNativeTarget section */ - 4C5B7AD20E1A0BC8006CB905 /* Placeholder (Do Not Use) */ = { - isa = PBXNativeTarget; - buildConfigurationList = 4C5B7ADA0E1A0BC9006CB905 /* Build configuration list for PBXNativeTarget "Placeholder (Do Not Use)" */; - buildPhases = ( - 4C5B7ACF0E1A0BC8006CB905 /* Resources */, - 4C5B7AD00E1A0BC8006CB905 /* Sources */, - 4C5B7AD10E1A0BC8006CB905 /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - 4C5B7ADC0E1A0BCD006CB905 /* PBXTargetDependency */, - ); - name = "Placeholder (Do Not Use)"; - productName = "Placeholder (Do Not Use)"; - productReference = 4C5B7AD30E1A0BC8006CB905 /* Placeholder (Do Not Use).bundle */; - productType = "com.apple.product-type.bundle"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 4C96F4FE0E199AB500B03430 /* Project object */ = { - isa = PBXProject; - buildConfigurationList = 4C96F5010E199AB500B03430 /* Build configuration list for PBXProject "CocoaFrontendPlugin" */; - compatibilityVersion = "Xcode 2.4"; - hasScannedForEncodings = 0; - mainGroup = 4C96F4FC0E199AB500B03430; - productRefGroup = 4C5B7A8C0E1A0B4C006CB905 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 4C96F50C0E199AF100B03430 /* Cocoa Frontend Plugin */, - 4C5B7AD20E1A0BC8006CB905 /* Placeholder (Do Not Use) */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 4C5B7ACF0E1A0BC8006CB905 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 4C5B7AD00E1A0BC8006CB905 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 4C5B7ADC0E1A0BCD006CB905 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 4C96F50C0E199AF100B03430 /* Cocoa Frontend Plugin */; - targetProxy = 4C5B7ADB0E1A0BCD006CB905 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin XCBuildConfiguration section */ - 4C5B7AD50E1A0BC9006CB905 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_ENABLE_FIX_AND_CONTINUE = YES; - GCC_MODEL_TUNING = G5; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h"; - INFOPLIST_FILE = "Placeholder (Do Not Use)-Info.plist"; - INSTALL_PATH = "$(HOME)/Library/Bundles"; - OTHER_LDFLAGS = ( - "-framework", - Foundation, - "-framework", - AppKit, - ); - PREBINDING = NO; - PRODUCT_NAME = "Placeholder (Do Not Use)"; - WRAPPER_EXTENSION = bundle; - ZERO_LINK = YES; - }; - name = Debug; - }; - 4C5B7AD60E1A0BC9006CB905 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - GCC_ENABLE_FIX_AND_CONTINUE = NO; - GCC_MODEL_TUNING = G5; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h"; - INFOPLIST_FILE = "Placeholder (Do Not Use)-Info.plist"; - INSTALL_PATH = "$(HOME)/Library/Bundles"; - OTHER_LDFLAGS = ( - "-framework", - Foundation, - "-framework", - AppKit, - ); - PREBINDING = NO; - PRODUCT_NAME = "Placeholder (Do Not Use)"; - WRAPPER_EXTENSION = bundle; - ZERO_LINK = NO; - }; - name = Release; - }; - 4C96F4FF0E199AB500B03430 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = NO; - }; - name = Debug; - }; - 4C96F5000E199AB500B03430 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = YES; - }; - name = Release; - }; - 4C96F50D0E199AF100B03430 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - PRODUCT_NAME = "Cocoa Frontend Plugin"; - }; - name = Debug; - }; - 4C96F50E0E199AF100B03430 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - GCC_ENABLE_FIX_AND_CONTINUE = NO; - PRODUCT_NAME = "Cocoa Frontend Plugin"; - ZERO_LINK = NO; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 4C5B7ADA0E1A0BC9006CB905 /* Build configuration list for PBXNativeTarget "Placeholder (Do Not Use)" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 4C5B7AD50E1A0BC9006CB905 /* Debug */, - 4C5B7AD60E1A0BC9006CB905 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4C96F5010E199AB500B03430 /* Build configuration list for PBXProject "CocoaFrontendPlugin" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 4C96F4FF0E199AB500B03430 /* Debug */, - 4C96F5000E199AB500B03430 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4C96F5110E199B3300B03430 /* Build configuration list for PBXLegacyTarget "Cocoa Frontend Plugin" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 4C96F50D0E199AF100B03430 /* Debug */, - 4C96F50E0E199AF100B03430 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 4C96F4FE0E199AB500B03430 /* Project object */; -} diff --git a/IPython/deathrow/oldfrontend/cocoa/plugin/IPythonCocoaFrontendLoader.py b/IPython/deathrow/oldfrontend/cocoa/plugin/IPythonCocoaFrontendLoader.py deleted file mode 100644 index 748a1c1..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/plugin/IPythonCocoaFrontendLoader.py +++ /dev/null @@ -1,25 +0,0 @@ -# encoding: utf-8 -""" -Provides a namespace for loading the Cocoa frontend via a Cocoa plugin. - -Author: Barry Wark -""" -__docformat__ = "restructuredtext en" - -#----------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#----------------------------------------------------------------------------- - -from PyObjCTools import AppHelper -from twisted.internet import _threadedselect - -#make sure _threadedselect is installed first -reactor = _threadedselect.install() - -# load the Cocoa frontend controller -from IPython.frontend.cocoa.cocoa_frontend import IPythonCocoaController -reactor.interleave(AppHelper.callAfter) -assert(reactor.running) diff --git a/IPython/deathrow/oldfrontend/cocoa/plugin/Makefile b/IPython/deathrow/oldfrontend/cocoa/plugin/Makefile deleted file mode 100644 index 109d8bf..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/plugin/Makefile +++ /dev/null @@ -1,6 +0,0 @@ -include ./plugins.mk - -all : dist/IPythonCocoaController.plugin - -dist/IPythonCocoaController.plugin : ./IPythonCocoaFrontendLoader.py\ - ./setup.py \ No newline at end of file diff --git a/IPython/deathrow/oldfrontend/cocoa/plugin/Placeholder (Do Not Use)-Info.plist b/IPython/deathrow/oldfrontend/cocoa/plugin/Placeholder (Do Not Use)-Info.plist deleted file mode 100644 index 01fd88b..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/plugin/Placeholder (Do Not Use)-Info.plist +++ /dev/null @@ -1,20 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> -<plist version="1.0"> -<dict> - <key>CFBundleDevelopmentRegion</key> - <string>English</string> - <key>CFBundleExecutable</key> - <string>${EXECUTABLE_NAME}</string> - <key>CFBundleIdentifier</key> - <string>com.yourcompany.Placeholder (Do Not Use)</string> - <key>CFBundleInfoDictionaryVersion</key> - <string>6.0</string> - <key>CFBundlePackageType</key> - <string>BNDL</string> - <key>CFBundleSignature</key> - <string>????</string> - <key>CFBundleVersion</key> - <string>1.0</string> -</dict> -</plist> diff --git a/IPython/deathrow/oldfrontend/cocoa/plugin/plugins.mk b/IPython/deathrow/oldfrontend/cocoa/plugin/plugins.mk deleted file mode 100644 index 2df61f0..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/plugin/plugins.mk +++ /dev/null @@ -1,21 +0,0 @@ -%.plugin:: - rm -rf dist/$(notdir $@) - rm -rf build dist && \ - python setup.py py2app -s - -%.py: - @echo "test -f $@" - @test -f %@ - -%.nib: - @echo "test -f $@" - @test -f %@ - -.DEFAULT_GOAL := all - -.PHONY : all clean - -clean : - rm -rf build dist - - diff --git a/IPython/deathrow/oldfrontend/cocoa/plugin/setup.py b/IPython/deathrow/oldfrontend/cocoa/plugin/setup.py deleted file mode 100644 index 398f823..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/plugin/setup.py +++ /dev/null @@ -1,35 +0,0 @@ -# encoding: utf-8 -""" -setup.py - -Setuptools installer script for generating a Cocoa plugin for the -IPython cocoa frontend - -Author: Barry Wark -""" -__docformat__ = "restructuredtext en" - -#----------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#----------------------------------------------------------------------------- - -from setuptools import setup - -infoPlist = dict( - CFBundleDevelopmentRegion='English', - CFBundleIdentifier='org.scipy.ipython.cocoa_frontend', - NSPrincipalClass='IPythonCocoaController', -) - -setup( - plugin=['IPythonCocoaFrontendLoader.py'], - setup_requires=['py2app'], - options=dict(py2app=dict( - plist=infoPlist, - site_packages=True, - excludes=['IPython','twisted','PyObjCTools'] - )), -) \ No newline at end of file diff --git a/IPython/deathrow/oldfrontend/cocoa/tests/test_cocoa_frontend.py b/IPython/deathrow/oldfrontend/cocoa/tests/test_cocoa_frontend.py deleted file mode 100644 index 3640bfe..0000000 --- a/IPython/deathrow/oldfrontend/cocoa/tests/test_cocoa_frontend.py +++ /dev/null @@ -1,100 +0,0 @@ -# encoding: utf-8 -"""This file contains unittests for the -IPython.frontend.cocoa.cocoa_frontend module. -""" -__docformat__ = "restructuredtext en" - -#--------------------------------------------------------------------------- -# Copyright (C) 2005-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#--------------------------------------------------------------------------- - -#--------------------------------------------------------------------------- -# Imports -#--------------------------------------------------------------------------- - -# Tell nose to skip this module -__test__ = {} - -from twisted.trial import unittest -from twisted.internet.defer import succeed - -from IPython.kernel.core.interpreter import Interpreter -import IPython.kernel.engineservice as es - -try: - from IPython.frontend.cocoa.cocoa_frontend import IPythonCocoaController - from Foundation import NSMakeRect - from AppKit import NSTextView, NSScrollView -except ImportError: - # This tells twisted.trial to skip this module if PyObjC is not found - skip = True - -#--------------------------------------------------------------------------- -# Tests -#--------------------------------------------------------------------------- -class TestIPythonCocoaControler(unittest.TestCase): - """Tests for IPythonCocoaController""" - - def setUp(self): - self.controller = IPythonCocoaController.alloc().init() - self.engine = es.EngineService() - self.engine.startService() - - def tearDown(self): - self.controller = None - self.engine.stopService() - - def testControllerExecutesCode(self): - code ="""5+5""" - expected = Interpreter().execute(code) - del expected['number'] - def removeNumberAndID(result): - del result['number'] - del result['id'] - return result - d = self.controller.execute(code) - d.addCallback(removeNumberAndID) - d.addCallback(lambda r: self.assertEquals(r, expected)) - - def testControllerMirrorsUserNSWithValuesAsStrings(self): - code = """userns1=1;userns2=2""" - def testControllerUserNS(result): - self.assertEquals(self.controller.userNS['userns1'], 1) - self.assertEquals(self.controller.userNS['userns2'], 2) - self.controller.execute(code).addCallback(testControllerUserNS) - - def testControllerInstantiatesIEngine(self): - self.assert_(es.IEngineBase.providedBy(self.controller.engine)) - - def testControllerCompletesToken(self): - code = """longNameVariable=10""" - def testCompletes(result): - self.assert_("longNameVariable" in result) - - def testCompleteToken(result): - self.controller.complete("longNa").addCallback(testCompletes) - - self.controller.execute(code).addCallback(testCompletes) - - - def testCurrentIndent(self): - """test that current_indent_string returns current indent or None. - Uses _indent_for_block for direct unit testing. - """ - - self.controller.tabUsesSpaces = True - self.assert_(self.controller._indent_for_block("""a=3""") == None) - self.assert_(self.controller._indent_for_block("") == None) - block = """def test():\n a=3""" - self.assert_(self.controller._indent_for_block(block) == \ - ' ' * self.controller.tabSpaces) - - block = """if(True):\n%sif(False):\n%spass""" % \ - (' '*self.controller.tabSpaces, - 2*' '*self.controller.tabSpaces) - self.assert_(self.controller._indent_for_block(block) == \ - 2*(' '*self.controller.tabSpaces)) - diff --git a/IPython/deathrow/oldfrontend/frontendbase.py b/IPython/deathrow/oldfrontend/frontendbase.py deleted file mode 100644 index aeb1c16..0000000 --- a/IPython/deathrow/oldfrontend/frontendbase.py +++ /dev/null @@ -1,343 +0,0 @@ -# encoding: utf-8 -# -*- test-case-name: IPython.frontend.tests.test_frontendbase -*- -""" -frontendbase provides an interface and base class for GUI frontends for -IPython.kernel/IPython.kernel.core. - -Frontend implementations will likely want to subclass FrontEndBase. - -Author: Barry Wark -""" -__docformat__ = "restructuredtext en" - -#------------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports -#------------------------------------------------------------------------------- -import string -import codeop -import uuid - - -from IPython.frontend.zopeinterface import ( - Interface, - Attribute, -) -from IPython.kernel.core.history import FrontEndHistory -from IPython.kernel.core.util import Bunch - -############################################################################## -# TEMPORARY!!! fake configuration, while we decide whether to use tconfig or -# not - -rc = Bunch() -rc.prompt_in1 = r'In [$number]: ' -rc.prompt_in2 = r'...' -rc.prompt_out = r'Out [$number]: ' - -############################################################################## -# Interface definitions -############################################################################## - -class IFrontEndFactory(Interface): - """Factory interface for frontends.""" - - def __call__(engine=None, history=None): - """ - Parameters: - interpreter : IPython.kernel.engineservice.IEngineCore - """ - - pass - - -class IFrontEnd(Interface): - """Interface for frontends. All methods return t.i.d.Deferred""" - - Attribute("input_prompt_template", "string.Template instance\ - substituteable with execute result.") - Attribute("output_prompt_template", "string.Template instance\ - substituteable with execute result.") - Attribute("continuation_prompt_template", "string.Template instance\ - substituteable with execute result.") - - def update_cell_prompt(result, blockID=None): - """Subclass may override to update the input prompt for a block. - - In asynchronous frontends, this method will be called as a - twisted.internet.defer.Deferred's callback/errback. - Implementations should thus return result when finished. - - Result is a result dict in case of success, and a - twisted.python.util.failure.Failure in case of an error - """ - - pass - - def render_result(result): - """Render the result of an execute call. Implementors may choose the - method of rendering. - For example, a notebook-style frontend might render a Chaco plot - inline. - - Parameters: - result : dict (result of IEngineBase.execute ) - blockID = result['blockID'] - - Result: - Output of frontend rendering - """ - - pass - - def render_error(failure): - """Subclasses must override to render the failure. - - In asynchronous frontend, since this method will be called as a - twisted.internet.defer.Deferred's callback. Implementations - should thus return result when finished. - - blockID = failure.blockID - """ - - pass - - def input_prompt(number=''): - """Returns the input prompt by subsituting into - self.input_prompt_template - """ - pass - - def output_prompt(number=''): - """Returns the output prompt by subsituting into - self.output_prompt_template - """ - - pass - - def continuation_prompt(): - """Returns the continuation prompt by subsituting into - self.continuation_prompt_template - """ - - pass - - def is_complete(block): - """Returns True if block is complete, False otherwise.""" - - pass - - - def get_history_previous(current_block): - """Returns the block previous in the history. Saves currentBlock if - the history_cursor is currently at the end of the input history""" - pass - - def get_history_next(): - """Returns the next block in the history.""" - - pass - - def complete(self, line): - """Returns the list of possible completions, and the completed - line. - - The input argument is the full line to be completed. This method - returns both the line completed as much as possible, and the list - of further possible completions (full words). - """ - pass - - -############################################################################## -# Base class for all the frontends. -############################################################################## - -class FrontEndBase(object): - """ - FrontEndBase manages the state tasks for a CLI frontend: - - Input and output history management - - Input/continuation and output prompt generation - - Some issues (due to possibly unavailable engine): - - How do we get the current cell number for the engine? - - How do we handle completions? - """ - - history_cursor = 0 - - input_prompt_template = string.Template(rc.prompt_in1) - output_prompt_template = string.Template(rc.prompt_out) - continuation_prompt_template = string.Template(rc.prompt_in2) - - def __init__(self, shell=None, history=None): - self.shell = shell - if history is None: - self.history = FrontEndHistory(input_cache=['']) - else: - self.history = history - - - def input_prompt(self, number=''): - """Returns the current input prompt - - It would be great to use ipython1.core.prompts.Prompt1 here - """ - return self.input_prompt_template.safe_substitute({'number':number}) - - - def continuation_prompt(self): - """Returns the current continuation prompt""" - - return self.continuation_prompt_template.safe_substitute() - - def output_prompt(self, number=''): - """Returns the output prompt for result""" - - return self.output_prompt_template.safe_substitute({'number':number}) - - - def is_complete(self, block): - """Determine if block is complete. - - Parameters - block : string - - Result - True if block can be sent to the engine without compile errors. - False otherwise. - """ - - try: - is_complete = codeop.compile_command(block.rstrip() + '\n\n', - "<string>", "exec") - except: - return False - - lines = block.split('\n') - return ((is_complete is not None) - and (len(lines)==1 or str(lines[-1])=='')) - - - def execute(self, block, blockID=None): - """Execute the block and return the result. - - Parameters: - block : {str, AST} - blockID : any - Caller may provide an ID to identify this block. - result['blockID'] := blockID - - Result: - Deferred result of self.interpreter.execute - """ - - if(not self.is_complete(block)): - raise Exception("Block is not compilable") - - if(blockID == None): - blockID = uuid.uuid4() - - try: - result = self.shell.execute(block) - except Exception as e: - e = self._add_block_id_for_failure(e, blockID=blockID) - e = self.update_cell_prompt(e, blockID=blockID) - e = self.render_error(e) - else: - result = self._add_block_id_for_result(result, blockID=blockID) - result = self.update_cell_prompt(result, blockID=blockID) - result = self.render_result(result) - - return result - - - def _add_block_id_for_result(self, result, blockID): - """Add the blockID to result or failure. Unfortunatley, we have to - treat failures differently than result dicts. - """ - - result['blockID'] = blockID - - return result - - def _add_block_id_for_failure(self, failure, blockID): - """_add_block_id_for_failure""" - failure.blockID = blockID - return failure - - - def _add_history(self, result, block=None): - """Add block to the history""" - - assert(block != None) - self.history.add_items([block]) - self.history_cursor += 1 - - return result - - - def get_history_previous(self, current_block): - """ Returns previous history string and decrement history cursor. - """ - command = self.history.get_history_item(self.history_cursor - 1) - - if command is not None: - if(self.history_cursor+1 == len(self.history.input_cache)): - self.history.input_cache[self.history_cursor] = current_block - self.history_cursor -= 1 - return command - - - def get_history_next(self): - """ Returns next history string and increment history cursor. - """ - command = self.history.get_history_item(self.history_cursor+1) - - if command is not None: - self.history_cursor += 1 - return command - - ### - # Subclasses probably want to override these methods... - ### - - def update_cell_prompt(self, result, blockID=None): - """Subclass may override to update the input prompt for a block. - - This method only really makes sens in asyncrhonous frontend. - Since this method will be called as a - twisted.internet.defer.Deferred's callback, implementations should - return result when finished. - """ - - raise NotImplementedError - - - def render_result(self, result): - """Subclasses must override to render result. - - In asynchronous frontends, this method will be called as a - twisted.internet.defer.Deferred's callback. Implementations - should thus return result when finished. - """ - - raise NotImplementedError - - - def render_error(self, failure): - """Subclasses must override to render the failure. - - In asynchronous frontends, this method will be called as a - twisted.internet.defer.Deferred's callback. Implementations - should thus return result when finished. - """ - - raise NotImplementedError - diff --git a/IPython/deathrow/oldfrontend/linefrontendbase.py b/IPython/deathrow/oldfrontend/linefrontendbase.py deleted file mode 100644 index 491c47c..0000000 --- a/IPython/deathrow/oldfrontend/linefrontendbase.py +++ /dev/null @@ -1,373 +0,0 @@ -""" -Base front end class for all line-oriented frontends, rather than -block-oriented. - -Currently this focuses on synchronous frontends. -""" -__docformat__ = "restructuredtext en" - -#------------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports -#------------------------------------------------------------------------------- -import re - -import sys -import codeop - -from frontendbase import FrontEndBase -from IPython.kernel.core.interpreter import Interpreter - -def common_prefix(strings): - """ Given a list of strings, return the common prefix between all - these strings. - """ - ref = strings[0] - prefix = '' - for size in range(len(ref)): - test_prefix = ref[:size+1] - for string in strings[1:]: - if not string.startswith(test_prefix): - return prefix - prefix = test_prefix - - return prefix - -#----------------------------------------------------------------------------- -# Base class for the line-oriented front ends -#----------------------------------------------------------------------------- - -class LineFrontEndBase(FrontEndBase): - """ Concrete implementation of the FrontEndBase class. This is meant - to be the base class behind all the frontend that are line-oriented, - rather than block-oriented. - """ - - # We need to keep the prompt number, to be able to increment - # it when there is an exception. - prompt_number = 1 - - # We keep a reference to the last result: it helps testing and - # programatic control of the frontend. - last_result = dict(number=0) - - # The last prompt displayed. Useful for continuation prompts. - last_prompt = '' - - # The input buffer being edited - input_buffer = '' - - # Set to true for debug output - debug = False - - # A banner to print at startup - banner = None - - #-------------------------------------------------------------------------- - # FrontEndBase interface - #-------------------------------------------------------------------------- - - def __init__(self, shell=None, history=None, banner=None, *args, **kwargs): - if shell is None: - shell = Interpreter() - FrontEndBase.__init__(self, shell=shell, history=history) - - if banner is not None: - self.banner = banner - - def start(self): - """ Put the frontend in a state where it is ready for user - interaction. - """ - if self.banner is not None: - self.write(self.banner, refresh=False) - - self.new_prompt(self.input_prompt_template.substitute(number=1)) - - - def complete(self, line): - """Complete line in engine's user_ns - - Parameters - ---------- - line : string - - Returns - ------- - The replacement for the line and the list of possible completions. - """ - completions = self.shell.complete(line) - complete_sep = re.compile('[\s\{\}\[\]\(\)\=]') - if completions: - prefix = common_prefix(completions) - residual = complete_sep.split(line)[:-1] - line = line[:-len(residual)] + prefix - return line, completions - - - def render_result(self, result): - """ Frontend-specific rendering of the result of a calculation - that has been sent to an engine. - """ - if 'stdout' in result and result['stdout']: - self.write('\n' + result['stdout']) - if 'display' in result and result['display']: - self.write("%s%s\n" % ( - self.output_prompt_template.substitute( - number=result['number']), - result['display']['pprint'] - ) ) - - - def render_error(self, failure): - """ Frontend-specific rendering of error. - """ - self.write('\n\n'+str(failure)+'\n\n') - return failure - - - def is_complete(self, string): - """ Check if a string forms a complete, executable set of - commands. - - For the line-oriented frontend, multi-line code is not executed - as soon as it is complete: the users has to enter two line - returns. - """ - if string in ('', '\n'): - # Prefiltering, eg through ipython0, may return an empty - # string although some operations have been accomplished. We - # thus want to consider an empty string as a complete - # statement. - return True - elif ( len(self.input_buffer.split('\n'))>2 - and not re.findall(r"\n[\t ]*\n[\t ]*$", string)): - return False - else: - self.capture_output() - try: - # Add line returns here, to make sure that the statement is - # complete (except if '\' was used). - # This should probably be done in a different place (like - # maybe 'prefilter_input' method? For now, this works. - clean_string = string.rstrip('\n') - if not clean_string.endswith('\\'): clean_string +='\n\n' - is_complete = codeop.compile_command(clean_string, - "<string>", "exec") - self.release_output() - except Exception as e: - # XXX: Hack: return True so that the - # code gets executed and the error captured. - is_complete = True - return is_complete - - - def write(self, string, refresh=True): - """ Write some characters to the display. - - Subclass should overide this method. - - The refresh keyword argument is used in frontends with an - event loop, to choose whether the write should trigget an UI - refresh, and thus be syncrhonous, or not. - """ - print >>sys.__stderr__, string - - - def execute(self, python_string, raw_string=None): - """ Stores the raw_string in the history, and sends the - python string to the interpreter. - """ - if raw_string is None: - raw_string = python_string - # Create a false result, in case there is an exception - self.last_result = dict(number=self.prompt_number) - - try: - try: - self.history.input_cache[-1] = raw_string.rstrip() - result = self.shell.execute(python_string) - self.last_result = result - self.render_result(result) - except: - self.show_traceback() - finally: - self.after_execute() - - - #-------------------------------------------------------------------------- - # LineFrontEndBase interface - #-------------------------------------------------------------------------- - - def prefilter_input(self, string): - """ Prefilter the input to turn it in valid python. - """ - string = string.replace('\r\n', '\n') - string = string.replace('\t', 4*' ') - # Clean the trailing whitespace - string = '\n'.join(l.rstrip() for l in string.split('\n')) - return string - - - def after_execute(self): - """ All the operations required after an execution to put the - terminal back in a shape where it is usable. - """ - self.prompt_number += 1 - self.new_prompt(self.input_prompt_template.substitute( - number=(self.last_result['number'] + 1))) - # Start a new empty history entry - self._add_history(None, '') - self.history_cursor = len(self.history.input_cache) - 1 - - - def complete_current_input(self): - """ Do code completion on current line. - """ - if self.debug: - print >>sys.__stdout__, "complete_current_input", - line = self.input_buffer - new_line, completions = self.complete(line) - if len(completions)>1: - self.write_completion(completions, new_line=new_line) - elif not line == new_line: - self.input_buffer = new_line - if self.debug: - print >>sys.__stdout__, 'line', line - print >>sys.__stdout__, 'new_line', new_line - print >>sys.__stdout__, completions - - - def get_line_width(self): - """ Return the width of the line in characters. - """ - return 80 - - - def write_completion(self, possibilities, new_line=None): - """ Write the list of possible completions. - - new_line is the completed input line that should be displayed - after the completion are writen. If None, the input_buffer - before the completion is used. - """ - if new_line is None: - new_line = self.input_buffer - - self.write('\n') - max_len = len(max(possibilities, key=len)) + 1 - - # Now we check how much symbol we can put on a line... - chars_per_line = self.get_line_width() - symbols_per_line = max(1, chars_per_line/max_len) - - pos = 1 - completion_string = [] - for symbol in possibilities: - if pos < symbols_per_line: - completion_string.append(symbol.ljust(max_len)) - pos += 1 - else: - completion_string.append(symbol.rstrip() + '\n') - pos = 1 - self.write(''.join(completion_string)) - self.new_prompt(self.input_prompt_template.substitute( - number=self.last_result['number'] + 1)) - self.input_buffer = new_line - - - def new_prompt(self, prompt): - """ Prints a prompt and starts a new editing buffer. - - Subclasses should use this method to make sure that the - terminal is put in a state favorable for a new line - input. - """ - self.input_buffer = '' - self.write(prompt) - - - def continuation_prompt(self): - """Returns the current continuation prompt. - """ - return ("."*(len(self.last_prompt)-2) + ': ') - - - def execute_command(self, command, hidden=False): - """ Execute a command, not only in the model, but also in the - view, if any. - """ - return self.shell.execute(command) - - #-------------------------------------------------------------------------- - # Private API - #-------------------------------------------------------------------------- - - def _on_enter(self, new_line_pos=0): - """ Called when the return key is pressed in a line editing - buffer. - - Parameters - ---------- - new_line_pos : integer, optional - Position of the new line to add, starting from the - end (0 adds a new line after the last line, -1 before - the last line...) - - Returns - ------- - True if execution is triggered - """ - current_buffer = self.input_buffer - # XXX: This string replace is ugly, but there should be no way it - # fails. - prompt_less_buffer = re.sub('^' + self.continuation_prompt(), - '', current_buffer).replace('\n' + self.continuation_prompt(), - '\n') - cleaned_buffer = self.prefilter_input(prompt_less_buffer) - if self.is_complete(cleaned_buffer): - self.execute(cleaned_buffer, raw_string=current_buffer) - return True - else: - # Start a new line. - new_line_pos = -new_line_pos - lines = current_buffer.split('\n')[:-1] - prompt_less_lines = prompt_less_buffer.split('\n') - # Create the new line, with the continuation prompt, and the - # same amount of indent than the line above it. - new_line = self.continuation_prompt() + \ - self._get_indent_string('\n'.join( - prompt_less_lines[:new_line_pos-1])) - if len(lines) == 1: - # We are starting a first continuation line. Indent it. - new_line += '\t' - elif current_buffer[:-1].split('\n')[-1].rstrip().endswith(':'): - # The last line ends with ":", autoindent the new line. - new_line += '\t' - - if new_line_pos == 0: - lines.append(new_line) - else: - lines.insert(new_line_pos, new_line) - self.input_buffer = '\n'.join(lines) - - - def _get_indent_string(self, string): - """ Return the string of whitespace that prefixes a line. Used to - add the right amount of indendation when creating a new line. - """ - string = string.replace('\t', ' '*4) - string = string.split('\n')[-1] - indent_chars = len(string) - len(string.lstrip()) - indent_string = '\t'*(indent_chars // 4) + \ - ' '*(indent_chars % 4) - - return indent_string - - diff --git a/IPython/deathrow/oldfrontend/prefilterfrontend.py b/IPython/deathrow/oldfrontend/prefilterfrontend.py deleted file mode 100644 index 81c043f..0000000 --- a/IPython/deathrow/oldfrontend/prefilterfrontend.py +++ /dev/null @@ -1,256 +0,0 @@ -""" -Frontend class that uses IPython0 to prefilter the inputs. - -Using the IPython0 mechanism gives us access to the magics. - -This is a transitory class, used here to do the transition between -ipython0 and ipython1. This class is meant to be short-lived as more -functionnality is abstracted out of ipython0 in reusable functions and -is added on the interpreter. This class can be a used to guide this -refactoring. -""" - -#------------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports -#------------------------------------------------------------------------------- -import sys -import pydoc -import os -import re -import __builtin__ - -from IPython.core.iplib import InteractiveShell -from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap - -from IPython.kernel.core.sync_traceback_trap import SyncTracebackTrap - -import IPython.utils.io - -from linefrontendbase import LineFrontEndBase, common_prefix - -#----------------------------------------------------------------------------- -# Utility functions -#----------------------------------------------------------------------------- - -def mk_system_call(system_call_function, command): - """ given a os.system replacement, and a leading string command, - returns a function that will execute the command with the given - argument string. - """ - def my_system_call(args): - system_call_function("%s %s" % (command, args)) - - my_system_call.__doc__ = "Calls %s" % command - return my_system_call - -#----------------------------------------------------------------------------- -# Frontend class using ipython0 to do the prefiltering. -#----------------------------------------------------------------------------- - -class PrefilterFrontEnd(LineFrontEndBase): - """ Class that uses ipython0 to do prefilter the input, do the - completion and the magics. - - The core trick is to use an ipython0 instance to prefilter the - input, and share the namespace between the interpreter instance used - to execute the statements and the ipython0 used for code - completion... - """ - - debug = False - - def __init__(self, ipython0=None, *args, **kwargs): - """ Parameters - ---------- - - ipython0: an optional ipython0 instance to use for command - prefiltering and completion. - """ - LineFrontEndBase.__init__(self, *args, **kwargs) - self.shell.output_trap = RedirectorOutputTrap( - out_callback=self.write, - err_callback=self.write, - ) - self.shell.traceback_trap = SyncTracebackTrap( - formatters=self.shell.traceback_trap.formatters, - ) - - # Start the ipython0 instance: - self.save_output_hooks() - if ipython0 is None: - # Instanciate an IPython0 InteractiveShell to be able to use the - # prefiltering. - # Suppress all key input, to avoid waiting - def my_rawinput(x=None): - return '\n' - old_rawinput = __builtin__.raw_input - __builtin__.raw_input = my_rawinput - ipython0 = InteractiveShell( - parent=None, user_ns=self.shell.user_ns, - user_global_ns=self.shell.user_global_ns - ) - __builtin__.raw_input = old_rawinput - self.ipython0 = ipython0 - # Set the pager: - self.ipython0.set_hook('show_in_pager', - lambda s, string: self.write("\n" + string)) - self.ipython0.write = self.write - self._ip = _ip = self.ipython0 - # Make sure the raw system call doesn't get called, as we don't - # have a stdin accessible. - self._ip.system = self.system_call - # XXX: Muck around with magics so that they work better - # in our environment - if not sys.platform.startswith('win'): - self.ipython0.magic_ls = mk_system_call(self.system_call, - 'ls -CF') - # And now clean up the mess created by ipython0 - self.release_output() - - - if not 'banner' in kwargs and self.banner is None: - self.banner = self.ipython0.banner - - # FIXME: __init__ and start should be two different steps - self.start() - - #-------------------------------------------------------------------------- - # FrontEndBase interface - #-------------------------------------------------------------------------- - - def show_traceback(self): - """ Use ipython0 to capture the last traceback and display it. - """ - # Don't do the capture; the except_hook has already done some - # modifications to the IO streams, if we store them, we'll be - # storing the wrong ones. - #self.capture_output() - self.ipython0.showtraceback(tb_offset=-1) - self.release_output() - - - def execute(self, python_string, raw_string=None): - if self.debug: - print 'Executing Python code:', repr(python_string) - self.capture_output() - LineFrontEndBase.execute(self, python_string, - raw_string=raw_string) - self.release_output() - - - def save_output_hooks(self): - """ Store all the output hooks we can think of, to be able to - restore them. - - We need to do this early, as starting the ipython0 instance will - screw ouput hooks. - """ - self.__old_cout_write = Term.cout.write - self.__old_cerr_write = Term.cerr.write - self.__old_stdout = sys.stdout - self.__old_stderr= sys.stderr - self.__old_help_output = pydoc.help.output - self.__old_display_hook = sys.displayhook - - - def capture_output(self): - """ Capture all the output mechanisms we can think of. - """ - self.save_output_hooks() - Term.cout.write = self.write - Term.cerr.write = self.write - sys.stdout = Term.cout - sys.stderr = Term.cerr - pydoc.help.output = self.shell.output_trap.out - - - def release_output(self): - """ Release all the different captures we have made. - """ - Term.cout.write = self.__old_cout_write - Term.cerr.write = self.__old_cerr_write - sys.stdout = self.__old_stdout - sys.stderr = self.__old_stderr - pydoc.help.output = self.__old_help_output - sys.displayhook = self.__old_display_hook - - - def complete(self, line): - # FIXME: This should be factored out in the linefrontendbase - # method. - word = self._get_completion_text(line) - completions = self.ipython0.complete(word) - # FIXME: The proper sort should be done in the complete method. - key = lambda x: x.replace('_', '') - completions.sort(key=key) - if completions: - prefix = common_prefix(completions) - line = line[:-len(word)] + prefix - return line, completions - - #-------------------------------------------------------------------------- - # LineFrontEndBase interface - #-------------------------------------------------------------------------- - - def prefilter_input(self, input_string): - """ Using IPython0 to prefilter the commands to turn them - in executable statements that are valid Python strings. - """ - input_string = LineFrontEndBase.prefilter_input(self, input_string) - filtered_lines = [] - # The IPython0 prefilters sometime produce output. We need to - # capture it. - self.capture_output() - self.last_result = dict(number=self.prompt_number) - - try: - try: - for line in input_string.split('\n'): - pf = self.ipython0.prefilter_manager.prefilter_lines - filtered_lines.append(pf(line, False).rstrip()) - except: - # XXX: probably not the right thing to do. - self.ipython0.showsyntaxerror() - self.after_execute() - finally: - self.release_output() - - # Clean up the trailing whitespace, to avoid indentation errors - filtered_string = '\n'.join(filtered_lines) - return filtered_string - - #-------------------------------------------------------------------------- - # PrefilterFrontEnd interface - #-------------------------------------------------------------------------- - - def system_call(self, command_string): - """ Allows for frontend to define their own system call, to be - able capture output and redirect input. - """ - return os.system(command_string) - - def do_exit(self): - """ Exit the shell, cleanup and save the history. - """ - self.ipython0.atexit_operations() - - def _get_completion_text(self, line): - """ Returns the text to be completed by breaking the line at specified - delimiters. - """ - # Break at: spaces, '=', all parentheses (except if balanced). - # FIXME2: In the future, we need to make the implementation similar to - # that in the 'pyreadline' module (modes/basemode.py) where we break at - # each delimiter and try to complete the residual line, until we get a - # successful list of completions. - expression = '\s|=|,|:|\((?!.*\))|\[(?!.*\])|\{(?!.*\})' - complete_sep = re.compile(expression) - text = complete_sep.split(line)[-1] - return text diff --git a/IPython/deathrow/oldfrontend/process/__init__.py b/IPython/deathrow/oldfrontend/process/__init__.py deleted file mode 100644 index af9be72..0000000 --- a/IPython/deathrow/oldfrontend/process/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -""" -Package for dealing for process execution in a callback environment, in a -portable way. - -killable_process.py is a wrapper of subprocess.Popen that allows the -subprocess and its children to be killed in a reliable way, including -under windows. - -winprocess.py is required by killable_process.py to kill processes under -windows. - -piped_process.py wraps process execution with callbacks to print output, -in a non-blocking way. It can be used to interact with a subprocess in eg -a GUI event loop. -""" - -from pipedprocess import PipedProcess - - diff --git a/IPython/deathrow/oldfrontend/process/killableprocess.py b/IPython/deathrow/oldfrontend/process/killableprocess.py deleted file mode 100644 index 2c5c380..0000000 --- a/IPython/deathrow/oldfrontend/process/killableprocess.py +++ /dev/null @@ -1,184 +0,0 @@ -# Addapted from killableprocess.py. -#______________________________________________________________________________ -# -# killableprocess - subprocesses which can be reliably killed -# -# Parts of this module are copied from the subprocess.py file contained -# in the Python distribution. -# -# Copyright (c) 2003-2004 by Peter Astrand <astrand@lysator.liu.se> -# -# Additions and modifications written by Benjamin Smedberg -# <benjamin@smedbergs.us> are Copyright (c) 2006 by the Mozilla Foundation -# <http://www.mozilla.org/> -# -# By obtaining, using, and/or copying this software and/or its -# associated documentation, you agree that you have read, understood, -# and will comply with the following terms and conditions: -# -# Permission to use, copy, modify, and distribute this software and -# its associated documentation for any purpose and without fee is -# hereby granted, provided that the above copyright notice appears in -# all copies, and that both that copyright notice and this permission -# notice appear in supporting documentation, and that the name of the -# author not be used in advertising or publicity pertaining to -# distribution of the software without specific, written prior -# permission. -# -# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR -# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, -# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION -# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -r"""killableprocess - Subprocesses which can be reliably killed - -This module is a subclass of the builtin "subprocess" module. It allows -processes that launch subprocesses to be reliably killed on Windows (via the Popen.kill() method. - -It also adds a timeout argument to Wait() for a limited period of time before -forcefully killing the process. - -Note: On Windows, this module requires Windows 2000 or higher (no support for -Windows 95, 98, or NT 4.0). It also requires ctypes, which is bundled with -Python 2.5+ or available from http://python.net/crew/theller/ctypes/ -""" - -import subprocess -from subprocess import PIPE -import sys -import os -import types - -try: - from subprocess import CalledProcessError -except ImportError: - # Python 2.4 doesn't implement CalledProcessError - class CalledProcessError(Exception): - """This exception is raised when a process run by check_call() returns - a non-zero exit status. The exit status will be stored in the - returncode attribute.""" - def __init__(self, returncode, cmd): - self.returncode = returncode - self.cmd = cmd - def __str__(self): - return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) - -mswindows = (sys.platform == "win32") - -skip = False - -if mswindows: - import platform - if platform.uname()[3] == '' or platform.uname()[3] > '6.0.6000': - # Killable process does not work under vista when starting for - # something else than cmd. - skip = True - else: - import winprocess -else: - import signal - -if not mswindows: - def DoNothing(*args): - pass - - -if skip: - Popen = subprocess.Popen -else: - class Popen(subprocess.Popen): - if not mswindows: - # Override __init__ to set a preexec_fn - def __init__(self, *args, **kwargs): - if len(args) >= 7: - raise Exception("Arguments preexec_fn and after must be passed by keyword.") - - real_preexec_fn = kwargs.pop("preexec_fn", None) - def setpgid_preexec_fn(): - os.setpgid(0, 0) - if real_preexec_fn: - apply(real_preexec_fn) - - kwargs['preexec_fn'] = setpgid_preexec_fn - - subprocess.Popen.__init__(self, *args, **kwargs) - - if mswindows: - def _execute_child(self, args, executable, preexec_fn, close_fds, - cwd, env, universal_newlines, startupinfo, - creationflags, shell, - p2cread, p2cwrite, - c2pread, c2pwrite, - errread, errwrite): - if not isinstance(args, types.StringTypes): - args = subprocess.list2cmdline(args) - - if startupinfo is None: - startupinfo = winprocess.STARTUPINFO() - - if None not in (p2cread, c2pwrite, errwrite): - startupinfo.dwFlags |= winprocess.STARTF_USESTDHANDLES - - startupinfo.hStdInput = int(p2cread) - startupinfo.hStdOutput = int(c2pwrite) - startupinfo.hStdError = int(errwrite) - if shell: - startupinfo.dwFlags |= winprocess.STARTF_USESHOWWINDOW - startupinfo.wShowWindow = winprocess.SW_HIDE - comspec = os.environ.get("COMSPEC", "cmd.exe") - args = comspec + " /c " + args - - # We create a new job for this process, so that we can kill - # the process and any sub-processes - self._job = winprocess.CreateJobObject() - - creationflags |= winprocess.CREATE_SUSPENDED - creationflags |= winprocess.CREATE_UNICODE_ENVIRONMENT - - hp, ht, pid, tid = winprocess.CreateProcess( - executable, args, - None, None, # No special security - 1, # Must inherit handles! - creationflags, - winprocess.EnvironmentBlock(env), - cwd, startupinfo) - - self._child_created = True - self._handle = hp - self._thread = ht - self.pid = pid - - # XXX: A try/except to fix UAC-related problems under - # Windows Vista, when reparenting jobs. - try: - winprocess.AssignProcessToJobObject(self._job, hp) - except WindowsError: - pass - winprocess.ResumeThread(ht) - - if p2cread is not None: - p2cread.Close() - if c2pwrite is not None: - c2pwrite.Close() - if errwrite is not None: - errwrite.Close() - - def kill(self, group=True): - """Kill the process. If group=True, all sub-processes will also be killed.""" - if mswindows: - if group: - winprocess.TerminateJobObject(self._job, 127) - else: - winprocess.TerminateProcess(self._handle, 127) - self.returncode = 127 - else: - if group: - os.killpg(self.pid, signal.SIGKILL) - else: - os.kill(self.pid, signal.SIGKILL) - self.returncode = -9 - - diff --git a/IPython/deathrow/oldfrontend/process/pipedprocess.py b/IPython/deathrow/oldfrontend/process/pipedprocess.py deleted file mode 100644 index ab160c1..0000000 --- a/IPython/deathrow/oldfrontend/process/pipedprocess.py +++ /dev/null @@ -1,74 +0,0 @@ -# encoding: utf-8 -""" -Object for encapsulating process execution by using callbacks for stdout, -stderr and stdin. -""" -__docformat__ = "restructuredtext en" - -#------------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports -#------------------------------------------------------------------------------- -from killableprocess import Popen, PIPE -from threading import Thread -from time import sleep -import os - -class PipedProcess(Thread): - """ Class that encapsulates process execution by using callbacks for - stdout, stderr and stdin, and providing a reliable way of - killing it. - """ - - def __init__(self, command_string, out_callback, - end_callback=None,): - """ command_string: the command line executed to start the - process. - - out_callback: the python callable called on stdout/stderr. - - end_callback: an optional callable called when the process - finishes. - - These callbacks are called from a different thread as the - thread from which is started. - """ - self.command_string = command_string - self.out_callback = out_callback - self.end_callback = end_callback - Thread.__init__(self) - - - def run(self): - """ Start the process and hook up the callbacks. - """ - env = os.environ - env['TERM'] = 'xterm' - process = Popen(self.command_string + ' 2>&1', shell=True, - env=env, - universal_newlines=True, - stdout=PIPE, stdin=PIPE, ) - self.process = process - while True: - out_char = process.stdout.read(1) - if out_char == '': - if process.poll() is not None: - # The process has finished - break - else: - # The process is not giving any interesting - # output. No use polling it immediatly. - sleep(0.1) - else: - self.out_callback(out_char) - - if self.end_callback is not None: - self.end_callback() - - diff --git a/IPython/deathrow/oldfrontend/process/winprocess.py b/IPython/deathrow/oldfrontend/process/winprocess.py deleted file mode 100644 index 18f778d..0000000 --- a/IPython/deathrow/oldfrontend/process/winprocess.py +++ /dev/null @@ -1,264 +0,0 @@ -# A module to expose various thread/process/job related structures and -# methods from kernel32 -# -# The MIT License -# -# Copyright (c) 2006 the Mozilla Foundation <http://www.mozilla.org> -# -# Permission is hereby granted, free of charge, to any person obtaining a -# copy of this software and associated documentation files (the "Software"), -# to deal in the Software without restriction, including without limitation -# the rights to use, copy, modify, merge, publish, distribute, sublicense, -# and/or sell copies of the Software, and to permit persons to whom the -# Software is furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -# DEALINGS IN THE SOFTWARE. - -from ctypes import c_void_p, POINTER, sizeof, Structure, windll, WinError, WINFUNCTYPE -from ctypes.wintypes import BOOL, BYTE, DWORD, HANDLE, LPCWSTR, LPWSTR, UINT, WORD - -LPVOID = c_void_p -LPBYTE = POINTER(BYTE) -LPDWORD = POINTER(DWORD) - -SW_HIDE = 0 - -def ErrCheckBool(result, func, args): - """errcheck function for Windows functions that return a BOOL True - on success""" - if not result: - raise WinError() - return args - -# CloseHandle() - -CloseHandleProto = WINFUNCTYPE(BOOL, HANDLE) -CloseHandle = CloseHandleProto(("CloseHandle", windll.kernel32)) -CloseHandle.errcheck = ErrCheckBool - -# AutoHANDLE - -class AutoHANDLE(HANDLE): - """Subclass of HANDLE which will call CloseHandle() on deletion.""" - def Close(self): - if self.value: - CloseHandle(self) - self.value = 0 - - def __del__(self): - self.Close() - - def __int__(self): - return self.value - -def ErrCheckHandle(result, func, args): - """errcheck function for Windows functions that return a HANDLE.""" - if not result: - raise WinError() - return AutoHANDLE(result) - -# PROCESS_INFORMATION structure - -class PROCESS_INFORMATION(Structure): - _fields_ = [("hProcess", HANDLE), - ("hThread", HANDLE), - ("dwProcessID", DWORD), - ("dwThreadID", DWORD)] - - def __init__(self): - Structure.__init__(self) - - self.cb = sizeof(self) - -LPPROCESS_INFORMATION = POINTER(PROCESS_INFORMATION) - -# STARTUPINFO structure - -class STARTUPINFO(Structure): - _fields_ = [("cb", DWORD), - ("lpReserved", LPWSTR), - ("lpDesktop", LPWSTR), - ("lpTitle", LPWSTR), - ("dwX", DWORD), - ("dwY", DWORD), - ("dwXSize", DWORD), - ("dwYSize", DWORD), - ("dwXCountChars", DWORD), - ("dwYCountChars", DWORD), - ("dwFillAttribute", DWORD), - ("dwFlags", DWORD), - ("wShowWindow", WORD), - ("cbReserved2", WORD), - ("lpReserved2", LPBYTE), - ("hStdInput", HANDLE), - ("hStdOutput", HANDLE), - ("hStdError", HANDLE) - ] -LPSTARTUPINFO = POINTER(STARTUPINFO) - -STARTF_USESHOWWINDOW = 0x01 -STARTF_USESIZE = 0x02 -STARTF_USEPOSITION = 0x04 -STARTF_USECOUNTCHARS = 0x08 -STARTF_USEFILLATTRIBUTE = 0x10 -STARTF_RUNFULLSCREEN = 0x20 -STARTF_FORCEONFEEDBACK = 0x40 -STARTF_FORCEOFFFEEDBACK = 0x80 -STARTF_USESTDHANDLES = 0x100 - -# EnvironmentBlock - -class EnvironmentBlock: - """An object which can be passed as the lpEnv parameter of CreateProcess. - It is initialized with a dictionary.""" - - def __init__(self, dict): - if not dict: - self._as_parameter_ = None - else: - values = ["%s=%s" % (key, value) - for (key, value) in dict.iteritems()] - values.append("") - self._as_parameter_ = LPCWSTR("\0".join(values)) - -# CreateProcess() - -CreateProcessProto = WINFUNCTYPE(BOOL, # Return type - LPCWSTR, # lpApplicationName - LPWSTR, # lpCommandLine - LPVOID, # lpProcessAttributes - LPVOID, # lpThreadAttributes - BOOL, # bInheritHandles - DWORD, # dwCreationFlags - LPVOID, # lpEnvironment - LPCWSTR, # lpCurrentDirectory - LPSTARTUPINFO, # lpStartupInfo - LPPROCESS_INFORMATION # lpProcessInformation - ) - -CreateProcessFlags = ((1, "lpApplicationName", None), - (1, "lpCommandLine"), - (1, "lpProcessAttributes", None), - (1, "lpThreadAttributes", None), - (1, "bInheritHandles", True), - (1, "dwCreationFlags", 0), - (1, "lpEnvironment", None), - (1, "lpCurrentDirectory", None), - (1, "lpStartupInfo"), - (2, "lpProcessInformation")) - -def ErrCheckCreateProcess(result, func, args): - ErrCheckBool(result, func, args) - # return a tuple (hProcess, hThread, dwProcessID, dwThreadID) - pi = args[9] - return AutoHANDLE(pi.hProcess), AutoHANDLE(pi.hThread), pi.dwProcessID, pi.dwThreadID - -CreateProcess = CreateProcessProto(("CreateProcessW", windll.kernel32), - CreateProcessFlags) -CreateProcess.errcheck = ErrCheckCreateProcess - -CREATE_BREAKAWAY_FROM_JOB = 0x01000000 -CREATE_DEFAULT_ERROR_MODE = 0x04000000 -CREATE_NEW_CONSOLE = 0x00000010 -CREATE_NEW_PROCESS_GROUP = 0x00000200 -CREATE_NO_WINDOW = 0x08000000 -CREATE_SUSPENDED = 0x00000004 -CREATE_UNICODE_ENVIRONMENT = 0x00000400 -DEBUG_ONLY_THIS_PROCESS = 0x00000002 -DEBUG_PROCESS = 0x00000001 -DETACHED_PROCESS = 0x00000008 - -# CreateJobObject() - -CreateJobObjectProto = WINFUNCTYPE(HANDLE, # Return type - LPVOID, # lpJobAttributes - LPCWSTR # lpName - ) - -CreateJobObjectFlags = ((1, "lpJobAttributes", None), - (1, "lpName", None)) - -CreateJobObject = CreateJobObjectProto(("CreateJobObjectW", windll.kernel32), - CreateJobObjectFlags) -CreateJobObject.errcheck = ErrCheckHandle - -# AssignProcessToJobObject() - -AssignProcessToJobObjectProto = WINFUNCTYPE(BOOL, # Return type - HANDLE, # hJob - HANDLE # hProcess - ) -AssignProcessToJobObjectFlags = ((1, "hJob"), - (1, "hProcess")) -AssignProcessToJobObject = AssignProcessToJobObjectProto( - ("AssignProcessToJobObject", windll.kernel32), - AssignProcessToJobObjectFlags) -AssignProcessToJobObject.errcheck = ErrCheckBool - -# ResumeThread() - -def ErrCheckResumeThread(result, func, args): - if result == -1: - raise WinError() - - return args - -ResumeThreadProto = WINFUNCTYPE(DWORD, # Return type - HANDLE # hThread - ) -ResumeThreadFlags = ((1, "hThread"),) -ResumeThread = ResumeThreadProto(("ResumeThread", windll.kernel32), - ResumeThreadFlags) -ResumeThread.errcheck = ErrCheckResumeThread - -# TerminateJobObject() - -TerminateJobObjectProto = WINFUNCTYPE(BOOL, # Return type - HANDLE, # hJob - UINT # uExitCode - ) -TerminateJobObjectFlags = ((1, "hJob"), - (1, "uExitCode", 127)) -TerminateJobObject = TerminateJobObjectProto( - ("TerminateJobObject", windll.kernel32), - TerminateJobObjectFlags) -TerminateJobObject.errcheck = ErrCheckBool - -# WaitForSingleObject() - -WaitForSingleObjectProto = WINFUNCTYPE(DWORD, # Return type - HANDLE, # hHandle - DWORD, # dwMilliseconds - ) -WaitForSingleObjectFlags = ((1, "hHandle"), - (1, "dwMilliseconds", -1)) -WaitForSingleObject = WaitForSingleObjectProto( - ("WaitForSingleObject", windll.kernel32), - WaitForSingleObjectFlags) - -INFINITE = -1 -WAIT_TIMEOUT = 0x0102 -WAIT_OBJECT_0 = 0x0 -WAIT_ABANDONED = 0x0080 - -# GetExitCodeProcess() - -GetExitCodeProcessProto = WINFUNCTYPE(BOOL, # Return type - HANDLE, # hProcess - LPDWORD, # lpExitCode - ) -GetExitCodeProcessFlags = ((1, "hProcess"), - (2, "lpExitCode")) -GetExitCodeProcess = GetExitCodeProcessProto( - ("GetExitCodeProcess", windll.kernel32), - GetExitCodeProcessFlags) -GetExitCodeProcess.errcheck = ErrCheckBool diff --git a/IPython/deathrow/oldfrontend/tests/test_asyncfrontendbase.py b/IPython/deathrow/oldfrontend/tests/test_asyncfrontendbase.py deleted file mode 100644 index 0b7e486..0000000 --- a/IPython/deathrow/oldfrontend/tests/test_asyncfrontendbase.py +++ /dev/null @@ -1,106 +0,0 @@ -# encoding: utf-8 -"""This file contains unittests for the asyncfrontendbase module.""" - -#--------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#--------------------------------------------------------------------------- - -#--------------------------------------------------------------------------- -# Imports -#--------------------------------------------------------------------------- - -from twisted.trial import unittest - -from IPython.frontend.asyncfrontendbase import AsyncFrontEndBase -from IPython.frontend import frontendbase -from IPython.kernel.engineservice import EngineService -from IPython.testing.parametric import Parametric, parametric - -#----------------------------------------------------------------------------- -# Classes and functions -#----------------------------------------------------------------------------- - -class FrontEndCallbackChecker(AsyncFrontEndBase): - """FrontEndBase subclass for checking callbacks""" - def __init__(self, engine=None, history=None): - super(FrontEndCallbackChecker, self).__init__(engine=engine, - history=history) - self.updateCalled = False - self.renderResultCalled = False - self.renderErrorCalled = False - - def update_cell_prompt(self, result, blockID=None): - self.updateCalled = True - return result - - def render_result(self, result): - self.renderResultCalled = True - return result - - def render_error(self, failure): - self.renderErrorCalled = True - return failure - - -class TestAsyncFrontendBase(unittest.TestCase): - def setUp(self): - """Setup the EngineService and FrontEndBase""" - - self.fb = FrontEndCallbackChecker(engine=EngineService()) - - def test_implements_IFrontEnd(self): - self.assert_(frontendbase.IFrontEnd.implementedBy( - AsyncFrontEndBase)) - - def test_is_complete_returns_False_for_incomplete_block(self): - block = """def test(a):""" - self.assert_(self.fb.is_complete(block) == False) - - def test_is_complete_returns_True_for_complete_block(self): - block = """def test(a): pass""" - self.assert_(self.fb.is_complete(block)) - block = """a=3""" - self.assert_(self.fb.is_complete(block)) - - def test_blockID_added_to_result(self): - block = """3+3""" - d = self.fb.execute(block, blockID='TEST_ID') - d.addCallback(lambda r: self.assert_(r['blockID']=='TEST_ID')) - return d - - def test_blockID_added_to_failure(self): - block = "raise Exception()" - d = self.fb.execute(block,blockID='TEST_ID') - d.addErrback(lambda f: self.assert_(f.blockID=='TEST_ID')) - return d - - def test_callbacks_added_to_execute(self): - d = self.fb.execute("10+10") - d.addCallback(lambda r: self.assert_(self.fb.updateCalled and self.fb.renderResultCalled)) - return d - - def test_error_callback_added_to_execute(self): - """Test that render_error called on execution error.""" - - d = self.fb.execute("raise Exception()") - d.addErrback(lambda f: self.assert_(self.fb.renderErrorCalled)) - return d - - def test_history_returns_expected_block(self): - """Make sure history browsing doesn't fail.""" - - blocks = ["a=1","a=2","a=3"] - d = self.fb.execute(blocks[0]) - d.addCallback(lambda _: self.fb.execute(blocks[1])) - d.addCallback(lambda _: self.fb.execute(blocks[2])) - d.addCallback(lambda _: self.assert_(self.fb.get_history_previous("")==blocks[-2])) - d.addCallback(lambda _: self.assert_(self.fb.get_history_previous("")==blocks[-3])) - d.addCallback(lambda _: self.assert_(self.fb.get_history_next()==blocks[-2])) - return d - - def test_history_returns_none_at_startup(self): - self.assert_(self.fb.get_history_previous("")==None) - self.assert_(self.fb.get_history_next()==None) diff --git a/IPython/deathrow/oldfrontend/tests/test_frontendbase.py b/IPython/deathrow/oldfrontend/tests/test_frontendbase.py deleted file mode 100644 index a78e084..0000000 --- a/IPython/deathrow/oldfrontend/tests/test_frontendbase.py +++ /dev/null @@ -1,32 +0,0 @@ -# encoding: utf-8 -""" -Test the basic functionality of frontendbase. -""" - -__docformat__ = "restructuredtext en" - -#------------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is -# in the file COPYING, distributed as part of this software. -#------------------------------------------------------------------------------- - -from IPython.frontend.frontendbase import FrontEndBase - -def test_iscomplete(): - """ Check that is_complete works. - """ - f = FrontEndBase() - assert f.is_complete('(a + a)') - assert not f.is_complete('(a + a') - assert f.is_complete('1') - assert not f.is_complete('1 + ') - assert not f.is_complete('1 + \n\n') - assert f.is_complete('if True:\n print 1\n') - assert not f.is_complete('if True:\n print 1') - assert f.is_complete('def f():\n print 1\n') - -if __name__ == '__main__': - test_iscomplete() - diff --git a/IPython/deathrow/oldfrontend/tests/test_linefrontend.py b/IPython/deathrow/oldfrontend/tests/test_linefrontend.py deleted file mode 100644 index 78bc58c..0000000 --- a/IPython/deathrow/oldfrontend/tests/test_linefrontend.py +++ /dev/null @@ -1,37 +0,0 @@ -# encoding: utf-8 -""" -Test the LineFrontEnd -""" - -__docformat__ = "restructuredtext en" - -#------------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is -# in the file COPYING, distributed as part of this software. -#------------------------------------------------------------------------------- - -from IPython.frontend.linefrontendbase import LineFrontEndBase -from copy import deepcopy -import nose.tools as nt - -class ConcreteLineFrontEnd(LineFrontEndBase): - """ A concrete class to test the LineFrontEndBase. - """ - def capture_output(self): - pass - - def release_output(self): - pass - - -def test_is_complete(): - """ Tests line completion heuristic. - """ - frontend = ConcreteLineFrontEnd() - yield nt.assert_true, not frontend.is_complete('for x in \\') - yield nt.assert_true, not frontend.is_complete('for x in (1, ):') - yield nt.assert_true, frontend.is_complete('for x in (1, ):\n pass') - - diff --git a/IPython/deathrow/oldfrontend/tests/test_prefilterfrontend.py b/IPython/deathrow/oldfrontend/tests/test_prefilterfrontend.py deleted file mode 100644 index d1353ad..0000000 --- a/IPython/deathrow/oldfrontend/tests/test_prefilterfrontend.py +++ /dev/null @@ -1,268 +0,0 @@ -# encoding: utf-8 -""" -Test process execution and IO redirection. -""" - -__docformat__ = "restructuredtext en" - -#------------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is -# in the file COPYING, distributed as part of this software. -#------------------------------------------------------------------------------- - -from copy import copy, deepcopy -from cStringIO import StringIO -import string -import sys - -from nose.tools import assert_equal - -from IPython.frontend.prefilterfrontend import PrefilterFrontEnd -from IPython.testing.globalipapp import get_ipython - -#----------------------------------------------------------------------------- -# Support utilities -#----------------------------------------------------------------------------- - -class TestPrefilterFrontEnd(PrefilterFrontEnd): - - input_prompt_template = string.Template('') - output_prompt_template = string.Template('') - banner = '' - - def __init__(self): - self.out = StringIO() - PrefilterFrontEnd.__init__(self) - # Some more code for isolation (yeah, crazy) - self._on_enter() - self.out.flush() - self.out.reset() - self.out.truncate() - - def write(self, string, *args, **kwargs): - self.out.write(string) - - def _on_enter(self): - self.input_buffer += '\n' - PrefilterFrontEnd._on_enter(self) - - -def isolate_ipython0(func): - """ Decorator to isolate execution that involves an iptyhon0. - - Notes - ----- - - Apply only to functions with no arguments. Nose skips functions - with arguments. - """ - def my_func(): - ip0 = get_ipython() - if ip0 is None: - return func() - # We have a real ipython running... - user_ns = ip0.user_ns - user_global_ns = ip0.user_global_ns - - # Previously the isolation was attempted with a deep copy of the user - # dicts, but we found cases where this didn't work correctly. I'm not - # quite sure why, but basically it did damage the user namespace, such - # that later tests stopped working correctly. Instead we use a simpler - # approach, just computing the list of added keys to the namespace and - # eliminating those afterwards. Existing keys that may have been - # modified remain modified. So far this has proven to be robust. - - # Compute set of old local/global keys - old_locals = set(user_ns.keys()) - old_globals = set(user_global_ns.keys()) - try: - out = func() - finally: - # Find new keys, and if any, remove them - new_locals = set(user_ns.keys()) - old_locals - new_globals = set(user_global_ns.keys()) - old_globals - for k in new_locals: - del user_ns[k] - for k in new_globals: - del user_global_ns[k] - return out - - my_func.__name__ = func.__name__ - return my_func - -#----------------------------------------------------------------------------- -# Tests -#----------------------------------------------------------------------------- - -@isolate_ipython0 -def test_execution(): - """ Test execution of a command. - """ - f = TestPrefilterFrontEnd() - f.input_buffer = 'print(1)' - f._on_enter() - out_value = f.out.getvalue() - assert_equal(out_value, '1\n') - - -@isolate_ipython0 -def test_multiline(): - """ Test execution of a multiline command. - """ - f = TestPrefilterFrontEnd() - f.input_buffer = 'if True:' - f._on_enter() - f.input_buffer += 'print 1' - f._on_enter() - out_value = f.out.getvalue() - yield assert_equal, out_value, '' - f._on_enter() - out_value = f.out.getvalue() - yield assert_equal, out_value, '1\n' - f = TestPrefilterFrontEnd() - f.input_buffer='(1 +' - f._on_enter() - f.input_buffer += '0)' - f._on_enter() - out_value = f.out.getvalue() - yield assert_equal, out_value, '' - f._on_enter() - out_value = f.out.getvalue() - yield assert_equal, out_value, '1\n' - - -@isolate_ipython0 -def test_capture(): - """ Test the capture of output in different channels. - """ - # Test on the OS-level stdout, stderr. - f = TestPrefilterFrontEnd() - f.input_buffer = \ - 'import os; out=os.fdopen(1, "w"); out.write("1") ; out.flush()' - f._on_enter() - out_value = f.out.getvalue() - yield assert_equal, out_value, '1' - f = TestPrefilterFrontEnd() - f.input_buffer = \ - 'import os; out=os.fdopen(2, "w"); out.write("1") ; out.flush()' - f._on_enter() - out_value = f.out.getvalue() - yield assert_equal, out_value, '1' - - -@isolate_ipython0 -def test_magic(): - """ Test the magic expansion and history. - - This test is fairly fragile and will break when magics change. - """ - f = TestPrefilterFrontEnd() - # Before checking the interactive namespace, make sure it's clear (it can - # otherwise pick up things stored in the user's local db) - f.input_buffer += '%reset -f' - f._on_enter() - f.complete_current_input() - # Now, run the %who magic and check output - f.input_buffer += '%who' - f._on_enter() - out_value = f.out.getvalue() - assert_equal(out_value, 'Interactive namespace is empty.\n') - - -@isolate_ipython0 -def test_help(): - """ Test object inspection. - """ - f = TestPrefilterFrontEnd() - f.input_buffer += "def f():" - f._on_enter() - f.input_buffer += "'foobar'" - f._on_enter() - f.input_buffer += "pass" - f._on_enter() - f._on_enter() - f.input_buffer += "f?" - f._on_enter() - assert 'traceback' not in f.last_result - ## XXX: ipython doctest magic breaks this. I have no clue why - #out_value = f.out.getvalue() - #assert out_value.split()[-1] == 'foobar' - - -@isolate_ipython0 -def test_completion_simple(): - """ Test command-line completion on trivial examples. - """ - f = TestPrefilterFrontEnd() - f.input_buffer = 'zzza = 1' - f._on_enter() - f.input_buffer = 'zzzb = 2' - f._on_enter() - f.input_buffer = 'zz' - f.complete_current_input() - out_value = f.out.getvalue() - yield assert_equal, out_value, '\nzzza zzzb ' - yield assert_equal, f.input_buffer, 'zzz' - - -@isolate_ipython0 -def test_completion_parenthesis(): - """ Test command-line completion when a parenthesis is open. - """ - f = TestPrefilterFrontEnd() - f.input_buffer = 'zzza = 1' - f._on_enter() - f.input_buffer = 'zzzb = 2' - f._on_enter() - f.input_buffer = 'map(zz' - f.complete_current_input() - out_value = f.out.getvalue() - yield assert_equal, out_value, '\nzzza zzzb ' - yield assert_equal, f.input_buffer, 'map(zzz' - - -@isolate_ipython0 -def test_completion_indexing(): - """ Test command-line completion when indexing on objects. - """ - f = TestPrefilterFrontEnd() - f.input_buffer = 'a = [0]' - f._on_enter() - f.input_buffer = 'a[0].' - f.complete_current_input() - - if sys.version_info[:2] >= (2,6): - # In Python 2.6, ints picked up a few non __ methods, so now there are - # no completions. - assert_equal(f.input_buffer, 'a[0].') - else: - # Right answer for 2.4/2.5 - assert_equal(f.input_buffer, 'a[0].__') - - -@isolate_ipython0 -def test_completion_equal(): - """ Test command-line completion when the delimiter is "=", not " ". - """ - f = TestPrefilterFrontEnd() - f.input_buffer = 'a=1.' - f.complete_current_input() - if sys.version_info[:2] >= (2,6): - # In Python 2.6, ints picked up a few non __ methods, so now there are - # no completions. - assert_equal(f.input_buffer, 'a=1.') - else: - # Right answer for 2.4/2.5 - assert_equal(f.input_buffer, 'a=1.__') - - -if __name__ == '__main__': - test_magic() - test_help() - test_execution() - test_multiline() - test_capture() - test_completion_simple() - test_completion_complex() diff --git a/IPython/deathrow/oldfrontend/tests/test_process.py b/IPython/deathrow/oldfrontend/tests/test_process.py deleted file mode 100644 index 9e43487..0000000 --- a/IPython/deathrow/oldfrontend/tests/test_process.py +++ /dev/null @@ -1,68 +0,0 @@ -# encoding: utf-8 -""" -Test process execution and IO redirection. -""" - -__docformat__ = "restructuredtext en" - -#----------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is -# in the file COPYING, distributed as part of this software. -#----------------------------------------------------------------------------- - -from cStringIO import StringIO -from time import sleep -import sys - -from IPython.frontend.process import PipedProcess -from IPython.testing import decorators as dec - - -def test_capture_out(): - """ A simple test to see if we can execute a process and get the output. - """ - s = StringIO() - p = PipedProcess('echo 1', out_callback=s.write, ) - p.start() - p.join() - result = s.getvalue().rstrip() - assert result == '1' - - -def test_io(): - """ Checks that we can send characters on stdin to the process. - """ - s = StringIO() - p = PipedProcess(sys.executable + ' -c "a = raw_input(); print a"', - out_callback=s.write, ) - p.start() - test_string = '12345\n' - while not hasattr(p, 'process'): - sleep(0.1) - p.process.stdin.write(test_string) - p.join() - result = s.getvalue() - assert result == test_string - - -@dec.skip_win32 -def test_kill(): - """ Check that we can kill a process, and its subprocess. - """ - s = StringIO() - p = PipedProcess(sys.executable + ' -c "a = raw_input();"', - out_callback=s.write, ) - p.start() - while not hasattr(p, 'process'): - sleep(0.1) - p.process.kill() - assert p.process.poll() is not None - - -if __name__ == '__main__': - test_capture_out() - test_io() - test_kill() - diff --git a/IPython/deathrow/oldfrontend/wx/console_widget.py b/IPython/deathrow/oldfrontend/wx/console_widget.py deleted file mode 100644 index e4ec901..0000000 --- a/IPython/deathrow/oldfrontend/wx/console_widget.py +++ /dev/null @@ -1,625 +0,0 @@ -# encoding: utf-8 -""" -A Wx widget to act as a console and input commands. - -This widget deals with prompts and provides an edit buffer -restricted to after the last prompt. -""" - -__docformat__ = "restructuredtext en" - -#------------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is -# in the file COPYING, distributed as part of this software. -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports -#------------------------------------------------------------------------------- - -import wx -import wx.stc as stc - -from wx.py import editwindow -import time -import sys -import string - -LINESEP = '\n' -if sys.platform == 'win32': - LINESEP = '\n\r' - -import re - -# FIXME: Need to provide an API for non user-generated display on the -# screen: this should not be editable by the user. -#------------------------------------------------------------------------------- -# Constants -#------------------------------------------------------------------------------- -_COMPLETE_BUFFER_MARKER = 31 -_ERROR_MARKER = 30 -_INPUT_MARKER = 29 - -_DEFAULT_SIZE = 10 -if sys.platform == 'darwin': - _DEFAULT_SIZE = 12 - -_DEFAULT_STYLE = { - #background definition - 'default' : 'size:%d' % _DEFAULT_SIZE, - 'bracegood' : 'fore:#00AA00,back:#000000,bold', - 'bracebad' : 'fore:#FF0000,back:#000000,bold', - - # Edge column: a number of None - 'edge_column' : -1, - - # properties for the various Python lexer styles - 'comment' : 'fore:#007F00', - 'number' : 'fore:#007F7F', - 'string' : 'fore:#7F007F,italic', - 'char' : 'fore:#7F007F,italic', - 'keyword' : 'fore:#00007F,bold', - 'triple' : 'fore:#7F0000', - 'tripledouble' : 'fore:#7F0000', - 'class' : 'fore:#0000FF,bold,underline', - 'def' : 'fore:#007F7F,bold', - 'operator' : 'bold', - - # Default colors - 'trace' : '#FAFAF1', # Nice green - 'stdout' : '#FDFFD3', # Nice yellow - 'stderr' : '#FFF1F1', # Nice red - - # Default scintilla settings - 'antialiasing' : True, - 'carret_color' : 'BLACK', - 'background_color' :'WHITE', - - #prompt definition - 'prompt_in1' : \ - '\n\x01\x1b[0;34m\x02In [\x01\x1b[1;34m\x02$number\x01\x1b[0;34m\x02]: \x01\x1b[0m\x02', - - 'prompt_out': \ - '\x01\x1b[0;31m\x02Out[\x01\x1b[1;31m\x02$number\x01\x1b[0;31m\x02]: \x01\x1b[0m\x02', - } - -# new style numbers -_STDOUT_STYLE = 15 -_STDERR_STYLE = 16 -_TRACE_STYLE = 17 - - -# system colors -#SYS_COLOUR_BACKGROUND = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND) - -# Translation table from ANSI escape sequences to color. -ANSI_STYLES = {'0;30': [0, 'BLACK'], '0;31': [1, 'RED'], - '0;32': [2, 'GREEN'], '0;33': [3, 'BROWN'], - '0;34': [4, 'BLUE'], '0;35': [5, 'PURPLE'], - '0;36': [6, 'CYAN'], '0;37': [7, 'LIGHT GREY'], - '1;30': [8, 'DARK GREY'], '1;31': [9, 'RED'], - '1;32': [10, 'SEA GREEN'], '1;33': [11, 'YELLOW'], - '1;34': [12, 'LIGHT BLUE'], '1;35': - [13, 'MEDIUM VIOLET RED'], - '1;36': [14, 'LIGHT STEEL BLUE'], '1;37': [15, 'YELLOW']} - -# XXX: Maybe one day we should factor this code with coloransi. Right now -# coloransi is hard to reuse and makes our code more complex. - -#we define platform specific fonts -if wx.Platform == '__WXMSW__': - FACES = { 'times': 'Times New Roman', - 'mono' : 'Courier New', - 'helv' : 'Arial', - 'other': 'Comic Sans MS', - 'size' : 10, - 'size2': 8, - } -elif wx.Platform == '__WXMAC__': - FACES = { 'times': 'Times New Roman', - 'mono' : 'Monaco', - 'helv' : 'Arial', - 'other': 'Comic Sans MS', - 'size' : 10, - 'size2': 8, - } -else: - FACES = { 'times': 'Times', - 'mono' : 'Courier', - 'helv' : 'Helvetica', - 'other': 'new century schoolbook', - 'size' : 10, - 'size2': 8, - } - - -#----------------------------------------------------------------------------- -# The console widget class -#----------------------------------------------------------------------------- - -class ConsoleWidget(editwindow.EditWindow): - """ Specialized styled text control view for console-like workflow. - - This widget is mainly interested in dealing with the prompt and - keeping the cursor inside the editing line. - """ - - # This is where the title captured from the ANSI escape sequences are - # stored. - title = 'Console' - - # Last prompt printed - last_prompt = '' - - # The buffer being edited. - def _set_input_buffer(self, string): - self.SetSelection(self.current_prompt_pos, self.GetLength()) - self.ReplaceSelection(string) - self.GotoPos(self.GetLength()) - - def _get_input_buffer(self): - """ Returns the text in current edit buffer. - """ - input_buffer = self.GetTextRange(self.current_prompt_pos, - self.GetLength()) - input_buffer = input_buffer.replace(LINESEP, '\n') - return input_buffer - - input_buffer = property(_get_input_buffer, _set_input_buffer) - - style = _DEFAULT_STYLE.copy() - - # Translation table from ANSI escape sequences to color. Override - # this to specify your colors. - ANSI_STYLES = ANSI_STYLES.copy() - - # Font faces - faces = FACES.copy() - - # Store the last time a refresh was done - _last_refresh_time = 0 - - #-------------------------------------------------------------------------- - # Public API - #-------------------------------------------------------------------------- - - def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, - size=wx.DefaultSize, style=wx.WANTS_CHARS, ): - editwindow.EditWindow.__init__(self, parent, id, pos, size, style) - self.configure_scintilla() - # Track if 'enter' key as ever been processed - # This variable will only be reallowed until key goes up - self.enter_catched = False - self.current_prompt_pos = 0 - - self.Bind(wx.EVT_KEY_DOWN, self._on_key_down) - self.Bind(wx.EVT_KEY_UP, self._on_key_up) - - - def write(self, text, refresh=True): - """ Write given text to buffer, while translating the ansi escape - sequences. - """ - # XXX: do not put print statements to sys.stdout/sys.stderr in - # this method, the print statements will call this method, as - # you will end up with an infinit loop - title = self.title_pat.split(text) - if len(title)>1: - self.title = title[-2] - - text = self.title_pat.sub('', text) - segments = self.color_pat.split(text) - segment = segments.pop(0) - self.GotoPos(self.GetLength()) - self.StartStyling(self.GetLength(), 0xFF) - try: - self.AppendText(segment) - except UnicodeDecodeError: - # XXX: Do I really want to skip the exception? - pass - - if segments: - for ansi_tag, text in zip(segments[::2], segments[1::2]): - self.StartStyling(self.GetLength(), 0xFF) - try: - self.AppendText(text) - except UnicodeDecodeError: - # XXX: Do I really want to skip the exception? - pass - - if ansi_tag not in self.ANSI_STYLES: - style = 0 - else: - style = self.ANSI_STYLES[ansi_tag][0] - - self.SetStyling(len(text), style) - - self.GotoPos(self.GetLength()) - if refresh: - current_time = time.time() - if current_time - self._last_refresh_time > 0.03: - if sys.platform == 'win32': - wx.SafeYield() - else: - wx.Yield() - # self.ProcessEvent(wx.PaintEvent()) - self._last_refresh_time = current_time - - - def new_prompt(self, prompt): - """ Prints a prompt at start of line, and move the start of the - current block there. - - The prompt can be given with ascii escape sequences. - """ - self.write(prompt, refresh=False) - # now we update our cursor giving end of prompt - self.current_prompt_pos = self.GetLength() - self.current_prompt_line = self.GetCurrentLine() - self.EnsureCaretVisible() - self.last_prompt = prompt - - - def continuation_prompt(self): - """ Returns the current continuation prompt. - We need to implement this method here to deal with the - ascii escape sequences cleaning up. - """ - # ASCII-less prompt - ascii_less = ''.join(self.color_pat.split(self.last_prompt)[2::2]) - return "."*(len(ascii_less)-2) + ': ' - - - def scroll_to_bottom(self): - maxrange = self.GetScrollRange(wx.VERTICAL) - self.ScrollLines(maxrange) - - - def pop_completion(self, possibilities, offset=0): - """ Pops up an autocompletion menu. Offset is the offset - in characters of the position at which the menu should - appear, relativ to the cursor. - """ - self.AutoCompSetIgnoreCase(False) - self.AutoCompSetAutoHide(False) - self.AutoCompSetMaxHeight(len(possibilities)) - self.AutoCompShow(offset, " ".join(possibilities)) - - - def get_line_width(self): - """ Return the width of the line in characters. - """ - return self.GetSize()[0]/self.GetCharWidth() - - - def configure_scintilla(self): - """ Set up all the styling option of the embedded scintilla - widget. - """ - p = self.style.copy() - - # Marker for complete buffer. - self.MarkerDefine(_COMPLETE_BUFFER_MARKER, stc.STC_MARK_BACKGROUND, - background=p['trace']) - - # Marker for current input buffer. - self.MarkerDefine(_INPUT_MARKER, stc.STC_MARK_BACKGROUND, - background=p['stdout']) - # Marker for tracebacks. - self.MarkerDefine(_ERROR_MARKER, stc.STC_MARK_BACKGROUND, - background=p['stderr']) - - self.SetEOLMode(stc.STC_EOL_LF) - - # Ctrl"+" or Ctrl "-" can be used to zoomin/zoomout the text inside - # the widget - self.CmdKeyAssign(ord('+'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN) - self.CmdKeyAssign(ord('-'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT) - # Also allow Ctrl Shift "=" for poor non US keyboard users. - self.CmdKeyAssign(ord('='), stc.STC_SCMOD_CTRL|stc.STC_SCMOD_SHIFT, - stc.STC_CMD_ZOOMIN) - - # Keys: we need to clear some of the keys the that don't play - # well with a console. - self.CmdKeyClear(ord('D'), stc.STC_SCMOD_CTRL) - self.CmdKeyClear(ord('L'), stc.STC_SCMOD_CTRL) - self.CmdKeyClear(ord('T'), stc.STC_SCMOD_CTRL) - self.CmdKeyClear(ord('A'), stc.STC_SCMOD_CTRL) - - self.SetEOLMode(stc.STC_EOL_CRLF) - self.SetWrapMode(stc.STC_WRAP_CHAR) - self.SetWrapMode(stc.STC_WRAP_WORD) - self.SetBufferedDraw(True) - - self.SetUseAntiAliasing(p['antialiasing']) - - self.SetLayoutCache(stc.STC_CACHE_PAGE) - self.SetUndoCollection(False) - self.SetUseTabs(True) - self.SetIndent(4) - self.SetTabWidth(4) - - # we don't want scintilla's autocompletion to choose - # automaticaly out of a single choice list, as we pop it up - # automaticaly - self.AutoCompSetChooseSingle(False) - self.AutoCompSetMaxHeight(10) - # XXX: this doesn't seem to have an effect. - self.AutoCompSetFillUps('\n') - - self.SetMargins(3, 3) #text is moved away from border with 3px - # Suppressing Scintilla margins - self.SetMarginWidth(0, 0) - self.SetMarginWidth(1, 0) - self.SetMarginWidth(2, 0) - - # Xterm escape sequences - self.color_pat = re.compile('\x01?\x1b\[(.*?)m\x02?') - self.title_pat = re.compile('\x1b]0;(.*?)\x07') - - # styles - - self.SetCaretForeground(p['carret_color']) - - background_color = p['background_color'] - - if 'default' in p: - if 'back' not in p['default']: - p['default'] += ',back:%s' % background_color - if 'size' not in p['default']: - p['default'] += ',size:%s' % self.faces['size'] - if 'face' not in p['default']: - p['default'] += ',face:%s' % self.faces['mono'] - - self.StyleSetSpec(stc.STC_STYLE_DEFAULT, p['default']) - else: - self.StyleSetSpec(stc.STC_STYLE_DEFAULT, - "fore:%s,back:%s,size:%d,face:%s" - % (self.ANSI_STYLES['0;30'][1], - background_color, - self.faces['size'], self.faces['mono'])) - - self.StyleClearAll() - - # XXX: two lines below are usefull if not using the lexer - #for style in self.ANSI_STYLES.values(): - # self.StyleSetSpec(style[0], "bold,fore:%s" % style[1]) - - # prompt definition - self.prompt_in1 = p['prompt_in1'] - self.prompt_out = p['prompt_out'] - - self.output_prompt_template = string.Template(self.prompt_out) - self.input_prompt_template = string.Template(self.prompt_in1) - - self.StyleSetSpec(_STDOUT_STYLE, p['stdout']) - self.StyleSetSpec(_STDERR_STYLE, p['stderr']) - self.StyleSetSpec(_TRACE_STYLE, p['trace']) - self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, p['bracegood']) - self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, p['bracebad']) - self.StyleSetSpec(stc.STC_P_COMMENTLINE, p['comment']) - self.StyleSetSpec(stc.STC_P_NUMBER, p['number']) - self.StyleSetSpec(stc.STC_P_STRING, p['string']) - self.StyleSetSpec(stc.STC_P_CHARACTER, p['char']) - self.StyleSetSpec(stc.STC_P_WORD, p['keyword']) - self.StyleSetSpec(stc.STC_P_WORD2, p['keyword']) - self.StyleSetSpec(stc.STC_P_TRIPLE, p['triple']) - self.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE, p['tripledouble']) - self.StyleSetSpec(stc.STC_P_CLASSNAME, p['class']) - self.StyleSetSpec(stc.STC_P_DEFNAME, p['def']) - self.StyleSetSpec(stc.STC_P_OPERATOR, p['operator']) - self.StyleSetSpec(stc.STC_P_COMMENTBLOCK, p['comment']) - - edge_column = p['edge_column'] - if edge_column is not None and edge_column > 0: - #we add a vertical line to console widget - self.SetEdgeMode(stc.STC_EDGE_LINE) - self.SetEdgeColumn(edge_column) - - - #-------------------------------------------------------------------------- - # EditWindow API - #-------------------------------------------------------------------------- - - def OnUpdateUI(self, event): - """ Override the OnUpdateUI of the EditWindow class, to prevent - syntax highlighting both for faster redraw, and for more - consistent look and feel. - """ - - - #-------------------------------------------------------------------------- - # Private API - #-------------------------------------------------------------------------- - - def _on_key_down(self, event, skip=True): - """ Key press callback used for correcting behavior for - console-like interfaces: the cursor is constraint to be after - the last prompt. - - Return True if event as been catched. - """ - catched = True - # XXX: Would the right way to do this be to have a - # dictionary at the instance level associating keys with - # callbacks? How would we deal with inheritance? And Do the - # different callbacks share local variables? - - # Intercept some specific keys. - key_code = event.GetKeyCode() - if key_code == ord('L') and event.ControlDown() : - self.scroll_to_bottom() - elif key_code == ord('K') and event.ControlDown() : - self.input_buffer = '' - elif key_code == ord('A') and event.ControlDown() : - self.GotoPos(self.GetLength()) - self.SetSelectionStart(self.current_prompt_pos) - self.SetSelectionEnd(self.GetCurrentPos()) - catched = True - elif key_code == ord('E') and event.ControlDown() : - self.GotoPos(self.GetLength()) - catched = True - elif key_code == wx.WXK_PAGEUP: - self.ScrollPages(-1) - elif key_code == wx.WXK_PAGEDOWN: - self.ScrollPages(1) - elif key_code == wx.WXK_HOME: - self.GotoPos(self.GetLength()) - elif key_code == wx.WXK_END: - self.GotoPos(self.GetLength()) - elif key_code == wx.WXK_UP and event.ShiftDown(): - self.ScrollLines(-1) - elif key_code == wx.WXK_DOWN and event.ShiftDown(): - self.ScrollLines(1) - else: - catched = False - - if self.AutoCompActive(): - event.Skip() - else: - if key_code in (13, wx.WXK_NUMPAD_ENTER): - # XXX: not catching modifiers, to be wx2.6-compatible - catched = True - if not self.enter_catched: - self.CallTipCancel() - if event.ShiftDown(): - # Try to force execution - self.GotoPos(self.GetLength()) - self.write('\n' + self.continuation_prompt(), - refresh=False) - self._on_enter() - else: - self._on_enter() - self.enter_catched = True - - elif key_code == wx.WXK_HOME: - if not event.ShiftDown(): - self.GotoPos(self.current_prompt_pos) - catched = True - else: - # FIXME: This behavior is not ideal: if the selection - # is already started, it will jump. - self.SetSelectionStart(self.current_prompt_pos) - self.SetSelectionEnd(self.GetCurrentPos()) - catched = True - - elif key_code == wx.WXK_UP: - if self.GetCurrentLine() > self.current_prompt_line: - if self.GetCurrentLine() == self.current_prompt_line + 1 \ - and self.GetColumn(self.GetCurrentPos()) < \ - self.GetColumn(self.current_prompt_pos): - self.GotoPos(self.current_prompt_pos) - else: - event.Skip() - catched = True - - elif key_code in (wx.WXK_LEFT, wx.WXK_BACK): - if not self._keep_cursor_in_buffer(self.GetCurrentPos() - 1): - event.Skip() - catched = True - - elif key_code == wx.WXK_RIGHT: - if not self._keep_cursor_in_buffer(self.GetCurrentPos() + 1): - event.Skip() - catched = True - - - elif key_code == wx.WXK_DELETE: - if not self._keep_cursor_in_buffer(self.GetCurrentPos() - 1): - event.Skip() - catched = True - - if skip and not catched: - # Put the cursor back in the edit region - if not self._keep_cursor_in_buffer(): - if not (self.GetCurrentPos() == self.GetLength() - and key_code == wx.WXK_DELETE): - event.Skip() - catched = True - - return catched - - - def _on_key_up(self, event, skip=True): - """ If cursor is outside the editing region, put it back. - """ - if skip: - event.Skip() - self._keep_cursor_in_buffer() - - - # XXX: I need to avoid the problem of having an empty glass; - def _keep_cursor_in_buffer(self, pos=None): - """ Checks if the cursor is where it is allowed to be. If not, - put it back. - - Returns - ------- - cursor_moved: Boolean - whether or not the cursor was moved by this routine. - - Notes - ------ - WARNING: This does proper checks only for horizontal - movements. - """ - if pos is None: - current_pos = self.GetCurrentPos() - else: - current_pos = pos - if current_pos < self.current_prompt_pos: - self.GotoPos(self.current_prompt_pos) - return True - line_num = self.LineFromPosition(current_pos) - if not current_pos > self.GetLength(): - line_pos = self.GetColumn(current_pos) - else: - line_pos = self.GetColumn(self.GetLength()) - line = self.GetLine(line_num) - # Jump the continuation prompt - continuation_prompt = self.continuation_prompt() - if ( line.startswith(continuation_prompt) - and line_pos < len(continuation_prompt)): - if line_pos < 2: - # We are at the beginning of the line, trying to move - # forward: jump forward. - self.GotoPos(current_pos + 1 + - len(continuation_prompt) - line_pos) - else: - # Jump back up - self.GotoPos(self.GetLineEndPosition(line_num-1)) - return True - elif ( current_pos > self.GetLineEndPosition(line_num) - and not current_pos == self.GetLength()): - # Jump to next line - self.GotoPos(current_pos + 1 + - len(continuation_prompt)) - return True - - # We re-allow enter event processing - self.enter_catched = False - return False - - -if __name__ == '__main__': - # Some simple code to test the console widget. - class MainWindow(wx.Frame): - def __init__(self, parent, id, title): - wx.Frame.__init__(self, parent, id, title, size=(300, 250)) - self._sizer = wx.BoxSizer(wx.VERTICAL) - self.console_widget = ConsoleWidget(self) - self._sizer.Add(self.console_widget, 1, wx.EXPAND) - self.SetSizer(self._sizer) - self.SetAutoLayout(1) - self.Show(True) - - app = wx.PySimpleApp() - w = MainWindow(None, wx.ID_ANY, 'ConsoleWidget') - w.SetSize((780, 460)) - w.Show() - - app.MainLoop() - - diff --git a/IPython/deathrow/oldfrontend/wx/ipythonx.py b/IPython/deathrow/oldfrontend/wx/ipythonx.py deleted file mode 100644 index 4eb6ffd..0000000 --- a/IPython/deathrow/oldfrontend/wx/ipythonx.py +++ /dev/null @@ -1,118 +0,0 @@ -""" -Entry point for a simple application giving a graphical frontend to -ipython. -""" - -try: - import wx -except ImportError as e: - e.args[0] = """%s -________________________________________________________________________________ -You need wxPython to run this application. -""" % e.args[0] - raise e - -from wx_frontend import WxController -import __builtin__ - - -class IPythonXController(WxController): - """ Sub class of WxController that adds some application-specific - bindings. - """ - - debug = False - - def __init__(self, *args, **kwargs): - WxController.__init__(self, *args, **kwargs) - self.ipython0.ask_exit = self.do_exit - # Scroll to top - maxrange = self.GetScrollRange(wx.VERTICAL) - self.ScrollLines(-maxrange) - - - def _on_key_down(self, event, skip=True): - # Intercept Ctrl-D to quit - if event.KeyCode == ord('D') and event.ControlDown() and \ - self.input_buffer == '' and \ - self._input_state == 'readline': - wx.CallAfter(self.ask_exit) - else: - WxController._on_key_down(self, event, skip=skip) - - - def ask_exit(self): - """ Ask the user whether to exit. - """ - self._input_state = 'subprocess' - self.write('\n', refresh=False) - self.capture_output() - self.ipython0.exit() - self.release_output() - if not self.ipython0.exit_now: - wx.CallAfter(self.new_prompt, - self.input_prompt_template.substitute( - number=self.last_result['number'] + 1)) - else: - wx.CallAfter(wx.GetApp().Exit) - self.write('Exiting ...', refresh=False) - - - def do_exit(self): - """ Exits the interpreter, kills the windows. - """ - WxController.do_exit(self) - self.release_output() - wx.CallAfter(wx.Exit) - - - -class IPythonX(wx.Frame): - """ Main frame of the IPythonX app. - """ - - def __init__(self, parent, id, title, debug=False): - wx.Frame.__init__(self, parent, id, title, size=(300,250)) - self._sizer = wx.BoxSizer(wx.VERTICAL) - self.shell = IPythonXController(self, debug=debug) - self._sizer.Add(self.shell, 1, wx.EXPAND) - self.SetSizer(self._sizer) - self.SetAutoLayout(1) - self.Show(True) - wx.EVT_CLOSE(self, self.on_close) - - - def on_close(self, event): - """ Called on closing the windows. - - Stops the event loop, to close all the child windows. - """ - wx.CallAfter(wx.Exit) - - -def main(): - from optparse import OptionParser - usage = """usage: %prog [options] - -Simple graphical frontend to IPython, using WxWidgets.""" - parser = OptionParser(usage=usage) - parser.add_option("-d", "--debug", - action="store_true", dest="debug", default=False, - help="Enable debug message for the wx frontend.") - - options, args = parser.parse_args() - - # Clear the options, to avoid having the ipython0 instance complain - import sys - sys.argv = sys.argv[:1] - - app = wx.PySimpleApp() - frame = IPythonX(None, wx.ID_ANY, 'IPythonX', debug=options.debug) - frame.shell.SetFocus() - frame.shell.app = app - frame.SetSize((680, 460)) - - app.MainLoop() - -if __name__ == '__main__': - main() diff --git a/IPython/deathrow/oldfrontend/wx/wx_frontend.py b/IPython/deathrow/oldfrontend/wx/wx_frontend.py deleted file mode 100644 index 8a3cb6f..0000000 --- a/IPython/deathrow/oldfrontend/wx/wx_frontend.py +++ /dev/null @@ -1,602 +0,0 @@ -# encoding: utf-8 -*- test-case-name: -# FIXME: Need to add tests. -# ipython1.frontend.wx.tests.test_wx_frontend -*- - -"""Classes to provide a Wx frontend to the -IPython.kernel.core.interpreter. - -This class inherits from ConsoleWidget, that provides a console-like -widget to provide a text-rendering widget suitable for a terminal. -""" - -__docformat__ = "restructuredtext en" - -#------------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports -#------------------------------------------------------------------------------- - -# Major library imports -import re -import __builtin__ -import sys -from threading import Lock - -import wx -from wx import stc - -# Ipython-specific imports. -from IPython.frontend.process import PipedProcess -from console_widget import ConsoleWidget, _COMPLETE_BUFFER_MARKER, \ - _ERROR_MARKER, _INPUT_MARKER -from IPython.frontend.prefilterfrontend import PrefilterFrontEnd - -#------------------------------------------------------------------------------- -# Classes to implement the Wx frontend -#------------------------------------------------------------------------------- -class WxController(ConsoleWidget, PrefilterFrontEnd): - """Classes to provide a Wx frontend to the - IPython.kernel.core.interpreter. - - This class inherits from ConsoleWidget, that provides a console-like - widget to provide a text-rendering widget suitable for a terminal. - """ - - # Print debug info on what is happening to the console. - debug = False - - # The title of the terminal, as captured through the ANSI escape - # sequences. - def _set_title(self, title): - return self.Parent.SetTitle(title) - - def _get_title(self): - return self.Parent.GetTitle() - - title = property(_get_title, _set_title) - - - # The buffer being edited. - # We are duplicating the definition here because of multiple - # inheritence - def _set_input_buffer(self, string): - ConsoleWidget._set_input_buffer(self, string) - self._colorize_input_buffer() - - def _get_input_buffer(self): - """ Returns the text in current edit buffer. - """ - return ConsoleWidget._get_input_buffer(self) - - input_buffer = property(_get_input_buffer, _set_input_buffer) - - - #-------------------------------------------------------------------------- - # Private Attributes - #-------------------------------------------------------------------------- - - # A flag governing the behavior of the input. Can be: - # - # 'readline' for readline-like behavior with a prompt - # and an edit buffer. - # 'raw_input' similar to readline, but triggered by a raw-input - # call. Can be used by subclasses to act differently. - # 'subprocess' for sending the raw input directly to a - # subprocess. - # 'buffering' for buffering of the input, that will be used - # when the input state switches back to another state. - _input_state = 'readline' - - # Attribute to store reference to the pipes of a subprocess, if we - # are running any. - _running_process = False - - # A queue for writing fast streams to the screen without flooding the - # event loop - _out_buffer = [] - - # A lock to lock the _out_buffer to make sure we don't empty it - # while it is being swapped - _out_buffer_lock = Lock() - - # The different line markers used to higlight the prompts. - _markers = dict() - - #-------------------------------------------------------------------------- - # Public API - #-------------------------------------------------------------------------- - - def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, - size=wx.DefaultSize, - style=wx.CLIP_CHILDREN|wx.WANTS_CHARS, - styledef=None, - *args, **kwds): - """ Create Shell instance. - - Parameters - ----------- - styledef : dict, optional - styledef is the dictionary of options used to define the - style. - """ - if styledef is not None: - self.style = styledef - ConsoleWidget.__init__(self, parent, id, pos, size, style) - PrefilterFrontEnd.__init__(self, **kwds) - - # Stick in our own raw_input: - self.ipython0.raw_input = self.raw_input - - # A time for flushing the write buffer - BUFFER_FLUSH_TIMER_ID = 100 - self._buffer_flush_timer = wx.Timer(self, BUFFER_FLUSH_TIMER_ID) - wx.EVT_TIMER(self, BUFFER_FLUSH_TIMER_ID, self._buffer_flush) - - if 'debug' in kwds: - self.debug = kwds['debug'] - kwds.pop('debug') - - # Inject self in namespace, for debug - if self.debug: - self.shell.user_ns['self'] = self - # Inject our own raw_input in namespace - self.shell.user_ns['raw_input'] = self.raw_input - - def raw_input(self, prompt=''): - """ A replacement from python's raw_input. - """ - self.new_prompt(prompt) - self._input_state = 'raw_input' - if hasattr(self, '_cursor'): - del self._cursor - self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS)) - self.__old_on_enter = self._on_enter - event_loop = wx.EventLoop() - def my_on_enter(): - event_loop.Exit() - self._on_enter = my_on_enter - # XXX: Running a separate event_loop. Ugly. - event_loop.Run() - self._on_enter = self.__old_on_enter - self._input_state = 'buffering' - self._cursor = wx.BusyCursor() - return self.input_buffer.rstrip('\n') - - - def system_call(self, command_string): - self._input_state = 'subprocess' - event_loop = wx.EventLoop() - def _end_system_call(): - self._input_state = 'buffering' - self._running_process = False - event_loop.Exit() - - self._running_process = PipedProcess(command_string, - out_callback=self.buffered_write, - end_callback = _end_system_call) - self._running_process.start() - # XXX: Running a separate event_loop. Ugly. - event_loop.Run() - # Be sure to flush the buffer. - self._buffer_flush(event=None) - - - def do_calltip(self): - """ Analyse current and displays useful calltip for it. - """ - if self.debug: - print >>sys.__stdout__, "do_calltip" - separators = re.compile('[\s\{\}\[\]\(\)\= ,:]') - symbol = self.input_buffer - symbol_string = separators.split(symbol)[-1] - base_symbol_string = symbol_string.split('.')[0] - if base_symbol_string in self.shell.user_ns: - symbol = self.shell.user_ns[base_symbol_string] - elif base_symbol_string in self.shell.user_global_ns: - symbol = self.shell.user_global_ns[base_symbol_string] - elif base_symbol_string in __builtin__.__dict__: - symbol = __builtin__.__dict__[base_symbol_string] - else: - return False - try: - for name in symbol_string.split('.')[1:] + ['__doc__']: - symbol = getattr(symbol, name) - self.AutoCompCancel() - # Check that the symbol can indeed be converted to a string: - symbol += '' - wx.CallAfter(self.CallTipShow, self.GetCurrentPos(), symbol) - except: - # The retrieve symbol couldn't be converted to a string - pass - - - def _popup_completion(self, create=False): - """ Updates the popup completion menu if it exists. If create is - true, open the menu. - """ - if self.debug: - print >>sys.__stdout__, "_popup_completion" - line = self.input_buffer - if (self.AutoCompActive() and line and not line[-1] == '.') \ - or create==True: - suggestion, completions = self.complete(line) - if completions: - offset = len(self._get_completion_text(line)) - self.pop_completion(completions, offset=offset) - if self.debug: - print >>sys.__stdout__, completions - - - def buffered_write(self, text): - """ A write method for streams, that caches the stream in order - to avoid flooding the event loop. - - This can be called outside of the main loop, in separate - threads. - """ - self._out_buffer_lock.acquire() - self._out_buffer.append(text) - self._out_buffer_lock.release() - if not self._buffer_flush_timer.IsRunning(): - wx.CallAfter(self._buffer_flush_timer.Start, - milliseconds=100, oneShot=True) - - - def clear_screen(self): - """ Empty completely the widget. - """ - self.ClearAll() - self.new_prompt(self.input_prompt_template.substitute( - number=(self.last_result['number'] + 1))) - - - #-------------------------------------------------------------------------- - # LineFrontEnd interface - #-------------------------------------------------------------------------- - - def execute(self, python_string, raw_string=None): - self._input_state = 'buffering' - self.CallTipCancel() - self._cursor = wx.BusyCursor() - if raw_string is None: - raw_string = python_string - end_line = self.current_prompt_line \ - + max(1, len(raw_string.split('\n'))-1) - for i in range(self.current_prompt_line, end_line): - if i in self._markers: - self.MarkerDeleteHandle(self._markers[i]) - self._markers[i] = self.MarkerAdd(i, _COMPLETE_BUFFER_MARKER) - # Use a callafter to update the display robustly under windows - def callback(): - self.GotoPos(self.GetLength()) - PrefilterFrontEnd.execute(self, python_string, - raw_string=raw_string) - wx.CallAfter(callback) - - - def execute_command(self, command, hidden=False): - """ Execute a command, not only in the model, but also in the - view. - """ - # XXX: This method needs to be integrated in the base fronted - # interface - if hidden: - return self.shell.execute(command) - else: - # XXX: we are not storing the input buffer previous to the - # execution, as this forces us to run the execution - # input_buffer a yield, which is not good. - ##current_buffer = self.shell.control.input_buffer - command = command.rstrip() - if len(command.split('\n')) > 1: - # The input command is several lines long, we need to - # force the execution to happen - command += '\n' - cleaned_command = self.prefilter_input(command) - self.input_buffer = command - # Do not use wx.Yield() (aka GUI.process_events()) to avoid - # recursive yields. - self.ProcessEvent(wx.PaintEvent()) - self.write('\n') - if not self.is_complete(cleaned_command + '\n'): - self._colorize_input_buffer() - self.render_error('Incomplete or invalid input') - self.new_prompt(self.input_prompt_template.substitute( - number=(self.last_result['number'] + 1))) - return False - self._on_enter() - return True - - - def save_output_hooks(self): - self.__old_raw_input = __builtin__.raw_input - PrefilterFrontEnd.save_output_hooks(self) - - def capture_output(self): - self.SetLexer(stc.STC_LEX_NULL) - PrefilterFrontEnd.capture_output(self) - __builtin__.raw_input = self.raw_input - - - def release_output(self): - __builtin__.raw_input = self.__old_raw_input - PrefilterFrontEnd.release_output(self) - self.SetLexer(stc.STC_LEX_PYTHON) - - - def after_execute(self): - PrefilterFrontEnd.after_execute(self) - # Clear the wait cursor - if hasattr(self, '_cursor'): - del self._cursor - self.SetCursor(wx.StockCursor(wx.CURSOR_CHAR)) - - - def show_traceback(self): - start_line = self.GetCurrentLine() - PrefilterFrontEnd.show_traceback(self) - self.ProcessEvent(wx.PaintEvent()) - #wx.Yield() - for i in range(start_line, self.GetCurrentLine()): - self._markers[i] = self.MarkerAdd(i, _ERROR_MARKER) - - - #-------------------------------------------------------------------------- - # FrontEndBase interface - #-------------------------------------------------------------------------- - - def render_error(self, e): - start_line = self.GetCurrentLine() - self.write('\n' + e + '\n') - for i in range(start_line, self.GetCurrentLine()): - self._markers[i] = self.MarkerAdd(i, _ERROR_MARKER) - - - #-------------------------------------------------------------------------- - # ConsoleWidget interface - #-------------------------------------------------------------------------- - - def new_prompt(self, prompt): - """ Display a new prompt, and start a new input buffer. - """ - self._input_state = 'readline' - ConsoleWidget.new_prompt(self, prompt) - i = self.current_prompt_line - self._markers[i] = self.MarkerAdd(i, _INPUT_MARKER) - - - def continuation_prompt(self, *args, **kwargs): - # Avoid multiple inheritence, be explicit about which - # parent method class gets called - return ConsoleWidget.continuation_prompt(self, *args, **kwargs) - - - def write(self, *args, **kwargs): - # Avoid multiple inheritence, be explicit about which - # parent method class gets called - return ConsoleWidget.write(self, *args, **kwargs) - - - def _on_key_down(self, event, skip=True): - """ Capture the character events, let the parent - widget handle them, and put our logic afterward. - """ - # FIXME: This method needs to be broken down in smaller ones. - current_line_num = self.GetCurrentLine() - key_code = event.GetKeyCode() - if key_code in (ord('c'), ord('C')) and event.ControlDown(): - # Capture Control-C - if self._input_state == 'subprocess': - if self.debug: - print >>sys.__stderr__, 'Killing running process' - if hasattr(self._running_process, 'process'): - self._running_process.process.kill() - elif self._input_state == 'buffering': - if self.debug: - print >>sys.__stderr__, 'Raising KeyboardInterrupt' - raise KeyboardInterrupt - # XXX: We need to make really sure we - # get back to a prompt. - elif self._input_state == 'subprocess' and ( - ( key_code <256 and not event.ControlDown() ) - or - ( key_code in (ord('d'), ord('D')) and - event.ControlDown())): - # We are running a process, we redirect keys. - ConsoleWidget._on_key_down(self, event, skip=skip) - char = chr(key_code) - # Deal with some inconsistency in wx keycodes: - if char == '\r': - char = '\n' - elif not event.ShiftDown(): - char = char.lower() - if event.ControlDown() and key_code in (ord('d'), ord('D')): - char = '\04' - self._running_process.process.stdin.write(char) - self._running_process.process.stdin.flush() - elif key_code in (ord('('), 57, 53): - # Calltips - event.Skip() - self.do_calltip() - elif self.AutoCompActive() and not key_code == ord('\t'): - event.Skip() - if key_code in (wx.WXK_BACK, wx.WXK_DELETE): - wx.CallAfter(self._popup_completion, create=True) - elif not key_code in (wx.WXK_UP, wx.WXK_DOWN, wx.WXK_LEFT, - wx.WXK_RIGHT, wx.WXK_ESCAPE): - wx.CallAfter(self._popup_completion) - else: - # Up history - if key_code == wx.WXK_UP and ( - event.ControlDown() or - current_line_num == self.current_prompt_line - ): - new_buffer = self.get_history_previous( - self.input_buffer) - if new_buffer is not None: - self.input_buffer = new_buffer - if self.GetCurrentLine() > self.current_prompt_line: - # Go to first line, for seemless history up. - self.GotoPos(self.current_prompt_pos) - # Down history - elif key_code == wx.WXK_DOWN and ( - event.ControlDown() or - current_line_num == self.LineCount -1 - ): - new_buffer = self.get_history_next() - if new_buffer is not None: - self.input_buffer = new_buffer - # Tab-completion - elif key_code == ord('\t'): - current_line, current_line_num = self.CurLine - if not re.match(r'^%s\s*$' % self.continuation_prompt(), - current_line): - self.complete_current_input() - if self.AutoCompActive(): - wx.CallAfter(self._popup_completion, create=True) - else: - event.Skip() - elif key_code == wx.WXK_BACK: - # If characters where erased, check if we have to - # remove a line. - # XXX: What about DEL? - # FIXME: This logics should be in ConsoleWidget, as it is - # independant of IPython - current_line, _ = self.CurLine - current_pos = self.GetCurrentPos() - current_line_num = self.LineFromPosition(current_pos) - current_col = self.GetColumn(current_pos) - len_prompt = len(self.continuation_prompt()) - if ( current_line.startswith(self.continuation_prompt()) - and current_col == len_prompt): - new_lines = [] - for line_num, line in enumerate( - self.input_buffer.split('\n')): - if (line_num + self.current_prompt_line == - current_line_num): - new_lines.append(line[len_prompt:]) - else: - new_lines.append('\n'+line) - # The first character is '\n', due to the above - # code: - self.input_buffer = ''.join(new_lines)[1:] - self.GotoPos(current_pos - 1 - len_prompt) - else: - ConsoleWidget._on_key_down(self, event, skip=skip) - else: - ConsoleWidget._on_key_down(self, event, skip=skip) - - - - def _on_key_up(self, event, skip=True): - """ Called when any key is released. - """ - if event.GetKeyCode() in (59, ord('.')): - # Intercepting '.' - event.Skip() - wx.CallAfter(self._popup_completion, create=True) - else: - ConsoleWidget._on_key_up(self, event, skip=skip) - # Make sure the continuation_prompts are always followed by a - # whitespace - new_lines = [] - if self._input_state == 'readline': - position = self.GetCurrentPos() - continuation_prompt = self.continuation_prompt()[:-1] - for line in self.input_buffer.split('\n'): - if not line == continuation_prompt: - new_lines.append(line) - self.input_buffer = '\n'.join(new_lines) - self.GotoPos(position) - - - def _on_enter(self): - """ Called on return key down, in readline input_state. - """ - last_line_num = self.LineFromPosition(self.GetLength()) - current_line_num = self.LineFromPosition(self.GetCurrentPos()) - new_line_pos = (last_line_num - current_line_num) - if self.debug: - print >>sys.__stdout__, repr(self.input_buffer) - self.write('\n', refresh=False) - # Under windows scintilla seems to be doing funny - # stuff to the line returns here, but the getter for - # input_buffer filters this out. - if sys.platform == 'win32': - self.input_buffer = self.input_buffer - old_prompt_num = self.current_prompt_pos - has_executed = PrefilterFrontEnd._on_enter(self, - new_line_pos=new_line_pos) - if old_prompt_num == self.current_prompt_pos: - # No execution has happened - self.GotoPos(self.GetLineEndPosition(current_line_num + 1)) - return has_executed - - - #-------------------------------------------------------------------------- - # EditWindow API - #-------------------------------------------------------------------------- - - def OnUpdateUI(self, event): - """ Override the OnUpdateUI of the EditWindow class, to prevent - syntax highlighting both for faster redraw, and for more - consistent look and feel. - """ - if not self._input_state == 'readline': - ConsoleWidget.OnUpdateUI(self, event) - - #-------------------------------------------------------------------------- - # Private API - #-------------------------------------------------------------------------- - - def _buffer_flush(self, event): - """ Called by the timer to flush the write buffer. - - This is always called in the mainloop, by the wx timer. - """ - self._out_buffer_lock.acquire() - _out_buffer = self._out_buffer - self._out_buffer = [] - self._out_buffer_lock.release() - self.write(''.join(_out_buffer), refresh=False) - - - def _colorize_input_buffer(self): - """ Keep the input buffer lines at a bright color. - """ - if not self._input_state in ('readline', 'raw_input'): - return - end_line = self.GetCurrentLine() - if not sys.platform == 'win32': - end_line += 1 - for i in range(self.current_prompt_line, end_line): - if i in self._markers: - self.MarkerDeleteHandle(self._markers[i]) - self._markers[i] = self.MarkerAdd(i, _INPUT_MARKER) - - -if __name__ == '__main__': - class MainWindow(wx.Frame): - def __init__(self, parent, id, title): - wx.Frame.__init__(self, parent, id, title, size=(300,250)) - self._sizer = wx.BoxSizer(wx.VERTICAL) - self.shell = WxController(self) - self._sizer.Add(self.shell, 1, wx.EXPAND) - self.SetSizer(self._sizer) - self.SetAutoLayout(1) - self.Show(True) - - app = wx.PySimpleApp() - frame = MainWindow(None, wx.ID_ANY, 'Ipython') - frame.shell.SetFocus() - frame.SetSize((680, 460)) - self = frame.shell - - app.MainLoop() - diff --git a/IPython/deathrow/oldfrontend/zopeinterface.py b/IPython/deathrow/oldfrontend/zopeinterface.py deleted file mode 100644 index 9a92458..0000000 --- a/IPython/deathrow/oldfrontend/zopeinterface.py +++ /dev/null @@ -1,27 +0,0 @@ -# encoding: utf-8 -# -*- test-case-name: IPython.frontend.tests.test_frontendbase -*- -""" -zope.interface mock. If zope is installed, this module provides a zope -interface classes, if not it provides mocks for them. - -Classes provided: -Interface, Attribute, implements, classProvides -""" -__docformat__ = "restructuredtext en" - -#------------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#------------------------------------------------------------------------------- - -try: - from zope.interface import Interface, Attribute, implements, classProvides -except ImportError: - #zope.interface is not available - Interface = object - def Attribute(name, doc): pass - def implements(interface): pass - def classProvides(interface): pass - diff --git a/IPython/deathrow/outputtrap.py b/IPython/deathrow/outputtrap.py deleted file mode 100644 index c63c798..0000000 --- a/IPython/deathrow/outputtrap.py +++ /dev/null @@ -1,258 +0,0 @@ -# -*- coding: utf-8 -*- -"""Class to trap stdout and stderr and log them separately. -""" - -#***************************************************************************** -# Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#***************************************************************************** - -import exceptions -import sys -from cStringIO import StringIO - -class OutputTrapError(exceptions.Exception): - """Exception for OutputTrap class.""" - - def __init__(self,args=None): - exceptions.Exception.__init__(self) - self.args = args - -class OutputTrap: - - """Class to trap standard output and standard error. They get logged in - StringIO objects which are available as <instance>.out and - <instance>.err. The class also offers summary methods which format this - data a bit. - - A word of caution: because it blocks messages, using this class can make - debugging very tricky. If you are having bizarre problems silently, try - turning your output traps off for a while. You can call the constructor - with the parameter debug=1 for these cases. This turns actual trapping - off, but you can keep the rest of your code unchanged (this has already - been a life saver). - - Example: - - # config: trapper with a line of dots as log separator (final '\\n' needed) - config = OutputTrap('Config','Out ','Err ','.'*80+'\\n') - - # start trapping output - config.trap_all() - - # now all output is logged ... - # do stuff... - - # output back to normal: - config.release_all() - - # print all that got logged: - print config.summary() - - # print individual raw data: - print config.out.getvalue() - print config.err.getvalue() - """ - - def __init__(self,name='Generic Output Trap', - out_head='Standard Output. ',err_head='Standard Error. ', - sum_sep='\n',debug=0,trap_out=0,trap_err=0, - quiet_out=0,quiet_err=0): - self.name = name - self.out_head = out_head - self.err_head = err_head - self.sum_sep = sum_sep - self.out = StringIO() - self.err = StringIO() - self.out_save = None - self.err_save = None - self.debug = debug - self.quiet_out = quiet_out - self.quiet_err = quiet_err - if trap_out: - self.trap_out() - if trap_err: - self.trap_err() - - def trap_out(self): - """Trap and log stdout.""" - if sys.stdout is self.out: - raise OutputTrapError,'You are already trapping stdout.' - if not self.debug: - self._out_save = sys.stdout - sys.stdout = self.out - - def release_out(self): - """Release stdout.""" - if not self.debug: - if not sys.stdout is self.out: - raise OutputTrapError,'You are not trapping stdout.' - sys.stdout = self._out_save - self.out_save = None - - def summary_out(self): - """Return as a string the log from stdout.""" - out = self.out.getvalue() - if out: - if self.quiet_out: - return out - else: - return self.out_head + 'Log by '+ self.name + ':\n' + out - else: - return '' - - def flush_out(self): - """Flush the stdout log. All data held in the log is lost.""" - - self.out.close() - self.out = StringIO() - - def trap_err(self): - """Trap and log stderr.""" - if sys.stderr is self.err: - raise OutputTrapError,'You are already trapping stderr.' - if not self.debug: - self._err_save = sys.stderr - sys.stderr = self.err - - def release_err(self): - """Release stderr.""" - if not self.debug: - if not sys.stderr is self.err: - raise OutputTrapError,'You are not trapping stderr.' - sys.stderr = self._err_save - self.err_save = None - - def summary_err(self): - """Return as a string the log from stderr.""" - err = self.err.getvalue() - if err: - if self.quiet_err: - return err - else: - return self.err_head + 'Log by '+ self.name + ':\n' + err - else: - return '' - - def flush_err(self): - """Flush the stdout log. All data held in the log is lost.""" - - self.err.close() - self.err = StringIO() - - def trap_all(self): - """Trap and log both stdout and stderr. - - Cacthes and discards OutputTrapError exceptions raised.""" - try: - self.trap_out() - except OutputTrapError: - pass - try: - self.trap_err() - except OutputTrapError: - pass - - def release_all(self): - """Release both stdout and stderr. - - Cacthes and discards OutputTrapError exceptions raised.""" - try: - self.release_out() - except OutputTrapError: - pass - try: - self.release_err() - except OutputTrapError: - pass - - def summary_all(self): - """Return as a string the log from stdout and stderr, prepending a separator - to each (defined in __init__ as sum_sep).""" - sum = '' - sout = self.summary_out() - if sout: - sum += self.sum_sep + sout - serr = self.summary_err() - if serr: - sum += '\n'+self.sum_sep + serr - return sum - - def flush_all(self): - """Flush stdout and stderr""" - self.flush_out() - self.flush_err() - - # a few shorthands - trap = trap_all - release = release_all - summary = summary_all - flush = flush_all -# end OutputTrap - - -#**************************************************************************** -# Module testing. Incomplete, I'm lazy... - -def _test_all(): - - """Module testing functions, activated when the module is called as a - script (not imported).""" - - # Put tests for this module in here. - # Define them as nested functions so they don't clobber the - # pydoc-generated docs - - def _test_(): - name = '' - print '#'*50+'\nRunning test for ' + name - # ... - print 'Finished test for '+ name +'\n'+'#'*50 - - def _test_OutputTrap(): - trap = OutputTrap(name = 'Test Trap', sum_sep = '.'*50+'\n', - out_head = 'SOut. ', err_head = 'SErr. ') - - name = 'OutputTrap class' - print '#'*50+'\nRunning test for ' + name - print 'Trapping out' - trap.trap_out() - print >>sys.stdout, '>>stdout. stdout is trapped.' - print >>sys.stderr, '>>stderr. stdout is trapped.' - trap.release_out() - print trap.summary_out() - - print 'Trapping err' - trap.trap_err() - print >>sys.stdout, '>>stdout. stderr is trapped.' - print >>sys.stderr, '>>stderr. stderr is trapped.' - trap.release_err() - print trap.summary_err() - - print 'Trapping all (no flushing)' - trap.trap_all() - print >>sys.stdout, '>>stdout. stdout/err is trapped.' - print >>sys.stderr, '>>stderr. stdout/err is trapped.' - trap.release_all() - print trap.summary_all() - - print 'Trapping all (flushing first)' - trap.flush() - trap.trap_all() - print >>sys.stdout, '>>stdout. stdout/err is trapped.' - print >>sys.stderr, '>>stderr. stdout/err is trapped.' - trap.release_all() - print trap.summary_all() - print 'Finished test for '+ name +'\n'+'#'*50 - - # call the actual tests here: - _test_OutputTrap() - - -if __name__=="__main__": - # _test_all() # XXX BROKEN. - pass - -#************************ end of file <OutputTrap.py> ************************ diff --git a/IPython/deathrow/quitter.py b/IPython/deathrow/quitter.py deleted file mode 100644 index 2617ac1..0000000 --- a/IPython/deathrow/quitter.py +++ /dev/null @@ -1,47 +0,0 @@ -# coding: utf-8 -""" -A simple class for quitting IPython. - -Authors -------- -* Fernando Perez -* Brian Granger -""" - -#----------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#----------------------------------------------------------------------------- - -#----------------------------------------------------------------------------- -# Imports -#----------------------------------------------------------------------------- - - -#----------------------------------------------------------------------------- -# Code -#----------------------------------------------------------------------------- - - -class Quitter(object): - """Simple class to handle exit, similar to Python 2.5's. - - It handles exiting in an ipython-safe manner, which the one in Python 2.5 - doesn't do (obviously, since it doesn't know about ipython).""" - - def __init__(self, shell, name): - self.shell = shell - self.name = name - - def __str__(self): - return 'Type %s() to exit.' % self.name - - def __call__(self): - self.shell.ask_exit() - - # Repr MUST return a string, else display like pprint hooks get confused - def __repr__(self): - self.shell.ask_exit() - return '' diff --git a/IPython/deathrow/scitedirector.py b/IPython/deathrow/scitedirector.py deleted file mode 100644 index 86f35fa..0000000 --- a/IPython/deathrow/scitedirector.py +++ /dev/null @@ -1,26 +0,0 @@ -import win32api -import win32gui -import win32con - -import struct -import array - -def findWindows(): - ret = [] - sdi = win32api.RegisterWindowMessage("SciTEDirectorInterface") - w = win32gui.GetWindow(win32gui.GetDesktopWindow(), win32con.GW_CHILD) - while w: - res = win32gui.SendMessage(w, sdi, 0, 0) - if res == sdi: - ret.append(w) - w = win32gui.GetWindow(w, win32con.GW_HWNDNEXT) - - return ret - -def sendCommand(w, message): - CopyDataStruct = "IIP" - char_buffer = array.array('c', message) - char_buffer_address = char_buffer.buffer_info()[0] - char_buffer_size = char_buffer.buffer_info()[1] - cds = struct.pack(CopyDataStruct, 0, char_buffer_size, char_buffer_address) - win32gui.SendMessage(w, win32con.WM_COPYDATA, 0, cds) diff --git a/IPython/deathrow/tests/test_prefilter.py b/IPython/deathrow/tests/test_prefilter.py deleted file mode 100644 index 410839f..0000000 --- a/IPython/deathrow/tests/test_prefilter.py +++ /dev/null @@ -1,440 +0,0 @@ -""" -Test which prefilter transformations get called for various input lines. -Note that this does *not* test the transformations themselves -- it's just -verifying that a particular combination of, e.g. config options and escape -chars trigger the proper handle_X transform of the input line. - -Usage: run from the command line with *normal* python, not ipython: -> python test_prefilter.py - -Fairly quiet output by default. Pass in -v to get everyone's favorite dots. -""" - -# The prefilter always ends in a call to some self.handle_X method. We swap -# all of those out so that we can capture which one was called. - -import sys -sys.path.append('..') -import IPython -import IPython.ipapi - -verbose = False -if len(sys.argv) > 1: - if sys.argv[1] == '-v': - sys.argv = sys.argv[:-1] # IPython is confused by -v, apparently - verbose = True - -IPython.Shell.start() - -ip = IPython.ipapi.get() - -# Collect failed tests + stats and print them at the end -failures = [] -num_tests = 0 - -# Store the results in module vars as we go -last_line = None -handler_called = None -def install_mock_handler(name): - """Swap out one of the IP.handle_x methods with a function which can - record which handler was called and what line was produced. The mock - handler func always returns '', which causes ipython to cease handling - the string immediately. That way, that it doesn't echo output, raise - exceptions, etc. But do note that testing multiline strings thus gets - a bit hard.""" - def mock_handler(self, line, continue_prompt=None, - pre=None,iFun=None,theRest=None, - obj=None): - #print "Inside %s with '%s'" % (name, line) - global last_line, handler_called - last_line = line - handler_called = name - return '' - mock_handler.name = name - setattr(IPython.iplib.InteractiveShell, name, mock_handler) - -install_mock_handler('handle_normal') -install_mock_handler('handle_auto') -install_mock_handler('handle_magic') -install_mock_handler('handle_help') -install_mock_handler('handle_shell_escape') -install_mock_handler('handle_alias') -install_mock_handler('handle_emacs') - - -def reset_esc_handlers(): - """The escape handlers are stored in a hash (as an attribute of the - InteractiveShell *instance*), so we have to rebuild that hash to get our - new handlers in there.""" - s = ip.IP - s.esc_handlers = {s.ESC_PAREN : s.handle_auto, - s.ESC_QUOTE : s.handle_auto, - s.ESC_QUOTE2 : s.handle_auto, - s.ESC_MAGIC : s.handle_magic, - s.ESC_HELP : s.handle_help, - s.ESC_SHELL : s.handle_shell_escape, - s.ESC_SH_CAP : s.handle_shell_escape, - } -reset_esc_handlers() - -# This is so I don't have to quote over and over. Gotta be a better way. -handle_normal = 'handle_normal' -handle_auto = 'handle_auto' -handle_magic = 'handle_magic' -handle_help = 'handle_help' -handle_shell_escape = 'handle_shell_escape' -handle_alias = 'handle_alias' -handle_emacs = 'handle_emacs' - -def check(assertion, failure_msg): - """Check a boolean assertion and fail with a message if necessary. Store - an error essage in module-level failures list in case of failure. Print - '.' or 'F' if module var Verbose is true. - """ - global num_tests - num_tests += 1 - if assertion: - if verbose: - sys.stdout.write('.') - sys.stdout.flush() - else: - if verbose: - sys.stdout.write('F') - sys.stdout.flush() - failures.append(failure_msg) - - -def check_handler(expected_handler, line): - """Verify that the expected hander was called (for the given line, - passed in for failure reporting). - - Pulled out to its own function so that tests which don't use - run_handler_tests can still take advantage of it.""" - check(handler_called == expected_handler, - "Expected %s to be called for %s, " - "instead %s called" % (expected_handler, - repr(line), - handler_called)) - - -def run_handler_tests(h_tests): - """Loop through a series of (input_line, handler_name) pairs, verifying - that, for each ip calls the given handler for the given line. - - The verbose complaint includes the line passed in, so if that line can - include enough info to find the error, the tests are modestly - self-documenting. - """ - for ln, expected_handler in h_tests: - global handler_called - handler_called = None - ip.runlines(ln) - check_handler(expected_handler, ln) - -def run_one_test(ln, expected_handler): - run_handler_tests([(ln, expected_handler)]) - - -# ========================================= -# Tests -# ========================================= - - -# Fundamental escape characters + whitespace & misc -# ================================================= -esc_handler_tests = [ - ( '?thing', handle_help, ), - ( 'thing?', handle_help ), # '?' can trail... - ( 'thing!', handle_normal), # but only '?' can trail - ( ' ?thing', handle_normal), # leading whitespace turns off esc chars - ( '!ls', handle_shell_escape), - ( '! true', handle_shell_escape), - ( '!! true', handle_shell_escape), - ( '%magic', handle_magic), - # XXX Possibly, add test for /,; once those are unhooked from %autocall - ( 'emacs_mode # PYTHON-MODE', handle_emacs ), - ( ' ', handle_normal), - - # Trailing qmark combos. Odd special cases abound - - # ! always takes priority! - ( '!thing?', handle_shell_escape), - ( '!thing arg?', handle_shell_escape), - ( '!!thing?', handle_shell_escape), - ( '!!thing arg?', handle_shell_escape), - ( ' !!thing arg?', handle_shell_escape), - - # For all other leading esc chars, we always trigger help - ( '%cmd?', handle_help), - ( '%cmd ?', handle_help), - ( '/cmd?', handle_help), - ( '/cmd ?', handle_help), - ( ';cmd?', handle_help), - ( ',cmd?', handle_help), - ] -run_handler_tests(esc_handler_tests) - - - -# Shell Escapes in Multi-line statements -# ====================================== -# -# We can't test this via runlines, since the hacked-over-for-testing -# handlers all return None, so continue_prompt never becomes true. Instead -# we drop into prefilter directly and pass in continue_prompt. - -old_mls = ip.options.multi_line_specials -for ln in [ ' !ls $f multi_line_specials %s', - ' !!ls $f multi_line_specials %s', # !! escapes work on mls - # Trailing ? doesn't trigger help: - ' !ls $f multi_line_specials %s ?', - ' !!ls $f multi_line_specials %s ?', - ]: - ip.options.multi_line_specials = 1 - on_ln = ln % 'on' - ignore = ip.IP.prefilter(on_ln, continue_prompt=True) - check_handler(handle_shell_escape, on_ln) - - ip.options.multi_line_specials = 0 - off_ln = ln % 'off' - ignore = ip.IP.prefilter(off_ln, continue_prompt=True) - check_handler(handle_normal, off_ln) - -ip.options.multi_line_specials = old_mls - - -# Automagic -# ========= - -# Pick one magic fun and one non_magic fun, make sure both exist -assert hasattr(ip.IP, "magic_cpaste") -assert not hasattr(ip.IP, "magic_does_not_exist") -ip.options.autocall = 0 # gotta have this off to get handle_normal -ip.options.automagic = 0 -run_handler_tests([ - # Without automagic, only shows up with explicit escape - ( 'cpaste', handle_normal), - ( '%cpaste', handle_magic), - ( '%does_not_exist', handle_magic), - ]) -ip.options.automagic = 1 -run_handler_tests([ - ( 'cpaste', handle_magic), - ( '%cpaste', handle_magic), - ( 'does_not_exist', handle_normal), - ( '%does_not_exist', handle_magic), - ( 'cd /', handle_magic), - ( 'cd = 2', handle_normal), - ( 'r', handle_magic), - ( 'r thing', handle_magic), - ( 'r"str"', handle_normal), - ]) - -# If next elt starts with anything that could be an assignment, func call, -# etc, we don't call the magic func, unless explicitly escaped to do so. -#magic_killing_tests = [] -#for c in list('!=()<>,'): -# magic_killing_tests.append(('cpaste %s killed_automagic' % c, handle_normal)) -# magic_killing_tests.append(('%%cpaste %s escaped_magic' % c, handle_magic)) -#run_handler_tests(magic_killing_tests) - -# magic on indented continuation lines -- on iff multi_line_specials == 1 -ip.options.multi_line_specials = 0 -ln = ' cpaste multi_line off kills magic' -ignore = ip.IP.prefilter(ln, continue_prompt=True) -check_handler(handle_normal, ln) - -ip.options.multi_line_specials = 1 -ln = ' cpaste multi_line on enables magic' -ignore = ip.IP.prefilter(ln, continue_prompt=True) -check_handler(handle_magic, ln) - -# user namespace shadows the magic one unless shell escaped -ip.user_ns['cpaste'] = 'user_ns' -run_handler_tests([ - ( 'cpaste', handle_normal), - ( '%cpaste', handle_magic)]) -del ip.user_ns['cpaste'] - - - -# Check for !=() turning off .ofind -# ================================= -class AttributeMutator(object): - """A class which will be modified on attribute access, to test ofind""" - def __init__(self): - self.called = False - - def getFoo(self): self.called = True - foo = property(getFoo) - -attr_mutator = AttributeMutator() -ip.to_user_ns('attr_mutator') - -ip.options.autocall = 1 - -run_one_test('attr_mutator.foo should mutate', handle_normal) -check(attr_mutator.called, 'ofind should be called in absence of assign characters') - -for c in list('!=()<>+*/%^&|'): - attr_mutator.called = False - run_one_test('attr_mutator.foo %s should *not* mutate' % c, handle_normal) - run_one_test('attr_mutator.foo%s should *not* mutate' % c, handle_normal) - - check(not attr_mutator.called, - 'ofind should not be called near character %s' % c) - - - -# Alias expansion -# =============== - -# With autocall on or off, aliases should be shadowed by user, internal and -# __builtin__ namespaces -# -# XXX Can aliases have '.' in their name? With autocall off, that works, -# with autocall on, it doesn't. Hmmm. -import __builtin__ -for ac_state in [0,1]: - ip.options.autocall = ac_state - ip.IP.alias_table['alias_cmd'] = 'alias_result' - ip.IP.alias_table['alias_head.with_dot'] = 'alias_result' - run_handler_tests([ - ("alias_cmd", handle_alias), - # XXX See note above - #("alias_head.with_dot unshadowed, autocall=%s" % ac_state, handle_alias), - ("alias_cmd.something aliases must match whole expr", handle_normal), - ("alias_cmd /", handle_alias), - ]) - - for ns in [ip.user_ns, ip.IP.internal_ns, __builtin__.__dict__ ]: - ns['alias_cmd'] = 'a user value' - ns['alias_head'] = 'a user value' - run_handler_tests([ - ("alias_cmd", handle_normal), - ("alias_head.with_dot", handle_normal)]) - del ns['alias_cmd'] - del ns['alias_head'] - -ip.options.autocall = 1 - - - - -# Autocall -# ======== - -# For all the tests below, 'len' is callable / 'thing' is not - -# Objects which are instances of IPyAutocall are *always* autocalled -import IPython.ipapi -class Autocallable(IPython.ipapi.IPyAutocall): - def __call__(self): - return "called" - -autocallable = Autocallable() -ip.to_user_ns('autocallable') - - -# First, with autocalling fully off -ip.options.autocall = 0 -run_handler_tests( [ - # With no escapes, no autocalling expansions happen, callable or not, - # unless the obj extends IPyAutocall - ( 'len autocall_0', handle_normal), - ( 'thing autocall_0', handle_normal), - ( 'autocallable', handle_auto), - - # With explicit escapes, callable and non-callables both get expanded, - # regardless of the %autocall setting: - ( '/len autocall_0', handle_auto), - ( ',len autocall_0 b0', handle_auto), - ( ';len autocall_0 b0', handle_auto), - - ( '/thing autocall_0', handle_auto), - ( ',thing autocall_0 b0', handle_auto), - ( ';thing autocall_0 b0', handle_auto), - - # Explicit autocall should not trigger if there is leading whitespace - ( ' /len autocall_0', handle_normal), - ( ' ;len autocall_0', handle_normal), - ( ' ,len autocall_0', handle_normal), - ( ' / len autocall_0', handle_normal), - - # But should work if the whitespace comes after the esc char - ( '/ len autocall_0', handle_auto), - ( '; len autocall_0', handle_auto), - ( ', len autocall_0', handle_auto), - ( '/ len autocall_0', handle_auto), - ]) - - -# Now, with autocall in default, 'smart' mode -ip.options.autocall = 1 -run_handler_tests( [ - # Autocalls without escapes -- only expand if it's callable - ( 'len a1', handle_auto), - ( 'thing a1', handle_normal), - ( 'autocallable', handle_auto), - - # As above, all explicit escapes generate auto-calls, callable or not - ( '/len a1', handle_auto), - ( ',len a1 b1', handle_auto), - ( ';len a1 b1', handle_auto), - ( '/thing a1', handle_auto), - ( ',thing a1 b1', handle_auto), - ( ';thing a1 b1', handle_auto), - - # Autocalls only happen on things which look like funcs, even if - # explicitly requested. Which, in this case means they look like a - # sequence of identifiers and . attribute references. Possibly the - # second of these two should trigger handle_auto. But not for now. - ( '"abc".join range(4)', handle_normal), - ( '/"abc".join range(4)', handle_normal), - ]) - - -# No tests for autocall = 2, since the extra magic there happens inside the -# handle_auto function, which our test doesn't examine. - -# Note that we leave autocall in default, 1, 'smart' mode - - -# Autocall / Binary operators -# ========================== - -# Even with autocall on, 'len in thing' won't transform. -# But ';len in thing' will - -# Note, the tests below don't check for multi-char ops. It could. - -# XXX % is a binary op and should be in the list, too, but fails -bin_ops = list(r'<>,&^|*/+-') + 'is not in and or'.split() -bin_tests = [] -for b in bin_ops: - bin_tests.append(('len %s binop_autocall' % b, handle_normal)) - bin_tests.append((';len %s binop_autocall' % b, handle_auto)) - bin_tests.append((',len %s binop_autocall' % b, handle_auto)) - bin_tests.append(('/len %s binop_autocall' % b, handle_auto)) - -# Who loves auto-generating tests? -run_handler_tests(bin_tests) - - -# Possibly add tests for namespace shadowing (really ofind's business?). -# -# user > ipython internal > python builtin > alias > magic - - -# ============ -# Test Summary -# ============ -num_f = len(failures) -if verbose: - print -print "%s tests run, %s failure%s" % (num_tests, - num_f, - num_f != 1 and "s" or "") -for f in failures: - print f - diff --git a/IPython/deathrow/twshell.py b/IPython/deathrow/twshell.py deleted file mode 100644 index e724239..0000000 --- a/IPython/deathrow/twshell.py +++ /dev/null @@ -1,287 +0,0 @@ -"""Twisted shell support. - -XXX - This module is missing proper docs. -""" -# Tell nose to skip this module -__test__ = {} - -import sys - -from twisted.internet import reactor, threads - -from IPython.core.ipmaker import make_IPython -from IPython.core.iplib import InteractiveShell -from IPython.utils.ipstruct import Struct -import Queue,thread,threading,signal -from signal import signal, SIGINT -import IPython.utils.io, ask_yes_no -from IPython.utils.warn import warn, error -from IPython.utils.decorators import flag_calls -from IPython.core import shellglobals - -def install_gtk2(): - """ Install gtk2 reactor, needs to be called bef """ - from twisted.internet import gtk2reactor - gtk2reactor.install() - - -def hijack_reactor(): - """Modifies Twisted's reactor with a dummy so user code does - not block IPython. This function returns the original - 'twisted.internet.reactor' that has been hijacked. - - NOTE: Make sure you call this *AFTER* you've installed - the reactor of your choice. - """ - from twisted import internet - orig_reactor = internet.reactor - - class DummyReactor(object): - def run(self): - pass - def __getattr__(self, name): - return getattr(orig_reactor, name) - def __setattr__(self, name, value): - return setattr(orig_reactor, name, value) - - internet.reactor = DummyReactor() - return orig_reactor - -class TwistedInteractiveShell(InteractiveShell): - """Simple multi-threaded shell.""" - - # Threading strategy taken from: - # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian - # McErlean and John Finlay. Modified with corrections by Antoon Pardon, - # from the pygtk mailing list, to avoid lockups with system calls. - - # class attribute to indicate whether the class supports threads or not. - # Subclasses with thread support should override this as needed. - isthreaded = True - - def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), - user_ns=None,user_global_ns=None,banner2='',**kw): - """Similar to the normal InteractiveShell, but with threading control""" - - InteractiveShell.__init__(self,name,usage,rc,user_ns, - user_global_ns,banner2) - - - # A queue to hold the code to be executed. - self.code_queue = Queue.Queue() - - # Stuff to do at closing time - self._kill = None - on_kill = kw.get('on_kill', []) - # Check that all things to kill are callable: - for t in on_kill: - if not callable(t): - raise TypeError,'on_kill must be a list of callables' - self.on_kill = on_kill - # thread identity of the "worker thread" (that may execute code directly) - self.worker_ident = None - self.reactor_started = False - self.first_run = True - - def runsource(self, source, filename="<input>", symbol="single"): - """Compile and run some source in the interpreter. - - Modified version of code.py's runsource(), to handle threading issues. - See the original for full docstring details.""" - - # If Ctrl-C was typed, we reset the flag and return right away - if shellglobals.KBINT: - shellglobals.KBINT = False - return False - - if self._kill: - # can't queue new code if we are being killed - return True - - try: - code = self.compile(source, filename, symbol) - except (OverflowError, SyntaxError, ValueError): - # Case 1 - self.showsyntaxerror(filename) - return False - - if code is None: - # Case 2 - return True - - # shortcut - if we are in worker thread, or the worker thread is not running, - # execute directly (to allow recursion and prevent deadlock if code is run early - # in IPython construction) - - if (not self.reactor_started or (self.worker_ident is None and not self.first_run) - or self.worker_ident == thread.get_ident() or shellglobals.run_in_frontend(source)): - InteractiveShell.runcode(self,code) - return - - # Case 3 - # Store code in queue, so the execution thread can handle it. - - self.first_run = False - completed_ev, received_ev = threading.Event(), threading.Event() - - self.code_queue.put((code,completed_ev, received_ev)) - - reactor.callLater(0.0,self.runcode) - received_ev.wait(5) - if not received_ev.isSet(): - # the mainloop is dead, start executing code directly - print "Warning: Timeout for mainloop thread exceeded" - print "switching to nonthreaded mode (until mainloop wakes up again)" - self.worker_ident = None - else: - completed_ev.wait() - - return False - - def runcode(self): - """Execute a code object. - - Multithreaded wrapper around IPython's runcode().""" - - - # we are in worker thread, stash out the id for runsource() - self.worker_ident = thread.get_ident() - - if self._kill: - print >>Term.cout, 'Closing threads...', - Term.cout.flush() - for tokill in self.on_kill: - tokill() - print >>Term.cout, 'Done.' - # allow kill() to return - self._kill.set() - return True - - # Install SIGINT handler. We do it every time to ensure that if user - # code modifies it, we restore our own handling. - try: - pass - signal(SIGINT,shellglobals.sigint_handler) - except SystemError: - # This happens under Windows, which seems to have all sorts - # of problems with signal handling. Oh well... - pass - - # Flush queue of pending code by calling the run methood of the parent - # class with all items which may be in the queue. - code_to_run = None - while 1: - try: - code_to_run, completed_ev, received_ev = self.code_queue.get_nowait() - except Queue.Empty: - break - received_ev.set() - - - # Exceptions need to be raised differently depending on which - # thread is active. This convoluted try/except is only there to - # protect against asynchronous exceptions, to ensure that a shellglobals.KBINT - # at the wrong time doesn't deadlock everything. The global - # CODE_TO_RUN is set to true/false as close as possible to the - # runcode() call, so that the KBINT handler is correctly informed. - try: - try: - shellglobals.CODE_RUN = True - InteractiveShell.runcode(self,code_to_run) - except KeyboardInterrupt: - print "Keyboard interrupted in mainloop" - while not self.code_queue.empty(): - code = self.code_queue.get_nowait() - break - finally: - shellglobals.CODE_RUN = False - # allow runsource() return from wait - completed_ev.set() - - # This MUST return true for gtk threading to work - return True - - def kill(self): - """Kill the thread, returning when it has been shut down.""" - self._kill = threading.Event() - reactor.callLater(0.0,self.runcode) - self._kill.wait() - - - -class IPShellTwisted: - """Run a Twisted reactor while in an IPython session. - - Python commands can be passed to the thread where they will be - executed. This is implemented by periodically checking for - passed code using a Twisted reactor callback. - """ - - TIMEOUT = 0.01 # Millisecond interval between reactor runs. - - def __init__(self, argv=None, user_ns=None, debug=1, - shell_class=TwistedInteractiveShell): - - from twisted.internet import reactor - self.reactor = hijack_reactor() - - mainquit = self.reactor.stop - - # Make sure IPython keeps going after reactor stop. - def reactorstop(): - pass - self.reactor.stop = reactorstop - reactorrun_orig = self.reactor.run - self.quitting = False - def reactorrun(): - while True and not self.quitting: - reactorrun_orig() - self.reactor.run = reactorrun - - self.IP = make_IPython(argv, user_ns=user_ns, debug=debug, - shell_class=shell_class, - on_kill=[mainquit]) - - # threading.Thread.__init__(self) - - def run(self): - self.IP.mainloop() - self.quitting = True - self.IP.kill() - - def mainloop(self): - def mainLoopThreadDeath(r): - print "mainLoopThreadDeath: ", str(r) - def spawnMainloopThread(): - d=threads.deferToThread(self.run) - d.addBoth(mainLoopThreadDeath) - reactor.callWhenRunning(spawnMainloopThread) - self.IP.reactor_started = True - self.reactor.run() - print "mainloop ending...." - -exists = True - - -if __name__ == '__main__': - # Sample usage. - - # Create the shell object. This steals twisted.internet.reactor - # for its own purposes, to make sure you've already installed a - # reactor of your choice. - shell = IPShellTwisted( - argv=[], - user_ns={'__name__': '__example__', - 'hello': 'world', - }, - ) - - # Run the mainloop. This runs the actual reactor.run() method. - # The twisted.internet.reactor object at this point is a dummy - # object that passes through to the actual reactor, but prevents - # run() from being called on it again. - shell.mainloop() - - # You must exit IPython to terminate your program. - print 'Goodbye!' - diff --git a/IPython/frontend.py b/IPython/frontend.py new file mode 100644 index 0000000..d2650de --- /dev/null +++ b/IPython/frontend.py @@ -0,0 +1,79 @@ +""" +Shim to maintain backwards compatibility with old frontend imports. + +We have moved all contents of the old `frontend` subpackage into top-level +subpackages (`html`, `qt` and `terminal`), and flattened the notebook into +just `IPython.html`, formerly `IPython.frontend.html.notebook`. + +This will let code that was making `from IPython.frontend...` calls continue +working, though a warning will be printed. +""" + +#----------------------------------------------------------------------------- +# Copyright (c) 2013, IPython Development Team. +# +# Distributed under the terms of the Modified BSD License. +# +# The full license is in the file COPYING.txt, distributed with this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- +from __future__ import print_function + +# Stdlib +import sys +import types +from warnings import warn + +warn("The top-level `frontend` package has been deprecated. " + "All its subpackages have been moved to the top `IPython` level.") + +#----------------------------------------------------------------------------- +# Class declarations +#----------------------------------------------------------------------------- + +class ShimModule(types.ModuleType): + + def __init__(self, *args, **kwargs): + self._mirror = kwargs.pop("mirror") + super(ShimModule, self).__init__(*args, **kwargs) + + def __getattr__(self, key): + # Use the equivalent of import_item(name), see below + name = "%s.%s" % (self._mirror, key) + + # NOTE: the code below is copied *verbatim* from + # importstring.import_item. For some very strange reason that makes no + # sense to me, if we call it *as a function*, it doesn't work. This + # has something to do with the deep bowels of the import machinery and + # I couldn't find a way to make the code work as a standard function + # call. But at least since it's an unmodified copy of import_item, + # which is used extensively and has a test suite, we can be reasonably + # confident this is OK. If anyone finds how to call the function, all + # the below could be replaced simply with: + # + # from IPython.utils.importstring import import_item + # return import_item('MIRROR.' + key) + + parts = name.rsplit('.', 1) + if len(parts) == 2: + # called with 'foo.bar....' + package, obj = parts + module = __import__(package, fromlist=[obj]) + try: + pak = module.__dict__[obj] + except KeyError: + raise ImportError('No module named %s' % obj) + return pak + else: + # called with un-dotted string + return __import__(parts[0]) + + +# Unconditionally insert the shim into sys.modules so that further import calls +# trigger the custom attribute access above + +sys.modules['IPython.frontend.html.notebook'] = ShimModule('notebook', mirror='IPython.html') +sys.modules['IPython.frontend'] = ShimModule('frontend', mirror='IPython') diff --git a/IPython/frontend/html/notebook/services/notebooks/tests/__init__.py b/IPython/frontend/html/notebook/services/notebooks/tests/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/IPython/frontend/html/notebook/services/notebooks/tests/__init__.py +++ /dev/null diff --git a/IPython/frontend/html/notebook/static/components b/IPython/frontend/html/notebook/static/components deleted file mode 160000 index 2a98f49..0000000 --- a/IPython/frontend/html/notebook/static/components +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 2a98f498092682f11affe9b0b86bd7e642cf7b13 diff --git a/IPython/frontend/html/notebook/tests/__init__.py b/IPython/frontend/html/notebook/tests/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/IPython/frontend/html/notebook/tests/__init__.py +++ /dev/null diff --git a/IPython/frontend/html/notebook/tree/__init__.py b/IPython/frontend/html/notebook/tree/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/IPython/frontend/html/notebook/tree/__init__.py +++ /dev/null diff --git a/IPython/frontend/qt/__init__.py b/IPython/frontend/qt/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/IPython/frontend/qt/__init__.py +++ /dev/null diff --git a/IPython/frontend/qt/console/__init__.py b/IPython/frontend/qt/console/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/IPython/frontend/qt/console/__init__.py +++ /dev/null diff --git a/IPython/frontend/qt/console/tests/__init__.py b/IPython/frontend/qt/console/tests/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/IPython/frontend/qt/console/tests/__init__.py +++ /dev/null diff --git a/IPython/frontend/terminal/__init__.py b/IPython/frontend/terminal/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/IPython/frontend/terminal/__init__.py +++ /dev/null diff --git a/IPython/frontend/terminal/console/__init__.py b/IPython/frontend/terminal/console/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/IPython/frontend/terminal/console/__init__.py +++ /dev/null diff --git a/IPython/frontend/terminal/console/tests/__init__.py b/IPython/frontend/terminal/console/tests/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/IPython/frontend/terminal/console/tests/__init__.py +++ /dev/null diff --git a/IPython/frontend/terminal/tests/__init__.py b/IPython/frontend/terminal/tests/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/IPython/frontend/terminal/tests/__init__.py +++ /dev/null diff --git a/IPython/frontend/html/notebook/README.md b/IPython/html/README.md similarity index 96% rename from IPython/frontend/html/notebook/README.md rename to IPython/html/README.md index e528167..cbb20a1 100644 --- a/IPython/frontend/html/notebook/README.md +++ b/IPython/html/README.md @@ -54,7 +54,7 @@ wide install. First, cd into js directory : ```bash -cd IPython/frontend/html/notebook/static/js/ +cd IPython/html/static/js/ # install yuidoc npm install yuidocjs ``` @@ -62,7 +62,7 @@ npm install yuidocjs ### Run YUIdoc server -From IPython/frontend/html/notebook/static/js/ +From IPython/html/static/js/ ```bash # run yuidoc for install dir ./node_modules/yuidocjs/lib/cli.js --server . @@ -70,4 +70,4 @@ From IPython/frontend/html/notebook/static/js/ Follow the instruction and the documentation should be available on localhost:3000 -Omitting `--server` will build a static version in the `out` folder by default. \ No newline at end of file +Omitting `--server` will build a static version in the `out` folder by default. diff --git a/IPython/frontend/html/notebook/__init__.py b/IPython/html/__init__.py similarity index 100% rename from IPython/frontend/html/notebook/__init__.py rename to IPython/html/__init__.py diff --git a/IPython/deathrow/__init__.py b/IPython/html/auth/__init__.py similarity index 100% rename from IPython/deathrow/__init__.py rename to IPython/html/auth/__init__.py diff --git a/IPython/frontend/html/notebook/auth/login.py b/IPython/html/auth/login.py similarity index 100% rename from IPython/frontend/html/notebook/auth/login.py rename to IPython/html/auth/login.py diff --git a/IPython/frontend/html/notebook/auth/logout.py b/IPython/html/auth/logout.py similarity index 100% rename from IPython/frontend/html/notebook/auth/logout.py rename to IPython/html/auth/logout.py diff --git a/IPython/deathrow/gui/__init__.py b/IPython/html/base/__init__.py similarity index 100% rename from IPython/deathrow/gui/__init__.py rename to IPython/html/base/__init__.py diff --git a/IPython/frontend/html/notebook/base/handlers.py b/IPython/html/base/handlers.py similarity index 100% rename from IPython/frontend/html/notebook/base/handlers.py rename to IPython/html/base/handlers.py diff --git a/IPython/frontend/html/notebook/base/zmqhandlers.py b/IPython/html/base/zmqhandlers.py similarity index 100% rename from IPython/frontend/html/notebook/base/zmqhandlers.py rename to IPython/html/base/zmqhandlers.py diff --git a/IPython/frontend/html/notebook/fabfile.py b/IPython/html/fabfile.py similarity index 100% rename from IPython/frontend/html/notebook/fabfile.py rename to IPython/html/fabfile.py diff --git a/IPython/deathrow/gui/wx/__init__.py b/IPython/html/notebook/__init__.py similarity index 100% rename from IPython/deathrow/gui/wx/__init__.py rename to IPython/html/notebook/__init__.py diff --git a/IPython/frontend/html/notebook/notebook/handlers.py b/IPython/html/notebook/handlers.py similarity index 100% rename from IPython/frontend/html/notebook/notebook/handlers.py rename to IPython/html/notebook/handlers.py diff --git a/IPython/frontend/html/notebook/notebookapp.py b/IPython/html/notebookapp.py similarity index 97% rename from IPython/frontend/html/notebook/notebookapp.py rename to IPython/html/notebookapp.py index b833f62..91bcffe 100644 --- a/IPython/frontend/html/notebook/notebookapp.py +++ b/IPython/html/notebookapp.py @@ -34,7 +34,7 @@ import webbrowser # Third party # check for pyzmq 2.1.11 from IPython.utils.zmqrelated import check_for_zmq -check_for_zmq('2.1.11', 'IPython.frontend.html.notebook') +check_for_zmq('2.1.11', 'IPython.html') import zmq from jinja2 import Environment, FileSystemLoader @@ -61,7 +61,7 @@ from tornado import httpserver from tornado import web # Our own libraries -from IPython.frontend.html.notebook import DEFAULT_STATIC_FILES_PATH +from IPython.html import DEFAULT_STATIC_FILES_PATH from .services.kernels.kernelmanager import MappingKernelManager from .services.notebooks.nbmanager import NotebookManager @@ -72,7 +72,7 @@ from .base.handlers import AuthenticatedFileHandler, FileFindHandler from IPython.config.application import catch_config_error, boolean_flag from IPython.core.application import BaseIPythonApplication -from IPython.frontend.consoleapp import IPythonConsoleApp +from IPython.consoleapp import IPythonConsoleApp from IPython.kernel import swallow_argv from IPython.kernel.zmq.session import default_secure from IPython.kernel.zmq.kernelapp import ( @@ -120,7 +120,7 @@ def random_ports(port, n): def load_handlers(name): """Load the (URL pattern, handler) tuples for each component.""" - name = 'IPython.frontend.html.notebook.' + name + name = 'IPython.html.' + name mod = __import__(name, fromlist=['default_handlers']) return mod.default_handlers @@ -490,7 +490,7 @@ class NotebookApp(BaseIPythonApplication): else: self.log.info("Using MathJax: %s", new) - notebook_manager_class = DottedObjectName('IPython.frontend.html.notebook.services.notebooks.filenbmanager.FileNotebookManager', + notebook_manager_class = DottedObjectName('IPython.html.services.notebooks.filenbmanager.FileNotebookManager', config=True, help='The notebook manager class to use.') diff --git a/IPython/deathrow/oldfrontend/cocoa/__init__.py b/IPython/html/services/__init__.py similarity index 100% rename from IPython/deathrow/oldfrontend/cocoa/__init__.py rename to IPython/html/services/__init__.py diff --git a/IPython/deathrow/oldfrontend/cocoa/tests/__init__.py b/IPython/html/services/clusters/__init__.py similarity index 100% rename from IPython/deathrow/oldfrontend/cocoa/tests/__init__.py rename to IPython/html/services/clusters/__init__.py diff --git a/IPython/frontend/html/notebook/services/clusters/clustermanager.py b/IPython/html/services/clusters/clustermanager.py similarity index 100% rename from IPython/frontend/html/notebook/services/clusters/clustermanager.py rename to IPython/html/services/clusters/clustermanager.py diff --git a/IPython/frontend/html/notebook/services/clusters/handlers.py b/IPython/html/services/clusters/handlers.py similarity index 100% rename from IPython/frontend/html/notebook/services/clusters/handlers.py rename to IPython/html/services/clusters/handlers.py diff --git a/IPython/deathrow/oldfrontend/tests/__init__.py b/IPython/html/services/kernels/__init__.py similarity index 100% rename from IPython/deathrow/oldfrontend/tests/__init__.py rename to IPython/html/services/kernels/__init__.py diff --git a/IPython/frontend/html/notebook/services/kernels/handlers.py b/IPython/html/services/kernels/handlers.py similarity index 100% rename from IPython/frontend/html/notebook/services/kernels/handlers.py rename to IPython/html/services/kernels/handlers.py diff --git a/IPython/frontend/html/notebook/services/kernels/kernelmanager.py b/IPython/html/services/kernels/kernelmanager.py similarity index 100% rename from IPython/frontend/html/notebook/services/kernels/kernelmanager.py rename to IPython/html/services/kernels/kernelmanager.py diff --git a/IPython/deathrow/oldfrontend/wx/__init__.py b/IPython/html/services/notebooks/__init__.py similarity index 100% rename from IPython/deathrow/oldfrontend/wx/__init__.py rename to IPython/html/services/notebooks/__init__.py diff --git a/IPython/frontend/html/notebook/services/notebooks/azurenbmanager.py b/IPython/html/services/notebooks/azurenbmanager.py similarity index 100% rename from IPython/frontend/html/notebook/services/notebooks/azurenbmanager.py rename to IPython/html/services/notebooks/azurenbmanager.py diff --git a/IPython/frontend/html/notebook/services/notebooks/filenbmanager.py b/IPython/html/services/notebooks/filenbmanager.py similarity index 100% rename from IPython/frontend/html/notebook/services/notebooks/filenbmanager.py rename to IPython/html/services/notebooks/filenbmanager.py diff --git a/IPython/frontend/html/notebook/services/notebooks/handlers.py b/IPython/html/services/notebooks/handlers.py similarity index 100% rename from IPython/frontend/html/notebook/services/notebooks/handlers.py rename to IPython/html/services/notebooks/handlers.py diff --git a/IPython/frontend/html/notebook/services/notebooks/nbmanager.py b/IPython/html/services/notebooks/nbmanager.py similarity index 100% rename from IPython/frontend/html/notebook/services/notebooks/nbmanager.py rename to IPython/html/services/notebooks/nbmanager.py diff --git a/IPython/deathrow/tests/__init__.py b/IPython/html/services/notebooks/tests/__init__.py similarity index 100% rename from IPython/deathrow/tests/__init__.py rename to IPython/html/services/notebooks/tests/__init__.py diff --git a/IPython/frontend/html/notebook/services/notebooks/tests/test_nbmanager.py b/IPython/html/services/notebooks/tests/test_nbmanager.py similarity index 100% rename from IPython/frontend/html/notebook/services/notebooks/tests/test_nbmanager.py rename to IPython/html/services/notebooks/tests/test_nbmanager.py diff --git a/IPython/frontend/html/notebook/static/auth/css/override.css b/IPython/html/static/auth/css/override.css similarity index 100% rename from IPython/frontend/html/notebook/static/auth/css/override.css rename to IPython/html/static/auth/css/override.css diff --git a/IPython/frontend/html/notebook/static/auth/js/loginmain.js b/IPython/html/static/auth/js/loginmain.js similarity index 100% rename from IPython/frontend/html/notebook/static/auth/js/loginmain.js rename to IPython/html/static/auth/js/loginmain.js diff --git a/IPython/frontend/html/notebook/static/auth/js/loginwidget.js b/IPython/html/static/auth/js/loginwidget.js similarity index 100% rename from IPython/frontend/html/notebook/static/auth/js/loginwidget.js rename to IPython/html/static/auth/js/loginwidget.js diff --git a/IPython/frontend/html/notebook/static/auth/js/logoutmain.js b/IPython/html/static/auth/js/logoutmain.js similarity index 100% rename from IPython/frontend/html/notebook/static/auth/js/logoutmain.js rename to IPython/html/static/auth/js/logoutmain.js diff --git a/IPython/frontend/html/notebook/static/auth/less/login.less b/IPython/html/static/auth/less/login.less similarity index 100% rename from IPython/frontend/html/notebook/static/auth/less/login.less rename to IPython/html/static/auth/less/login.less diff --git a/IPython/frontend/html/notebook/static/auth/less/logout.less b/IPython/html/static/auth/less/logout.less similarity index 100% rename from IPython/frontend/html/notebook/static/auth/less/logout.less rename to IPython/html/static/auth/less/logout.less diff --git a/IPython/frontend/html/notebook/static/auth/less/style.less b/IPython/html/static/auth/less/style.less similarity index 100% rename from IPython/frontend/html/notebook/static/auth/less/style.less rename to IPython/html/static/auth/less/style.less diff --git a/IPython/frontend/html/notebook/static/base/css/boilerplate.css b/IPython/html/static/base/css/boilerplate.css similarity index 100% rename from IPython/frontend/html/notebook/static/base/css/boilerplate.css rename to IPython/html/static/base/css/boilerplate.css diff --git a/IPython/frontend/html/notebook/static/base/images/favicon.ico b/IPython/html/static/base/images/favicon.ico similarity index 100% rename from IPython/frontend/html/notebook/static/base/images/favicon.ico rename to IPython/html/static/base/images/favicon.ico Binary files a/IPython/frontend/html/notebook/static/base/images/favicon.ico and b/IPython/html/static/base/images/favicon.ico differ diff --git a/IPython/frontend/html/notebook/static/base/images/ipynblogo.png b/IPython/html/static/base/images/ipynblogo.png similarity index 100% rename from IPython/frontend/html/notebook/static/base/images/ipynblogo.png rename to IPython/html/static/base/images/ipynblogo.png Binary files a/IPython/frontend/html/notebook/static/base/images/ipynblogo.png and b/IPython/html/static/base/images/ipynblogo.png differ diff --git a/IPython/frontend/html/notebook/static/base/images/ipynblogo.svg b/IPython/html/static/base/images/ipynblogo.svg similarity index 100% rename from IPython/frontend/html/notebook/static/base/images/ipynblogo.svg rename to IPython/html/static/base/images/ipynblogo.svg diff --git a/IPython/frontend/html/notebook/static/base/js/dialog.js b/IPython/html/static/base/js/dialog.js similarity index 100% rename from IPython/frontend/html/notebook/static/base/js/dialog.js rename to IPython/html/static/base/js/dialog.js diff --git a/IPython/frontend/html/notebook/static/base/js/events.js b/IPython/html/static/base/js/events.js similarity index 100% rename from IPython/frontend/html/notebook/static/base/js/events.js rename to IPython/html/static/base/js/events.js diff --git a/IPython/frontend/html/notebook/static/base/js/namespace.js b/IPython/html/static/base/js/namespace.js similarity index 100% rename from IPython/frontend/html/notebook/static/base/js/namespace.js rename to IPython/html/static/base/js/namespace.js diff --git a/IPython/frontend/html/notebook/static/base/js/page.js b/IPython/html/static/base/js/page.js similarity index 100% rename from IPython/frontend/html/notebook/static/base/js/page.js rename to IPython/html/static/base/js/page.js diff --git a/IPython/frontend/html/notebook/static/base/js/pagemain.js b/IPython/html/static/base/js/pagemain.js similarity index 100% rename from IPython/frontend/html/notebook/static/base/js/pagemain.js rename to IPython/html/static/base/js/pagemain.js diff --git a/IPython/frontend/html/notebook/static/base/js/utils.js b/IPython/html/static/base/js/utils.js similarity index 100% rename from IPython/frontend/html/notebook/static/base/js/utils.js rename to IPython/html/static/base/js/utils.js diff --git a/IPython/frontend/html/notebook/static/base/less/flexbox.less b/IPython/html/static/base/less/flexbox.less similarity index 100% rename from IPython/frontend/html/notebook/static/base/less/flexbox.less rename to IPython/html/static/base/less/flexbox.less diff --git a/IPython/frontend/html/notebook/static/base/less/mixins.less b/IPython/html/static/base/less/mixins.less similarity index 100% rename from IPython/frontend/html/notebook/static/base/less/mixins.less rename to IPython/html/static/base/less/mixins.less diff --git a/IPython/frontend/html/notebook/static/base/less/page.less b/IPython/html/static/base/less/page.less similarity index 100% rename from IPython/frontend/html/notebook/static/base/less/page.less rename to IPython/html/static/base/less/page.less diff --git a/IPython/frontend/html/notebook/static/base/less/style.less b/IPython/html/static/base/less/style.less similarity index 100% rename from IPython/frontend/html/notebook/static/base/less/style.less rename to IPython/html/static/base/less/style.less diff --git a/IPython/frontend/html/notebook/static/base/less/variables.less b/IPython/html/static/base/less/variables.less similarity index 100% rename from IPython/frontend/html/notebook/static/base/less/variables.less rename to IPython/html/static/base/less/variables.less diff --git a/IPython/html/static/components b/IPython/html/static/components new file mode 160000 index 0000000..2a98f49 --- /dev/null +++ b/IPython/html/static/components @@ -0,0 +1 @@ +Subproject commit 2a98f498092682f11affe9b0b86bd7e642cf7b13 diff --git a/IPython/frontend/html/notebook/static/custom/custom.css b/IPython/html/static/custom/custom.css similarity index 100% rename from IPython/frontend/html/notebook/static/custom/custom.css rename to IPython/html/static/custom/custom.css diff --git a/IPython/frontend/html/notebook/static/custom/custom.js b/IPython/html/static/custom/custom.js similarity index 100% rename from IPython/frontend/html/notebook/static/custom/custom.js rename to IPython/html/static/custom/custom.js diff --git a/IPython/frontend/html/notebook/static/dateformat/date.format.js b/IPython/html/static/dateformat/date.format.js similarity index 100% rename from IPython/frontend/html/notebook/static/dateformat/date.format.js rename to IPython/html/static/dateformat/date.format.js diff --git a/IPython/frontend/html/notebook/static/notebook/css/override.css b/IPython/html/static/notebook/css/override.css similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/css/override.css rename to IPython/html/static/notebook/css/override.css diff --git a/IPython/frontend/html/notebook/static/notebook/js/cell.js b/IPython/html/static/notebook/js/cell.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/cell.js rename to IPython/html/static/notebook/js/cell.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/celltoolbar.js b/IPython/html/static/notebook/js/celltoolbar.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/celltoolbar.js rename to IPython/html/static/notebook/js/celltoolbar.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/celltoolbarpresets/default.js b/IPython/html/static/notebook/js/celltoolbarpresets/default.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/celltoolbarpresets/default.js rename to IPython/html/static/notebook/js/celltoolbarpresets/default.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/celltoolbarpresets/example.js b/IPython/html/static/notebook/js/celltoolbarpresets/example.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/celltoolbarpresets/example.js rename to IPython/html/static/notebook/js/celltoolbarpresets/example.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/celltoolbarpresets/slideshow.js b/IPython/html/static/notebook/js/celltoolbarpresets/slideshow.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/celltoolbarpresets/slideshow.js rename to IPython/html/static/notebook/js/celltoolbarpresets/slideshow.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/codecell.js b/IPython/html/static/notebook/js/codecell.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/codecell.js rename to IPython/html/static/notebook/js/codecell.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/codemirror-ipython.js b/IPython/html/static/notebook/js/codemirror-ipython.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/codemirror-ipython.js rename to IPython/html/static/notebook/js/codemirror-ipython.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/completer.js b/IPython/html/static/notebook/js/completer.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/completer.js rename to IPython/html/static/notebook/js/completer.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/config.js b/IPython/html/static/notebook/js/config.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/config.js rename to IPython/html/static/notebook/js/config.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/contexthint.js b/IPython/html/static/notebook/js/contexthint.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/contexthint.js rename to IPython/html/static/notebook/js/contexthint.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/layoutmanager.js b/IPython/html/static/notebook/js/layoutmanager.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/layoutmanager.js rename to IPython/html/static/notebook/js/layoutmanager.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/main.js b/IPython/html/static/notebook/js/main.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/main.js rename to IPython/html/static/notebook/js/main.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/maintoolbar.js b/IPython/html/static/notebook/js/maintoolbar.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/maintoolbar.js rename to IPython/html/static/notebook/js/maintoolbar.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/mathjaxutils.js b/IPython/html/static/notebook/js/mathjaxutils.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/mathjaxutils.js rename to IPython/html/static/notebook/js/mathjaxutils.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/menubar.js b/IPython/html/static/notebook/js/menubar.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/menubar.js rename to IPython/html/static/notebook/js/menubar.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/notebook.js b/IPython/html/static/notebook/js/notebook.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/notebook.js rename to IPython/html/static/notebook/js/notebook.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/notificationarea.js b/IPython/html/static/notebook/js/notificationarea.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/notificationarea.js rename to IPython/html/static/notebook/js/notificationarea.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/notificationwidget.js b/IPython/html/static/notebook/js/notificationwidget.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/notificationwidget.js rename to IPython/html/static/notebook/js/notificationwidget.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/outputarea.js b/IPython/html/static/notebook/js/outputarea.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/outputarea.js rename to IPython/html/static/notebook/js/outputarea.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/pager.js b/IPython/html/static/notebook/js/pager.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/pager.js rename to IPython/html/static/notebook/js/pager.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/quickhelp.js b/IPython/html/static/notebook/js/quickhelp.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/quickhelp.js rename to IPython/html/static/notebook/js/quickhelp.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/savewidget.js b/IPython/html/static/notebook/js/savewidget.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/savewidget.js rename to IPython/html/static/notebook/js/savewidget.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/textcell.js b/IPython/html/static/notebook/js/textcell.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/textcell.js rename to IPython/html/static/notebook/js/textcell.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/toolbar.js b/IPython/html/static/notebook/js/toolbar.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/toolbar.js rename to IPython/html/static/notebook/js/toolbar.js diff --git a/IPython/frontend/html/notebook/static/notebook/js/tooltip.js b/IPython/html/static/notebook/js/tooltip.js similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/js/tooltip.js rename to IPython/html/static/notebook/js/tooltip.js diff --git a/IPython/frontend/html/notebook/static/notebook/less/ansicolors.less b/IPython/html/static/notebook/less/ansicolors.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/ansicolors.less rename to IPython/html/static/notebook/less/ansicolors.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/cell.less b/IPython/html/static/notebook/less/cell.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/cell.less rename to IPython/html/static/notebook/less/cell.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/celltoolbar.less b/IPython/html/static/notebook/less/celltoolbar.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/celltoolbar.less rename to IPython/html/static/notebook/less/celltoolbar.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/codecell.less b/IPython/html/static/notebook/less/codecell.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/codecell.less rename to IPython/html/static/notebook/less/codecell.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/codemirror.less b/IPython/html/static/notebook/less/codemirror.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/codemirror.less rename to IPython/html/static/notebook/less/codemirror.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/completer.less b/IPython/html/static/notebook/less/completer.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/completer.less rename to IPython/html/static/notebook/less/completer.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/highlight.less b/IPython/html/static/notebook/less/highlight.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/highlight.less rename to IPython/html/static/notebook/less/highlight.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/menubar.less b/IPython/html/static/notebook/less/menubar.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/menubar.less rename to IPython/html/static/notebook/less/menubar.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/notebook.less b/IPython/html/static/notebook/less/notebook.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/notebook.less rename to IPython/html/static/notebook/less/notebook.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/notificationarea.less b/IPython/html/static/notebook/less/notificationarea.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/notificationarea.less rename to IPython/html/static/notebook/less/notificationarea.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/notificationwidget.less b/IPython/html/static/notebook/less/notificationwidget.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/notificationwidget.less rename to IPython/html/static/notebook/less/notificationwidget.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/outputarea.less b/IPython/html/static/notebook/less/outputarea.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/outputarea.less rename to IPython/html/static/notebook/less/outputarea.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/pager.less b/IPython/html/static/notebook/less/pager.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/pager.less rename to IPython/html/static/notebook/less/pager.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/quickhelp.less b/IPython/html/static/notebook/less/quickhelp.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/quickhelp.less rename to IPython/html/static/notebook/less/quickhelp.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/renderedhtml.less b/IPython/html/static/notebook/less/renderedhtml.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/renderedhtml.less rename to IPython/html/static/notebook/less/renderedhtml.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/savewidget.less b/IPython/html/static/notebook/less/savewidget.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/savewidget.less rename to IPython/html/static/notebook/less/savewidget.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/style.less b/IPython/html/static/notebook/less/style.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/style.less rename to IPython/html/static/notebook/less/style.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/textcell.less b/IPython/html/static/notebook/less/textcell.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/textcell.less rename to IPython/html/static/notebook/less/textcell.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/toolbar.less b/IPython/html/static/notebook/less/toolbar.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/toolbar.less rename to IPython/html/static/notebook/less/toolbar.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/tooltip.less b/IPython/html/static/notebook/less/tooltip.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/tooltip.less rename to IPython/html/static/notebook/less/tooltip.less diff --git a/IPython/frontend/html/notebook/static/notebook/less/variables.less b/IPython/html/static/notebook/less/variables.less similarity index 100% rename from IPython/frontend/html/notebook/static/notebook/less/variables.less rename to IPython/html/static/notebook/less/variables.less diff --git a/IPython/frontend/html/notebook/static/services/kernels/js/kernel.js b/IPython/html/static/services/kernels/js/kernel.js similarity index 100% rename from IPython/frontend/html/notebook/static/services/kernels/js/kernel.js rename to IPython/html/static/services/kernels/js/kernel.js diff --git a/IPython/frontend/html/notebook/static/style/style.less b/IPython/html/static/style/style.less similarity index 100% rename from IPython/frontend/html/notebook/static/style/style.less rename to IPython/html/static/style/style.less diff --git a/IPython/frontend/html/notebook/static/style/style.min.css b/IPython/html/static/style/style.min.css similarity index 100% rename from IPython/frontend/html/notebook/static/style/style.min.css rename to IPython/html/static/style/style.min.css diff --git a/IPython/frontend/html/notebook/static/tree/css/override.css b/IPython/html/static/tree/css/override.css similarity index 100% rename from IPython/frontend/html/notebook/static/tree/css/override.css rename to IPython/html/static/tree/css/override.css diff --git a/IPython/frontend/html/notebook/static/tree/js/clusterlist.js b/IPython/html/static/tree/js/clusterlist.js similarity index 100% rename from IPython/frontend/html/notebook/static/tree/js/clusterlist.js rename to IPython/html/static/tree/js/clusterlist.js diff --git a/IPython/frontend/html/notebook/static/tree/js/main.js b/IPython/html/static/tree/js/main.js similarity index 100% rename from IPython/frontend/html/notebook/static/tree/js/main.js rename to IPython/html/static/tree/js/main.js diff --git a/IPython/frontend/html/notebook/static/tree/js/notebooklist.js b/IPython/html/static/tree/js/notebooklist.js similarity index 100% rename from IPython/frontend/html/notebook/static/tree/js/notebooklist.js rename to IPython/html/static/tree/js/notebooklist.js diff --git a/IPython/frontend/html/notebook/static/tree/less/altuploadform.less b/IPython/html/static/tree/less/altuploadform.less similarity index 100% rename from IPython/frontend/html/notebook/static/tree/less/altuploadform.less rename to IPython/html/static/tree/less/altuploadform.less diff --git a/IPython/frontend/html/notebook/static/tree/less/style.less b/IPython/html/static/tree/less/style.less similarity index 100% rename from IPython/frontend/html/notebook/static/tree/less/style.less rename to IPython/html/static/tree/less/style.less diff --git a/IPython/frontend/html/notebook/static/tree/less/tree.less b/IPython/html/static/tree/less/tree.less similarity index 100% rename from IPython/frontend/html/notebook/static/tree/less/tree.less rename to IPython/html/static/tree/less/tree.less diff --git a/IPython/frontend/html/notebook/templates/login.html b/IPython/html/templates/login.html similarity index 100% rename from IPython/frontend/html/notebook/templates/login.html rename to IPython/html/templates/login.html diff --git a/IPython/frontend/html/notebook/templates/logout.html b/IPython/html/templates/logout.html similarity index 100% rename from IPython/frontend/html/notebook/templates/logout.html rename to IPython/html/templates/logout.html diff --git a/IPython/frontend/html/notebook/templates/notebook.html b/IPython/html/templates/notebook.html similarity index 100% rename from IPython/frontend/html/notebook/templates/notebook.html rename to IPython/html/templates/notebook.html diff --git a/IPython/frontend/html/notebook/templates/page.html b/IPython/html/templates/page.html similarity index 100% rename from IPython/frontend/html/notebook/templates/page.html rename to IPython/html/templates/page.html diff --git a/IPython/frontend/html/notebook/templates/tree.html b/IPython/html/templates/tree.html similarity index 100% rename from IPython/frontend/html/notebook/templates/tree.html rename to IPython/html/templates/tree.html diff --git a/IPython/frontend/__init__.py b/IPython/html/tests/__init__.py similarity index 100% rename from IPython/frontend/__init__.py rename to IPython/html/tests/__init__.py diff --git a/IPython/frontend/html/notebook/tests/test_hist.sqlite b/IPython/html/tests/test_hist.sqlite similarity index 100% rename from IPython/frontend/html/notebook/tests/test_hist.sqlite rename to IPython/html/tests/test_hist.sqlite Binary files a/IPython/frontend/html/notebook/tests/test_hist.sqlite and b/IPython/html/tests/test_hist.sqlite differ diff --git a/IPython/frontend/html/__init__.py b/IPython/html/tree/__init__.py similarity index 100% rename from IPython/frontend/html/__init__.py rename to IPython/html/tree/__init__.py diff --git a/IPython/frontend/html/notebook/tree/handlers.py b/IPython/html/tree/handlers.py similarity index 100% rename from IPython/frontend/html/notebook/tree/handlers.py rename to IPython/html/tree/handlers.py diff --git a/IPython/frontend/html/notebook/utils.py b/IPython/html/utils.py similarity index 100% rename from IPython/frontend/html/notebook/utils.py rename to IPython/html/utils.py diff --git a/IPython/kernel/connect.py b/IPython/kernel/connect.py index 0a431df..ae8e406 100644 --- a/IPython/kernel/connect.py +++ b/IPython/kernel/connect.py @@ -300,7 +300,7 @@ def connect_qtconsole(connection_file=None, argv=None, profile=None): cf = find_connection_file(connection_file, profile=profile) cmd = ';'.join([ - "from IPython.frontend.qt.console import qtconsoleapp", + "from IPython.qt.console import qtconsoleapp", "qtconsoleapp.main()" ]) diff --git a/IPython/frontend/html/notebook/auth/__init__.py b/IPython/qt/__init__.py similarity index 100% rename from IPython/frontend/html/notebook/auth/__init__.py rename to IPython/qt/__init__.py diff --git a/IPython/frontend/qt/base_frontend_mixin.py b/IPython/qt/base_frontend_mixin.py similarity index 100% rename from IPython/frontend/qt/base_frontend_mixin.py rename to IPython/qt/base_frontend_mixin.py diff --git a/IPython/frontend/qt/client.py b/IPython/qt/client.py similarity index 100% rename from IPython/frontend/qt/client.py rename to IPython/qt/client.py diff --git a/IPython/frontend/html/notebook/base/__init__.py b/IPython/qt/console/__init__.py similarity index 100% rename from IPython/frontend/html/notebook/base/__init__.py rename to IPython/qt/console/__init__.py diff --git a/IPython/frontend/qt/console/ansi_code_processor.py b/IPython/qt/console/ansi_code_processor.py similarity index 100% rename from IPython/frontend/qt/console/ansi_code_processor.py rename to IPython/qt/console/ansi_code_processor.py diff --git a/IPython/frontend/qt/console/bracket_matcher.py b/IPython/qt/console/bracket_matcher.py similarity index 100% rename from IPython/frontend/qt/console/bracket_matcher.py rename to IPython/qt/console/bracket_matcher.py diff --git a/IPython/frontend/qt/console/call_tip_widget.py b/IPython/qt/console/call_tip_widget.py similarity index 100% rename from IPython/frontend/qt/console/call_tip_widget.py rename to IPython/qt/console/call_tip_widget.py diff --git a/IPython/frontend/qt/console/completion_html.py b/IPython/qt/console/completion_html.py similarity index 100% rename from IPython/frontend/qt/console/completion_html.py rename to IPython/qt/console/completion_html.py diff --git a/IPython/frontend/qt/console/completion_lexer.py b/IPython/qt/console/completion_lexer.py similarity index 100% rename from IPython/frontend/qt/console/completion_lexer.py rename to IPython/qt/console/completion_lexer.py diff --git a/IPython/frontend/qt/console/completion_plain.py b/IPython/qt/console/completion_plain.py similarity index 100% rename from IPython/frontend/qt/console/completion_plain.py rename to IPython/qt/console/completion_plain.py diff --git a/IPython/frontend/qt/console/completion_widget.py b/IPython/qt/console/completion_widget.py similarity index 100% rename from IPython/frontend/qt/console/completion_widget.py rename to IPython/qt/console/completion_widget.py diff --git a/IPython/frontend/qt/console/console_widget.py b/IPython/qt/console/console_widget.py similarity index 98% rename from IPython/frontend/qt/console/console_widget.py rename to IPython/qt/console/console_widget.py index ea68ea3..05ac076 100644 --- a/IPython/frontend/qt/console/console_widget.py +++ b/IPython/qt/console/console_widget.py @@ -18,8 +18,8 @@ from IPython.external.qt import QtCore, QtGui # Local imports from IPython.config.configurable import LoggingConfigurable from IPython.core.inputsplitter import ESC_SEQUENCES -from IPython.frontend.qt.rich_text import HtmlExporter -from IPython.frontend.qt.util import MetaQObjectHasTraits, get_font +from IPython.qt.rich_text import HtmlExporter +from IPython.qt.util import MetaQObjectHasTraits, get_font from IPython.utils.text import columnize from IPython.utils.traitlets import Bool, Enum, Integer, Unicode from ansi_code_processor import QtAnsiCodeProcessor diff --git a/IPython/frontend/qt/console/frontend_widget.py b/IPython/qt/console/frontend_widget.py similarity index 99% rename from IPython/frontend/qt/console/frontend_widget.py rename to IPython/qt/console/frontend_widget.py index d36b628..2b9b6e8 100644 --- a/IPython/frontend/qt/console/frontend_widget.py +++ b/IPython/qt/console/frontend_widget.py @@ -15,7 +15,7 @@ from IPython.external.qt import QtCore, QtGui from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter from IPython.core.inputtransformer import classic_prompt from IPython.core.oinspect import call_tip -from IPython.frontend.qt.base_frontend_mixin import BaseFrontendMixin +from IPython.qt.base_frontend_mixin import BaseFrontendMixin from IPython.utils.traitlets import Bool, Instance, Unicode from bracket_matcher import BracketMatcher from call_tip_widget import CallTipWidget diff --git a/IPython/frontend/qt/console/history_console_widget.py b/IPython/qt/console/history_console_widget.py similarity index 100% rename from IPython/frontend/qt/console/history_console_widget.py rename to IPython/qt/console/history_console_widget.py diff --git a/IPython/frontend/qt/console/ipython_widget.py b/IPython/qt/console/ipython_widget.py similarity index 100% rename from IPython/frontend/qt/console/ipython_widget.py rename to IPython/qt/console/ipython_widget.py diff --git a/IPython/frontend/qt/console/kill_ring.py b/IPython/qt/console/kill_ring.py similarity index 100% rename from IPython/frontend/qt/console/kill_ring.py rename to IPython/qt/console/kill_ring.py diff --git a/IPython/frontend/qt/console/mainwindow.py b/IPython/qt/console/mainwindow.py similarity index 100% rename from IPython/frontend/qt/console/mainwindow.py rename to IPython/qt/console/mainwindow.py diff --git a/IPython/frontend/qt/console/pygments_highlighter.py b/IPython/qt/console/pygments_highlighter.py similarity index 100% rename from IPython/frontend/qt/console/pygments_highlighter.py rename to IPython/qt/console/pygments_highlighter.py diff --git a/IPython/frontend/qt/console/qtconsoleapp.py b/IPython/qt/console/qtconsoleapp.py similarity index 93% rename from IPython/frontend/qt/console/qtconsoleapp.py rename to IPython/qt/console/qtconsoleapp.py index f377ddd..1636d15 100644 --- a/IPython/frontend/qt/console/qtconsoleapp.py +++ b/IPython/qt/console/qtconsoleapp.py @@ -57,19 +57,19 @@ from IPython.external.qt import QtCore, QtGui from IPython.config.application import boolean_flag, catch_config_error from IPython.core.application import BaseIPythonApplication from IPython.core.profiledir import ProfileDir -from IPython.frontend.qt.console.ipython_widget import IPythonWidget -from IPython.frontend.qt.console.rich_ipython_widget import RichIPythonWidget -from IPython.frontend.qt.console import styles -from IPython.frontend.qt.console.mainwindow import MainWindow -from IPython.frontend.qt.client import QtKernelClient -from IPython.frontend.qt.manager import QtKernelManager +from IPython.qt.console.ipython_widget import IPythonWidget +from IPython.qt.console.rich_ipython_widget import RichIPythonWidget +from IPython.qt.console import styles +from IPython.qt.console.mainwindow import MainWindow +from IPython.qt.client import QtKernelClient +from IPython.qt.manager import QtKernelManager from IPython.kernel import tunnel_to_kernel, find_connection_file from IPython.utils.traitlets import ( Dict, List, Unicode, CBool, Any ) from IPython.kernel.zmq.session import default_secure -from IPython.frontend.consoleapp import ( +from IPython.consoleapp import ( IPythonConsoleApp, app_aliases, app_flags, flags, aliases ) diff --git a/IPython/frontend/qt/console/resources/icon/IPythonConsole.svg b/IPython/qt/console/resources/icon/IPythonConsole.svg similarity index 100% rename from IPython/frontend/qt/console/resources/icon/IPythonConsole.svg rename to IPython/qt/console/resources/icon/IPythonConsole.svg diff --git a/IPython/frontend/qt/console/rich_ipython_widget.py b/IPython/qt/console/rich_ipython_widget.py similarity index 100% rename from IPython/frontend/qt/console/rich_ipython_widget.py rename to IPython/qt/console/rich_ipython_widget.py index 368eb28..bf2f85d 100644 --- a/IPython/frontend/qt/console/rich_ipython_widget.py +++ b/IPython/qt/console/rich_ipython_widget.py @@ -16,7 +16,7 @@ from IPython.external.qt import QtCore, QtGui # Local imports from IPython.utils.traitlets import Bool -from IPython.frontend.qt.svg import save_svg, svg_to_clipboard, svg_to_image +from IPython.qt.svg import save_svg, svg_to_clipboard, svg_to_image from ipython_widget import IPythonWidget diff --git a/IPython/frontend/qt/console/styles.py b/IPython/qt/console/styles.py similarity index 100% rename from IPython/frontend/qt/console/styles.py rename to IPython/qt/console/styles.py diff --git a/IPython/frontend/html/notebook/notebook/__init__.py b/IPython/qt/console/tests/__init__.py similarity index 100% rename from IPython/frontend/html/notebook/notebook/__init__.py rename to IPython/qt/console/tests/__init__.py diff --git a/IPython/frontend/qt/console/tests/test_ansi_code_processor.py b/IPython/qt/console/tests/test_ansi_code_processor.py similarity index 99% rename from IPython/frontend/qt/console/tests/test_ansi_code_processor.py rename to IPython/qt/console/tests/test_ansi_code_processor.py index 0e8de98..06752fb 100644 --- a/IPython/frontend/qt/console/tests/test_ansi_code_processor.py +++ b/IPython/qt/console/tests/test_ansi_code_processor.py @@ -2,7 +2,7 @@ import unittest # Local imports -from IPython.frontend.qt.console.ansi_code_processor import AnsiCodeProcessor +from IPython.qt.console.ansi_code_processor import AnsiCodeProcessor class TestAnsiCodeProcessor(unittest.TestCase): diff --git a/IPython/frontend/qt/console/tests/test_completion_lexer.py b/IPython/qt/console/tests/test_completion_lexer.py similarity index 96% rename from IPython/frontend/qt/console/tests/test_completion_lexer.py rename to IPython/qt/console/tests/test_completion_lexer.py index 6c948c6..70c9174 100644 --- a/IPython/frontend/qt/console/tests/test_completion_lexer.py +++ b/IPython/qt/console/tests/test_completion_lexer.py @@ -5,7 +5,7 @@ import unittest from pygments.lexers import CLexer, CppLexer, PythonLexer # Local imports -from IPython.frontend.qt.console.completion_lexer import CompletionLexer +from IPython.qt.console.completion_lexer import CompletionLexer class TestCompletionLexer(unittest.TestCase): diff --git a/IPython/frontend/qt/console/tests/test_console_widget.py b/IPython/qt/console/tests/test_console_widget.py similarity index 98% rename from IPython/frontend/qt/console/tests/test_console_widget.py rename to IPython/qt/console/tests/test_console_widget.py index 9f24820..cd86c2a 100644 --- a/IPython/frontend/qt/console/tests/test_console_widget.py +++ b/IPython/qt/console/tests/test_console_widget.py @@ -5,7 +5,7 @@ import unittest from IPython.external.qt import QtCore, QtGui # Local imports -from IPython.frontend.qt.console.console_widget import ConsoleWidget +from IPython.qt.console.console_widget import ConsoleWidget class TestConsoleWidget(unittest.TestCase): diff --git a/IPython/frontend/qt/console/tests/test_kill_ring.py b/IPython/qt/console/tests/test_kill_ring.py similarity index 98% rename from IPython/frontend/qt/console/tests/test_kill_ring.py rename to IPython/qt/console/tests/test_kill_ring.py index 32c41c6..d32d045 100644 --- a/IPython/frontend/qt/console/tests/test_kill_ring.py +++ b/IPython/qt/console/tests/test_kill_ring.py @@ -5,7 +5,7 @@ import unittest from IPython.external.qt import QtCore, QtGui # Local imports -from IPython.frontend.qt.console.kill_ring import KillRing, QtKillRing +from IPython.qt.console.kill_ring import KillRing, QtKillRing class TestKillRing(unittest.TestCase): diff --git a/IPython/frontend/qt/inprocess.py b/IPython/qt/inprocess.py similarity index 100% rename from IPython/frontend/qt/inprocess.py rename to IPython/qt/inprocess.py diff --git a/IPython/frontend/qt/kernel_mixins.py b/IPython/qt/kernel_mixins.py similarity index 100% rename from IPython/frontend/qt/kernel_mixins.py rename to IPython/qt/kernel_mixins.py diff --git a/IPython/frontend/qt/manager.py b/IPython/qt/manager.py similarity index 100% rename from IPython/frontend/qt/manager.py rename to IPython/qt/manager.py diff --git a/IPython/frontend/qt/rich_text.py b/IPython/qt/rich_text.py similarity index 100% rename from IPython/frontend/qt/rich_text.py rename to IPython/qt/rich_text.py diff --git a/IPython/frontend/qt/svg.py b/IPython/qt/svg.py similarity index 100% rename from IPython/frontend/qt/svg.py rename to IPython/qt/svg.py diff --git a/IPython/frontend/qt/util.py b/IPython/qt/util.py similarity index 100% rename from IPython/frontend/qt/util.py rename to IPython/qt/util.py diff --git a/IPython/scripts/ipython b/IPython/scripts/ipython index b435148..2aed24c 100755 --- a/IPython/scripts/ipython +++ b/IPython/scripts/ipython @@ -2,6 +2,6 @@ """Terminal-based IPython entry point. """ -from IPython.frontend.terminal.ipapp import launch_new_instance +from IPython.terminal.ipapp import launch_new_instance launch_new_instance() diff --git a/IPython/frontend/html/notebook/services/__init__.py b/IPython/terminal/__init__.py similarity index 100% rename from IPython/frontend/html/notebook/services/__init__.py rename to IPython/terminal/__init__.py diff --git a/IPython/frontend/html/notebook/services/clusters/__init__.py b/IPython/terminal/console/__init__.py similarity index 100% rename from IPython/frontend/html/notebook/services/clusters/__init__.py rename to IPython/terminal/console/__init__.py diff --git a/IPython/frontend/terminal/console/app.py b/IPython/terminal/console/app.py similarity index 95% rename from IPython/frontend/terminal/console/app.py rename to IPython/terminal/console/app.py index bc60879..8381f1f 100644 --- a/IPython/frontend/terminal/console/app.py +++ b/IPython/terminal/console/app.py @@ -17,7 +17,7 @@ import signal import sys import time -from IPython.frontend.terminal.ipapp import TerminalIPythonApp, frontend_flags as term_flags +from IPython.terminal.ipapp import TerminalIPythonApp, frontend_flags as term_flags from IPython.utils.traitlets import ( Dict, List, Unicode, Int, CaselessStrEnum, CBool, Any @@ -27,11 +27,11 @@ from IPython.utils.warn import warn,error from IPython.kernel.zmq.kernelapp import IPKernelApp from IPython.kernel.zmq.session import Session, default_secure from IPython.kernel.zmq.zmqshell import ZMQInteractiveShell -from IPython.frontend.consoleapp import ( +from IPython.consoleapp import ( IPythonConsoleApp, app_aliases, app_flags, aliases, app_aliases, flags ) -from IPython.frontend.terminal.console.interactiveshell import ZMQTerminalInteractiveShell +from IPython.terminal.console.interactiveshell import ZMQTerminalInteractiveShell #----------------------------------------------------------------------------- # Globals diff --git a/IPython/frontend/terminal/console/completer.py b/IPython/terminal/console/completer.py similarity index 100% rename from IPython/frontend/terminal/console/completer.py rename to IPython/terminal/console/completer.py diff --git a/IPython/frontend/terminal/console/interactiveshell.py b/IPython/terminal/console/interactiveshell.py similarity index 99% rename from IPython/frontend/terminal/console/interactiveshell.py rename to IPython/terminal/console/interactiveshell.py index c723fcb..095b6a8 100644 --- a/IPython/frontend/terminal/console/interactiveshell.py +++ b/IPython/terminal/console/interactiveshell.py @@ -37,8 +37,8 @@ from IPython.utils import io from IPython.utils.traitlets import List, Enum, Any, Instance, Unicode from IPython.utils.tempdir import NamedFileInTemporaryDirectory -from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell -from IPython.frontend.terminal.console.completer import ZMQCompleter +from IPython.terminal.interactiveshell import TerminalInteractiveShell +from IPython.terminal.console.completer import ZMQCompleter class ZMQTerminalInteractiveShell(TerminalInteractiveShell): diff --git a/IPython/frontend/html/notebook/services/kernels/__init__.py b/IPython/terminal/console/tests/__init__.py similarity index 100% rename from IPython/frontend/html/notebook/services/kernels/__init__.py rename to IPython/terminal/console/tests/__init__.py diff --git a/IPython/frontend/terminal/console/tests/test_console.py b/IPython/terminal/console/tests/test_console.py similarity index 100% rename from IPython/frontend/terminal/console/tests/test_console.py rename to IPython/terminal/console/tests/test_console.py diff --git a/IPython/frontend/terminal/console/tests/test_image_handler.py b/IPython/terminal/console/tests/test_image_handler.py similarity index 97% rename from IPython/frontend/terminal/console/tests/test_image_handler.py rename to IPython/terminal/console/tests/test_image_handler.py index 21f615a..11e3852 100644 --- a/IPython/frontend/terminal/console/tests/test_image_handler.py +++ b/IPython/terminal/console/tests/test_image_handler.py @@ -11,8 +11,7 @@ import unittest import base64 from IPython.kernel import KernelClient -from IPython.frontend.terminal.console.interactiveshell \ - import ZMQTerminalInteractiveShell +from IPython.terminal.console.interactiveshell import ZMQTerminalInteractiveShell from IPython.utils.tempdir import TemporaryDirectory from IPython.testing.tools import monkeypatch from IPython.testing.decorators import skip_without diff --git a/IPython/frontend/terminal/console/tests/writetofile.py b/IPython/terminal/console/tests/writetofile.py similarity index 100% rename from IPython/frontend/terminal/console/tests/writetofile.py rename to IPython/terminal/console/tests/writetofile.py diff --git a/IPython/frontend/terminal/embed.py b/IPython/terminal/embed.py similarity index 98% rename from IPython/frontend/terminal/embed.py rename to IPython/terminal/embed.py index a831575..3b06bfc 100644 --- a/IPython/frontend/terminal/embed.py +++ b/IPython/terminal/embed.py @@ -36,8 +36,8 @@ except: from IPython.core import ultratb, compilerop from IPython.core.magic import Magics, magics_class, line_magic -from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell -from IPython.frontend.terminal.ipapp import load_default_config +from IPython.terminal.interactiveshell import TerminalInteractiveShell +from IPython.terminal.ipapp import load_default_config from IPython.utils.traitlets import Bool, CBool, Unicode from IPython.utils.io import ask_yes_no diff --git a/IPython/frontend/terminal/interactiveshell.py b/IPython/terminal/interactiveshell.py similarity index 100% rename from IPython/frontend/terminal/interactiveshell.py rename to IPython/terminal/interactiveshell.py diff --git a/IPython/frontend/terminal/ipapp.py b/IPython/terminal/ipapp.py similarity index 96% rename from IPython/frontend/terminal/ipapp.py rename to IPython/terminal/ipapp.py index 4b91670..4e7658f 100755 --- a/IPython/frontend/terminal/ipapp.py +++ b/IPython/terminal/ipapp.py @@ -47,7 +47,7 @@ from IPython.core.magics import ScriptMagics from IPython.core.shellapp import ( InteractiveShellApp, shell_flags, shell_aliases ) -from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell +from IPython.terminal.interactiveshell import TerminalInteractiveShell from IPython.utils import warn from IPython.utils.path import get_ipython_dir, check_for_old_config from IPython.utils.traitlets import ( @@ -223,10 +223,10 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): ] subcommands = Dict(dict( - qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp', + qtconsole=('IPython.qt.console.qtconsoleapp.IPythonQtConsoleApp', """Launch the IPython Qt Console.""" ), - notebook=('IPython.frontend.html.notebook.notebookapp.NotebookApp', + notebook=('IPython.html.notebookapp.NotebookApp', """Launch the IPython HTML Notebook Server.""" ), profile = ("IPython.core.profileapp.ProfileApp", @@ -235,10 +235,10 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): kernel = ("IPython.kernel.zmq.kernelapp.IPKernelApp", "Start a kernel without an attached frontend." ), - console=('IPython.frontend.terminal.console.app.ZMQTerminalIPythonApp', + console=('IPython.terminal.console.app.ZMQTerminalIPythonApp', """Launch the IPython terminal-based Console.""" ), - locate=('IPython.frontend.terminal.ipapp.LocateIPythonApp', + locate=('IPython.terminal.ipapp.LocateIPythonApp', LocateIPythonApp.description ), history=('IPython.core.historyapp.HistoryApp', diff --git a/IPython/frontend/html/notebook/services/notebooks/__init__.py b/IPython/terminal/tests/__init__.py similarity index 100% rename from IPython/frontend/html/notebook/services/notebooks/__init__.py rename to IPython/terminal/tests/__init__.py diff --git a/IPython/frontend/terminal/tests/test_interactivshell.py b/IPython/terminal/tests/test_interactivshell.py similarity index 100% rename from IPython/frontend/terminal/tests/test_interactivshell.py rename to IPython/terminal/tests/test_interactivshell.py diff --git a/IPython/testing/decorators.py b/IPython/testing/decorators.py index 5d9edcb..28d368f 100644 --- a/IPython/testing/decorators.py +++ b/IPython/testing/decorators.py @@ -128,15 +128,17 @@ def make_label_dec(label,ds=None): -------- A simple labeling decorator: - >>> slow = make_label_dec('slow') - >>> print slow.__doc__ - Labels a test as 'slow'. + >>> slow = make_label_dec('slow') + >>> slow.__doc__ + "Labels a test as 'slow'." + And one that uses multiple labels and a custom docstring: + >>> rare = make_label_dec(['slow','hard'], ... "Mix labels 'slow' and 'hard' for rare tests.") - >>> print rare.__doc__ - Mix labels 'slow' and 'hard' for rare tests. + >>> rare.__doc__ + "Mix labels 'slow' and 'hard' for rare tests." Now, let's test using this one: >>> @rare diff --git a/IPython/testing/globalipapp.py b/IPython/testing/globalipapp.py index b647801..861f575 100644 --- a/IPython/testing/globalipapp.py +++ b/IPython/testing/globalipapp.py @@ -30,7 +30,7 @@ from . import tools from IPython.core import page from IPython.utils import io from IPython.utils import py3compat -from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell +from IPython.terminal.interactiveshell import TerminalInteractiveShell #----------------------------------------------------------------------------- # Functions diff --git a/IPython/testing/iptest.py b/IPython/testing/iptest.py index 3d02033..2c93f5f 100644 --- a/IPython/testing/iptest.py +++ b/IPython/testing/iptest.py @@ -230,8 +230,8 @@ def make_exclude(): # files for web serving. Occasionally projects may put a .py # file in there (MathJax ships a conf.py), so we might as # well play it safe and skip the whole thing. - ipjoin('frontend', 'html', 'notebook', 'static'), - ipjoin('frontend', 'html', 'notebook', 'fabfile'), + ipjoin('html', 'static'), + ipjoin('html', 'fabfile'), ] if not have['sqlite3']: exclusions.append(ipjoin('core', 'tests', 'test_history')) @@ -261,18 +261,18 @@ def make_exclude(): if not have['pexpect']: exclusions.extend([ipjoin('lib', 'irunner'), ipjoin('lib', 'tests', 'test_irunner'), - ipjoin('frontend', 'terminal', 'console'), + ipjoin('terminal', 'console'), ]) if not have['zmq']: exclusions.append(ipjoin('kernel')) - exclusions.append(ipjoin('frontend', 'qt')) - exclusions.append(ipjoin('frontend', 'html')) - exclusions.append(ipjoin('frontend', 'consoleapp.py')) - exclusions.append(ipjoin('frontend', 'terminal', 'console')) + exclusions.append(ipjoin('qt')) + exclusions.append(ipjoin('html')) + exclusions.append(ipjoin('consoleapp.py')) + exclusions.append(ipjoin('terminal', 'console')) exclusions.append(ipjoin('parallel')) elif not have['qt'] or not have['pygments']: - exclusions.append(ipjoin('frontend', 'qt')) + exclusions.append(ipjoin('qt')) if not have['pymongo']: exclusions.append(ipjoin('parallel', 'controller', 'mongodb')) @@ -293,17 +293,17 @@ def make_exclude(): exclusions.extend([ipjoin('extensions', 'tests', 'test_octavemagic')]) if not have['tornado']: - exclusions.append(ipjoin('frontend', 'html')) + exclusions.append(ipjoin('html')) if not have['jinja2']: - exclusions.append(ipjoin('frontend', 'html', 'notebook', 'notebookapp')) + exclusions.append(ipjoin('html', 'notebookapp')) if not have['rpy2'] or not have['numpy']: exclusions.append(ipjoin('extensions', 'rmagic')) exclusions.append(ipjoin('extensions', 'tests', 'test_rmagic')) if not have['azure']: - exclusions.append(ipjoin('frontend', 'html', 'notebook', 'services', 'notebooks', 'azurenbmanager')) + exclusions.append(ipjoin('html', 'services', 'notebooks', 'azurenbmanager')) # This is needed for the reg-exp to match on win32 in the ipdoctest plugin. if sys.platform == 'win32': @@ -429,14 +429,21 @@ class IPTester(object): # The process did not die... print('... failed. Manual cleanup may be required.') + def make_runners(inc_slow=False): """Define the top-level packages that need to be tested. """ # Packages to be tested via nose, that only depend on the stdlib - nose_pkg_names = ['config', 'core', 'extensions', 'frontend', 'lib', + nose_pkg_names = ['config', 'core', 'extensions', 'lib', 'terminal', 'testing', 'utils', 'nbformat' ] + if have['qt']: + nose_pkg_names.append('qt') + + if have['tornado']: + nose_pkg_names.append('html') + if have['zmq']: nose_pkg_names.append('kernel') nose_pkg_names.append('kernel.inprocess') diff --git a/IPython/utils/importstring.py b/IPython/utils/importstring.py index 03d1408..8653d71 100644 --- a/IPython/utils/importstring.py +++ b/IPython/utils/importstring.py @@ -19,29 +19,32 @@ Authors: #----------------------------------------------------------------------------- def import_item(name): - """Import and return bar given the string foo.bar.""" - package = '.'.join(name.split('.')[0:-1]) - obj = name.split('.')[-1] - - # Note: the original code for this was the following. We've left it - # visible for now in case the new implementation shows any problems down - # the road, to make it easier on anyone looking for a problem. This code - # should be removed once we're comfortable we didn't break anything. + """Import and return ``bar`` given the string ``foo.bar``. + + Calling ``bar = import_item("foo.bar")`` is the functional equivalent of + executing the code ``from foo import bar``. + + Parameters + ---------- + name : string + The fully qualified name of the module/package being imported. + + Returns + ------- + mod : module object + The module that was imported. + """ - ## execString = 'from %s import %s' % (package, obj) - ## try: - ## exec execString - ## except SyntaxError: - ## raise ImportError("Invalid class specification: %s" % name) - ## exec 'temp = %s' % obj - ## return temp - - if package: - module = __import__(package,fromlist=[obj]) + parts = name.rsplit('.', 1) + if len(parts) == 2: + # called with 'foo.bar....' + package, obj = parts + module = __import__(package, fromlist=[obj]) try: pak = module.__dict__[obj] except KeyError: raise ImportError('No module named %s' % obj) return pak else: - return __import__(obj) + # called with un-dotted string + return __import__(parts[0]) diff --git a/IPython/utils/process.py b/IPython/utils/process.py index d9aab85..42c6bf5 100644 --- a/IPython/utils/process.py +++ b/IPython/utils/process.py @@ -51,7 +51,7 @@ def find_cmd(cmd): from IPython.utils.path import get_ipython_module_path from IPython.utils.process import pycmd2argv - argv = pycmd2argv(get_ipython_module_path('IPython.frontend.terminal.ipapp')) + argv = pycmd2argv(get_ipython_module_path('IPython.terminal.ipapp')) Parameters ---------- diff --git a/IPython/utils/submodule.py b/IPython/utils/submodule.py index cbabf6b..e52f9db 100644 --- a/IPython/utils/submodule.py +++ b/IPython/utils/submodule.py @@ -33,7 +33,7 @@ def ipython_parent(): def ipython_submodules(root): """return IPython submodules relative to root""" return [ - pjoin(root, 'IPython', 'frontend', 'html', 'notebook', 'static', 'components'), + pjoin(root, 'IPython', 'html', 'static', 'components'), ] def is_repo(d): diff --git a/IPython/utils/tests/test_importstring.py b/IPython/utils/tests/test_importstring.py new file mode 100644 index 0000000..0c79cb3 --- /dev/null +++ b/IPython/utils/tests/test_importstring.py @@ -0,0 +1,39 @@ +"""Tests for IPython.utils.importstring.""" + +#----------------------------------------------------------------------------- +# Copyright (C) 2013 The IPython Development Team +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +import nose.tools as nt + +from IPython.utils.importstring import import_item + +#----------------------------------------------------------------------------- +# Tests +#----------------------------------------------------------------------------- + +def test_import_plain(): + "Test simple imports" + import os + os2 = import_item('os') + nt.assert_true(os is os2) + + +def test_import_nested(): + "Test nested imports from the stdlib" + from os import path + path2 = import_item('os.path') + nt.assert_true(path is path2) + + +def test_import_raises(): + "Test that failing imports raise the right exception" + nt.assert_raises(ImportError, import_item, 'IPython.foobar') + diff --git a/IPython/utils/tests/test_path.py b/IPython/utils/tests/test_path.py index cf0f228..c5b0376 100644 --- a/IPython/utils/tests/test_path.py +++ b/IPython/utils/tests/test_path.py @@ -404,7 +404,7 @@ def test_get_ipython_package_dir(): def test_get_ipython_module_path(): - ipapp_path = path.get_ipython_module_path('IPython.frontend.terminal.ipapp') + ipapp_path = path.get_ipython_module_path('IPython.terminal.ipapp') nt.assert_true(os.path.isfile(ipapp_path)) diff --git a/MANIFEST.in b/MANIFEST.in index de40bfa..e5567c3 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -11,11 +11,11 @@ graft scripts graft IPython prune IPython/deathrow prune IPython/external/js -prune IPython/frontend/html/notebook/static/mathjax +prune IPython/html/static/mathjax # Include some specific files and data resources we need include IPython/.git_commit_info.ini -include IPython/frontend/qt/console/resources/icon/IPythonConsole.svg +include IPython/qt/console/resources/icon/IPythonConsole.svg # Documentation graft docs diff --git a/docs/source/interactive/htmlnotebook.txt b/docs/source/interactive/htmlnotebook.txt index 718d01e..501d3a7 100644 --- a/docs/source/interactive/htmlnotebook.txt +++ b/docs/source/interactive/htmlnotebook.txt @@ -413,7 +413,7 @@ store the notebooks in a different format. Currently, we ship a storage. This can be used by adding the following lines to your ``ipython_notebook_config.py`` file:: - c.NotebookApp.notebook_manager_class = 'IPython.frontend.html.notebook.azurenbmanager.AzureNotebookManager' + c.NotebookApp.notebook_manager_class = 'IPython.html.services.notebooks.azurenbmanager.AzureNotebookManager' c.AzureNotebookManager.account_name = u'paste_your_account_name_here' c.AzureNotebookManager.account_key = u'paste_your_account_key_here' c.AzureNotebookManager.container = u'notebooks' diff --git a/setupbase.py b/setupbase.py index 218d5cb..315848e 100644 --- a/setupbase.py +++ b/setupbase.py @@ -134,7 +134,7 @@ def find_package_data(): # walk notebook resources: cwd = os.getcwd() - os.chdir(os.path.join('IPython', 'frontend', 'html', 'notebook')) + os.chdir(os.path.join('IPython', 'html')) static_walk = list(os.walk('static')) os.chdir(cwd) static_data = [] @@ -148,8 +148,8 @@ def find_package_data(): 'IPython.config.profile' : ['README*', '*/*.py'], 'IPython.testing' : ['*.txt'], 'IPython.testing.plugin' : ['*.txt'], - 'IPython.frontend.html.notebook' : ['templates/*'] + static_data, - 'IPython.frontend.qt.console' : ['resources/icon/*.svg'], + 'IPython.html' : ['templates/*'] + static_data, + 'IPython.qt.console' : ['resources/icon/*.svg'], } return package_data @@ -312,7 +312,7 @@ def find_scripts(entry_points=False, suffix=''): """ if entry_points: console_scripts = [s % suffix for s in [ - 'ipython%s = IPython.frontend.terminal.ipapp:launch_new_instance', + 'ipython%s = IPython.terminal.ipapp:launch_new_instance', 'pycolor%s = IPython.utils.PyColorize:main', 'ipcontroller%s = IPython.parallel.apps.ipcontrollerapp:launch_new_instance', 'ipengine%s = IPython.parallel.apps.ipengineapp:launch_new_instance',