Some Py3 and various other fixes from wxGuru.

Merged and squashed from https://github.com/RobinD42/Phoenix/pull/15,
with additional edits.

git-svn-id: https://svn.wxwidgets.org/svn/wx/wxPython/Phoenix/trunk@74364 c3d73ce0-8a6f-49c7-b76d-6d57e0e08775
This commit is contained in:
Robin Dunn
2013-07-05 20:54:22 +00:00
parent de0fab0786
commit 2e30a88173
17 changed files with 129 additions and 150 deletions

View File

@@ -2,7 +2,7 @@
#---------------------------------------------------------------------------
# This script is used to run through the commands used for the various stages
# of building Phoenix, and can also be a front-end for building wxWidgets and
# the Python extension mocdules.
# the Python extension modules.
#---------------------------------------------------------------------------
from __future__ import absolute_import
@@ -23,7 +23,6 @@ if sys.version_info < (3,):
else:
from urllib.request import urlopen
from distutils.dep_util import newer, newer_group
from buildtools.config import Config, msg, opj, posixjoin, loadETG, etg2sip, findCmd, \
phoenixDir, wxDir, copyIfNewer, copyFile, \
@@ -198,7 +197,7 @@ def setPythonVersion(args):
else:
PYTHON = args[idx+1]
del args[idx:idx+2]
PYVER = runcmd('%s -c "import sys; print(sys.version[:3])"' % PYTHON,
PYVER = runcmd('"%s" -c "import sys; print(sys.version[:3]"' % PYTHON,
getOutput=True, echoCmd=False)
PYSHORTVER = PYVER[0] + PYVER[2]
break
@@ -249,10 +248,10 @@ def setPythonVersion(args):
PYSHORTVER = PYVER[0] + PYVER[2]
PYTHON = os.path.abspath(PYTHON)
msg('Build using: %s' % PYTHON)
msg('Build using: "%s"' % PYTHON)
msg(runcmd('%s -c "import sys; print(sys.version)"' % PYTHON, True, False))
PYTHON_ARCH = runcmd('%s -c "import platform; print(platform.architecture()[0])"'
msg(runcmd('"%s" -c "import sys; print(sys.version)"' % PYTHON, True, False))
PYTHON_ARCH = runcmd('"%s" -c "import platform; print(platform.architecture()[0])"'
% PYTHON, True, False)
msg('Python\'s architecture is %s' % PYTHON_ARCH)
os.environ['PYTHON'] = PYTHON
@@ -431,7 +430,7 @@ def deleteIfExists(deldir, verbose=True):
if verbose:
msg("Removing folder: %s" % deldir)
shutil.rmtree(deldir)
except:
except Exception:
if verbose:
import traceback
msg("Error: %s" % traceback.format_exc(1))
@@ -480,7 +479,7 @@ def getTool(cmdName, version, MD5, envVar, platformBinary):
msg('Connection successful...')
data = connection.read()
msg('Data downloaded...')
except:
except Exception:
print('ERROR: Unable to download ' + url)
print(' Set %s in the environment to use a local build of %s instead' % (envVar, cmdName))
import traceback
@@ -595,7 +594,7 @@ def checkCompiler(quiet=False):
"mc = msvc.MSVCCompiler(); " \
"mc.initialize(); " \
"print(mc.cc)"
CC = runcmd('%s -c "%s"' % (PYTHON, cmd), getOutput=True, echoCmd=False)
CC = runcmd('"%s" -c "%s"' % (PYTHON, cmd), getOutput=True, echoCmd=False)
if not quiet:
msg("MSVC: %s" % CC)
@@ -606,7 +605,7 @@ def checkCompiler(quiet=False):
"arch = msvc.PLAT_TO_VCVARS[msvc.get_platform()]; " \
"env = msvc.query_vcvarsall(msvc.VERSION, arch); " \
"print(env)"
env = eval(runcmd('%s -c "%s"' % (PYTHON, cmd), getOutput=True, echoCmd=False))
env = eval(runcmd('"%s" -c "%s"' % (PYTHON, cmd), getOutput=True, echoCmd=False))
os.environ['PATH'] = bytes(env['path'])
os.environ['INCLUDE'] = bytes(env['include'])
os.environ['LIB'] = bytes(env['lib'])
@@ -692,7 +691,7 @@ def cmd_etg(options, args):
# run the script only if any dependencies are newer
if newer_group(deps, sipfile):
runcmd('%s %s %s' % (PYTHON, script, flags))
runcmd('"%s" %s %s' % (PYTHON, script, flags))
def cmd_sphinx(options, args):
@@ -905,13 +904,13 @@ def cmd_touch(options, args):
def cmd_test(options, args):
cmdTimer = CommandTimer('test')
pwd = pushDir(phoenixDir())
runcmd(PYTHON + ' unittests/runtests.py %s' % ('-v' if options.verbose else ''), fatal=False)
runcmd('"%s" unittests/runtests.py %s' % (PYTHON, '-v' if options.verbose else ''), fatal=False)
def testOne(name, options, args):
cmdTimer = CommandTimer('test %s:' % name)
pwd = pushDir(phoenixDir())
runcmd(PYTHON + ' unittests/%s.py %s' % (name, '-v' if options.verbose else ''), fatal=False)
runcmd('"%s" unittests/%s.py %s' % (PYTHON, name, '-v' if options.verbose else ''), fatal=False)
def cmd_build(options, args):
@@ -1014,7 +1013,7 @@ def cmd_build_wx(options, args):
print('wxWidgets build options: ' + str(build_options))
wxbuild.main(wxscript, build_options)
except:
except Exception:
print("ERROR: failed building wxWidgets")
import traceback
traceback.print_exc()
@@ -1135,7 +1134,7 @@ def cmd_build_py(options, args):
if options.jobs:
build_options.append('--jobs=%s' % options.jobs)
build_options.append('--python=%s' % PYTHON)
build_options.append('--python="%s"' % PYTHON)
build_options.append('--out=%s' % wafBuildDir)
if not isWindows and not isDarwin and not options.no_magic and not options.use_syswx:
@@ -1147,7 +1146,7 @@ def cmd_build_py(options, args):
# Run waf to perform the builds
pwd = pushDir(phoenixDir())
cmd = '%s %s %s configure build %s' % (PYTHON, waf, ' '.join(build_options), options.extra_waf)
cmd = '"%s" %s %s configure build %s' % (PYTHON, waf, ' '.join(build_options), options.extra_waf)
runcmd(cmd)
if isWindows and options.both:
@@ -1155,7 +1154,7 @@ def cmd_build_py(options, args):
del build_options[-1]
wafBuildDir = posixjoin(wafBuildBase, 'release')
build_options.append('--out=%s' % wafBuildDir)
cmd = '%s %s %s configure build %s' % (PYTHON, waf, ' '.join(build_options), options.extra_waf)
cmd = '"%s" %s %s configure build %s' % (PYTHON, waf, ' '.join(build_options), options.extra_waf)
runcmd(cmd)
copyWxDlls(options)
@@ -1202,7 +1201,7 @@ def cmd_install_py(options, args):
cmdTimer = CommandTimer('install_py')
DESTDIR = '' if not options.destdir else '--root=' + options.destdir
VERBOSE = '--verbose' if options.verbose else ''
cmd = "%s setup.py install --skip-build %s %s %s" % (
cmd = '"%s" setup.py install --skip-build %s %s %s' % (
PYTHON, DESTDIR, VERBOSE, options.extra_setup)
runcmd(cmd)
@@ -1210,7 +1209,7 @@ def cmd_install_py(options, args):
def _doSimpleSetupCmd(options, args, setupCmd):
cmdTimer = CommandTimer(setupCmd)
VERBOSE = '--verbose' if options.verbose else ''
cmd = "%s setup.py %s --skip-build %s %s" % (PYTHON, setupCmd, VERBOSE, options.extra_setup)
cmd = '"%s" setup.py %s --skip-build %s %s' % (PYTHON, setupCmd, VERBOSE, options.extra_setup)
runcmd(cmd)
@@ -1230,7 +1229,7 @@ def cmd_egg_info(options, args, egg_base=None):
cmdTimer = CommandTimer('egg_info')
VERBOSE = '--verbose' if options.verbose else ''
BASE = '--egg-base '+egg_base if egg_base is not None else ''
cmd = "%s setup.py egg_info %s %s" % (PYTHON, VERBOSE, BASE)
cmd = '"%s" setup.py egg_info %s %s' % (PYTHON, VERBOSE, BASE)
runcmd(cmd)

View File

@@ -71,7 +71,7 @@ class WidgetTestCase(unittest.TestCase):
def myExecfile(self, filename, ns):
if sys.version_info < (3,):
if not six.PY3:
execfile(filename, ns)
else:
with open(filename, 'r') as f:

View File

@@ -1331,9 +1331,9 @@ class ArtManager(wx.EvtHandler):
winxpgui.SetLayeredWindowAttributes(hwnd, 0, amount, 2)
elif _libimported == "ctypes":
style = self._winlib.GetWindowLongA(hwnd, 0xffffffecL)
style = self._winlib.GetWindowLongA(hwnd, 0xffffffec)
style |= 0x00080000
self._winlib.SetWindowLongA(hwnd, 0xffffffecL, style)
self._winlib.SetWindowLongA(hwnd, 0xffffffec, style)
self._winlib.SetLayeredWindowAttributes(hwnd, 0, amount, 2)
else:
if not wnd.CanSetTransparent():

View File

@@ -108,6 +108,9 @@ def _makeAttribString(evt):
return attribs.rstrip()
def cmp(a, b):
return (a > b) - (a < b)
#----------------------------------------------------------------------------
class EventLog(wx.ListCtrl):
@@ -273,7 +276,6 @@ class EventChooser(wx.Panel):
self.doUpdate = True
self.updateCallback()
def sortCompare(self, data1, data2):
item1 = self.watchList[data1][0]
item2 = self.watchList[data2][0]
@@ -411,7 +413,7 @@ class EventWatcher(wx.Frame):
def onToggleWatch(self, evt):
if evt.Checked():
if evt.IsChecked():
self.watch(self._unwatchedWidget)
self._unwatchedWidget = None
else:

View File

@@ -44,8 +44,8 @@ except ImportError:
from time import clock
import wx
from Utilities import BBox
import GUIMode
from .Utilities import BBox
from . import GUIMode
## A global variable to hold the Pixels per inch that wxWindows thinks is in use
@@ -2398,7 +2398,7 @@ class ScaledBitmap(TextObjectMixin, DrawObject):
XY = WorldToPixel(self.XY)
H = ScaleWorldToPixel(self.Height)[0]
W = H * (self.bmpWidth / self.bmpHeight)
if (self.ScaledBitmap is None) or (H <> self.ScaledHeight) :
if (self.ScaledBitmap is None) or (H != self.ScaledHeight) :
self.ScaledHeight = H
Img = self.Image.Scale(W, H)
self.ScaledBitmap = wx.Bitmap(Img)
@@ -2577,14 +2577,14 @@ class ScaledBitmap2(TextObjectMixin, DrawObject, ):
Hs = int(scale * Hb + 0.5)
if (self.ScaledBitmap is None) or (self.ScaledBitmap[0] != (Xb, Yb, Wb, Hb, Ws, Ws) ):
Img = self.Image.GetSubImage(wx.Rect(Xb, Yb, Wb, Hb))
print "rescaling with High quality"
print("rescaling with High quality")
Img.Rescale(Ws, Hs, quality=wx.IMAGE_QUALITY_HIGH)
bmp = wx.Bitmap(Img)
self.ScaledBitmap = ((Xb, Yb, Wb, Hb, Ws, Ws), bmp)# this defines the cached bitmap
#XY = self.ShiftFun(XY[0], XY[1], W, H)
#fixme: get the shiftfun working!
else:
#print "Using cached bitmap"
#print("Using cached bitmap")
##fixme: The cached bitmap could be used if the one needed is the same scale, but
## a subset of the cached one.
bmp = self.ScaledBitmap[1]
@@ -3362,7 +3362,7 @@ class FloatCanvas(wx.Panel):
self.GUIMode.UpdateScreen()
if self.Debug:
print "Drawing took %f seconds of CPU time"%(clock()-start)
print("Drawing took %f seconds of CPU time")%(clock()-start)
if self._HTBitmap is not None:
self._HTBitmap.SaveFile('junk.png', wx.BITMAP_TYPE_PNG)

View File

@@ -13,8 +13,8 @@ version of the code.
import wx
## fixme: events should live in their own module, so all of FloatCanvas
## wouldn't have to be imported here.
import FloatCanvas, Resources
from Utilities import BBox
from . import FloatCanvas, Resources
from .Utilities import BBox
import numpy as N
class Cursors(object):

View File

@@ -34,7 +34,7 @@ Many samples are available in the `wxPhoenix/samples/floatcanvas` folder.
"""
import wx
import FloatCanvas, Resources, GUIMode
from . import FloatCanvas, Resources, GUIMode
class NavCanvas(wx.Panel):
"""

View File

@@ -5,7 +5,11 @@ A Bounding Box object and assorted utilities , subclassed from a numpy array
"""
import numpy as N
try:
import numpy as N
except ImportError:
pass
# raise ImportError("I could not import numpy")
class BBox(N.ndarray):
"""
@@ -267,7 +271,7 @@ class RectBBox(BBox):
return BBox.__new__(self, data)
def __init__(self, data, edges=None):
''' assume edgepoints are ordered such you can walk along all edges with left rotation sense
""" assume edgepoints are ordered such you can walk along all edges with left rotation sense
This may be:
left-top
left-bottom
@@ -275,11 +279,11 @@ class RectBBox(BBox):
right-top
or any rotation.
'''
"""
BBox.BBox(data)
self.edges = np.asarray(edges)
print "new rectbbox created"
print("new rectbbox created")
def ac_leftOf_ab(self, a, b, c):
@@ -289,7 +293,7 @@ class RectBBox(BBox):
return (ac[0]*ab[1] - ac[1]*ab[0]) <= 0
def PointInside(self, point):
print "point inside called"
print("point inside called")
for edge in xrange(4):
if self.ac_leftOf_ab(self.edges[edge],

View File

@@ -7,7 +7,7 @@
# RCS-ID: $Id$
# License: wxWidgets license
#
# Tags: phoenix-port, unittest, documented
# Tags: py3-port, phoenix-port, unittest, documented
#
#----------------------------------------------------------------------------
#
@@ -22,7 +22,7 @@ a base class from which you can derive masked comboboxes tailored to a specific
function. See maskededit module overview for how to configure the control.
"""
import wx, types, string
import wx
from wx.lib.masked import *
# jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would
@@ -115,7 +115,7 @@ class BaseMaskedComboBox( wx.ComboBox, MaskedEditMixin ):
self._prevSelection = (-1, -1)
## Since combobox completion is case-insensitive, always validate same way
if not kwargs.has_key('compareNoCase'):
if 'compareNoCase' not in kwargs:
kwargs['compareNoCase'] = True
MaskedEditMixin.__init__( self, name, **kwargs )
@@ -151,13 +151,13 @@ class BaseMaskedComboBox( wx.ComboBox, MaskedEditMixin ):
if not hasattr(self, 'controlInitialized'):
self.controlInitialized = True ## must have been called via XRC, therefore base class is constructed
if not kwargs.has_key('choices'):
if 'choices' not in kwargs:
choices=[]
kwargs['choices'] = choices ## set up maskededit to work with choice list too
self._choices = []
## Since combobox completion is case-insensitive, always validate same way
if not kwargs.has_key('compareNoCase'):
if 'compareNoCase' not in kwargs:
kwargs['compareNoCase'] = True
MaskedEditMixin.__init__( self, name, **kwargs )
@@ -263,7 +263,7 @@ class BaseMaskedComboBox( wx.ComboBox, MaskedEditMixin ):
"""
## dbg('MaskedComboBox::_SetSelection: setting mark to (%d, %d)' % (sel_start, sel_to))
if not self.__readonly:
return self.SetMark( sel_start, sel_to )
return self.SetTextSelection( sel_start, sel_to )
def _GetInsertionPoint(self):
@@ -372,7 +372,7 @@ class BaseMaskedComboBox( wx.ComboBox, MaskedEditMixin ):
if self._isDate and self._4digityear:
dateparts = value.split(' ')
dateparts[0] = self._adjustDate(dateparts[0], fixcentury=True)
value = string.join(dateparts, ' ')
value = ' '.join(dateparts)
value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
else:
raise
@@ -479,7 +479,7 @@ class BaseMaskedComboBox( wx.ComboBox, MaskedEditMixin ):
penalty.
"""
if self._mask:
if type(choice) not in (types.StringType, types.UnicodeType):
if not isinstance(choice, six.string_types):
raise TypeError('%s: choices must be a sequence of strings' % str(self._index))
elif not self.IsValid(choice):
raise ValueError('%s: "%s" is not a valid value for the control as specified.' % (str(self._index), choice))
@@ -631,7 +631,7 @@ class BaseMaskedComboBox( wx.ComboBox, MaskedEditMixin ):
# WANTS_CHARS with CB_READONLY apparently prevents navigation on WXK_TAB;
# ensure we can still navigate properly, as maskededit mixin::OnChar assumes
# that event.Skip() will just work, but it doesn't:
if self._keyhandlers.has_key(key):
if key in self._keyhandlers:
self._keyhandlers[key](event)
# else pass
else:
@@ -732,7 +732,7 @@ class BaseMaskedComboBox( wx.ComboBox, MaskedEditMixin ):
# work around bug in wx 2.5
wx.CallAfter(self.SetInsertionPoint, 0)
wx.CallAfter(self.SetInsertionPoint, end)
elif isinstance(match_index, str) or isinstance(match_index, unicode):
elif isinstance(match_index, six.string_types):
## dbg('CallAfter SetValue')
# Preserve the textbox contents
# See commentary in _OnReturn docstring.
@@ -800,8 +800,7 @@ class PreMaskedComboBox( BaseMaskedComboBox, MaskedEditAccessorsMixin ):
_firstEventType = wx.EVT_SIZE
def __init__(self):
pre = wx.PreComboBox()
self.PostCreate(pre)
wx.ComboBox.__init__(self)
self.Bind(self._firstEventType, self.OnCreate)

View File

@@ -5,6 +5,7 @@
# Copyright: (c) 2003 by Will Sadkin
# RCS-ID: $Id$
# License: wxWindows license
# Tags: py3-port
#----------------------------------------------------------------------------
# 12/09/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
@@ -80,7 +81,7 @@ def Ctrl( *args, **kwargs):
Actually a factory function providing a unifying
interface for generating masked controls.
"""
if not kwargs.has_key('controlType'):
if 'controlType' not in kwargs:
controlType = TEXT
else:
controlType = kwargs['controlType']

View File

@@ -23,7 +23,8 @@ limits of IP Addresses, and allows automatic field navigation as the
user hits '.' when typing.
"""
import wx, types, string
import wx
import wx.lib.six as six
from wx.lib.masked import BaseMaskedTextCtrl
# jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would
@@ -107,11 +108,11 @@ class IpAddrCtrl( BaseMaskedTextCtrl, IpAddrCtrlAccessorsMixin ):
"""
if not kwargs.has_key('mask'):
if 'mask' not in kwargs:
kwargs['mask'] = mask = "###.###.###.###"
if not kwargs.has_key('formatcodes'):
if 'formatcodes' not in kwargs:
kwargs['formatcodes'] = 'F_Sr<>'
if not kwargs.has_key('validRegex'):
if 'validRegex' not in kwargs:
kwargs['validRegex'] = "( \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))(\.( \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))){3}"
@@ -188,9 +189,9 @@ class IpAddrCtrl( BaseMaskedTextCtrl, IpAddrCtrlAccessorsMixin ):
"""
## dbg('IpAddrCtrl::SetValue(%s)' % str(value), indent=1)
if type(value) not in (types.StringType, types.UnicodeType):
if not isinstance(value, six.string_types):
## dbg(indent=0)
raise ValueError('%s must be a string', str(value))
raise ValueError('%s must be a string' % str(value))
bValid = True # assume True
parts = value.split('.')
@@ -205,13 +206,13 @@ class IpAddrCtrl( BaseMaskedTextCtrl, IpAddrCtrlAccessorsMixin ):
break
elif part.strip(): # non-empty part
try:
j = string.atoi(part)
j = int(part)
if not 0 <= j <= 255:
bValid = False
break
else:
parts[i] = '%3d' % j
except:
except Exception:
bValid = False
break
else:

View File

@@ -813,11 +813,6 @@ import sys
import wx
import wx.lib.six as six
if sys.version < '3':
unicode = unicode
else:
unicode = str
# jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would
# be a good place to implement the 2.3 logger class
from wx.tools.dbg import Logger
@@ -1493,7 +1488,7 @@ class Field:
raise TypeError('%s: choices must be a sequence of strings' % str(self._index))
elif len( self._choices) > 0:
for choice in self._choices:
if not isinstance(choice, (str, unicode)):
if not isinstance(choice, six.string_types):
## dbg(indent=0, suspend=0)
raise TypeError('%s: choices must be a sequence of strings' % str(self._index))
@@ -1522,7 +1517,7 @@ class Field:
raise ve
self._hasList = True
#### dbg("kwargs.has_key('fillChar')?", kwargs.has_key('fillChar'), "len(self._choices) > 0?", len(self._choices) > 0)
#### dbg("'fillChar' in kwargs?", 'fillChar' in kwargs, "len(self._choices) > 0?", len(self._choices) > 0)
#### dbg("self._old_fillChar:'%s'" % self._old_fillChar, "self._fillChar: '%s'" % self._fillChar)
if 'fillChar' in kwargs and len(self._choices) > 0:
if kwargs['fillChar'] != ' ':
@@ -1955,7 +1950,7 @@ class MaskedEditMixin:
for key in ('emptyBackgroundColour', 'invalidBackgroundColour', 'validBackgroundColour',
'foregroundColour', 'signedForegroundColour'):
if key in ctrl_kwargs:
if isinstance(ctrl_kwargs[key], (str, unicode)):
if isinstance(ctrl_kwargs[key], six.string_types):
c = wx.Colour(ctrl_kwargs[key])
if c.Get() == (-1, -1, -1):
raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs[key]), key))
@@ -1974,7 +1969,7 @@ class MaskedEditMixin:
# Build dictionary of any changing parameters which should be propagated to the
# component fields:
for arg in Field.propagating_params:
#### dbg('kwargs.has_key(%s)?' % arg, kwargs.has_key(arg))
#### dbg('%s in kwargs?' % arg, arg in kwargs)
#### dbg('getattr(self._ctrl_constraints, _%s)?' % arg, getattr(self._ctrl_constraints, '_'+arg))
reset_args[arg] = arg in kwargs and kwargs[arg] != getattr(self._ctrl_constraints, '_'+arg)
#### dbg('reset_args[%s]?' % arg, reset_args[arg])
@@ -2410,7 +2405,7 @@ class MaskedEditMixin:
#### dbg('edit_end =', i)
edit_end = i
self._lookupField[i] = field_index
#### dbg('self._fields.has_key(%d)?' % field_index, self._fields.has_key(field_index))
#### dbg('%d in self._fields?' % field_index, field_index in self._fields)
if field_index not in self._fields:
kwargs = Field.valid_params.copy()
kwargs['index'] = field_index
@@ -2610,8 +2605,8 @@ class MaskedEditMixin:
inherit_args['defaultValue'] = "" # (reset for field)
for param in Field.propagating_params:
#### dbg('reset_args.has_key(%s)?' % param, reset_args.has_key(param))
#### dbg('reset_args.has_key(%(param)s) and reset_args[%(param)s]?' % locals(), reset_args.has_key(param) and reset_args[param])
#### dbg('%s in reset_args?' % param, param in reset_args)
#### dbg('%(param)s in reset_args and reset_args[%(param)s]?' % locals(), param in reset_args and reset_args[param])
if param in reset_args:
inherit_args[param] = self.GetCtrlParameter(param)
#### dbg('inherit_args[%s]' % param, inherit_args[param])
@@ -3061,7 +3056,6 @@ class MaskedEditMixin:
else:
field = self._FindField(pos)
if 'unicode' in wx.PlatformInfo:
if key < 256:
char = chr(key) # (must work if we got this far)
if not six.PY3:
@@ -3069,26 +3063,14 @@ class MaskedEditMixin:
else:
char = unichr(event.GetUnicodeKey())
## dbg('unicode char:', char)
excludes = unicode()
if not isinstance(field._excludeChars, unicode):
if not six.PY3:
excludes = six.text_type()
if not isinstance(field._excludeChars, six.text_type):
excludes += field._excludeChars.decode(self._defaultEncoding)
else:
excludes += field._excludeChars
if not isinstance(self._ctrl_constraints, unicode):
if not six.PY3:
if not isinstance(self._ctrl_constraints, six.text_type):
excludes += self._ctrl_constraints._excludeChars.decode(self._defaultEncoding)
else:
excludes += self._ctrl_constraints._excludeChars
else:
char = chr(key) # (must work if we got this far)
excludes = field._excludeChars + self._ctrl_constraints._excludeChars
## dbg("key ='%s'" % chr(key))
if chr(key) == ' ':
## dbg('okSpaces?', field._okSpaces)
pass
if char in excludes:
keep_processing = False
@@ -4555,7 +4537,7 @@ class MaskedEditMixin:
if len(year) == 2:
# Fix year adjustment to be less "20th century" :-) and to adjust heuristic as the
# years pass...
now = wx.DateTime_Now()
now = wx.DateTime.Now()
century = (now.GetYear() /100) * 100 # "this century"
twodig_year = now.GetYear() - century # "this year" (2 digits)
# if separation between today's 2-digit year and typed value > 50,
@@ -4637,7 +4619,7 @@ class MaskedEditMixin:
# convert okchars to unicode if required; will force subsequent appendings to
# result in unicode strings
if not six.PY3 and 'unicode' in wx.PlatformInfo and not isinstance(okchars, unicode):
if not six.PY3 and not isinstance(okchars, six.string_types):
okchars = okchars.decode(self._defaultEncoding)
field = self._FindField(pos)
@@ -4891,7 +4873,7 @@ class MaskedEditMixin:
groupchar = self._fields[0]._groupChar
try:
value = long(text.replace(groupchar,'').replace('(','-').replace(')','').replace(' ', ''))
value = int(text.replace(groupchar,'').replace('(','-').replace(')','').replace(' ', ''))
except:
## dbg('invalid number', indent=0)
return None, signpos, right_signpos
@@ -5226,7 +5208,7 @@ class MaskedEditMixin:
left = text[0:pos]
right = text[pos+1:]
if 'unicode' in wx.PlatformInfo and not isinstance(char, unicode):
if not isinstance(char, six.string_types):
# convert the keyboard constant to a unicode value, to
# ensure it can be concatenated into the control value:
if not six.PY3:
@@ -5413,7 +5395,7 @@ class MaskedEditMixin:
if self._isFloat:
number = float(value.replace(groupchar, '').replace(self._decimalChar, '.').replace('(', '-').replace(')', ''))
else:
number = long( value.replace(groupchar, '').replace('(', '-').replace(')', ''))
number = int( value.replace(groupchar, '').replace('(', '-').replace(')', ''))
if value.strip():
if self._fields[0]._alignRight:
require_digit_at = self._fields[0]._extent[1]-1
@@ -5765,7 +5747,7 @@ class MaskedEditMixin:
else:
item = 'selection'
## dbg('maxlength:', maxlength)
if not six.PY3 and 'unicode' in wx.PlatformInfo and not isinstance(paste_text, unicode):
if not six.PY3 and not isinstance(paste_text, six.string_types):
paste_text = paste_text.decode(self._defaultEncoding)
length_considered = len(paste_text)
@@ -5872,7 +5854,7 @@ class MaskedEditMixin:
if paste_text is not None:
if not six.PY3 and 'unicode' in wx.PlatformInfo and not isinstance(paste_text, unicode):
if not six.PY3 and not isinstance(paste_text, six.string_types):
paste_text = paste_text.decode(self._defaultEncoding)
## dbg('paste text: "%s"' % paste_text)

View File

@@ -399,11 +399,8 @@ GetAutoSize()
"""
import copy
import string
import types
import wx
import wx.lib.six as six
from sys import maxsize
@@ -669,7 +666,7 @@ class NumCtrl(BaseMaskedTextCtrl, NumCtrlAccessorsMixin):
fields = {}
if 'fractionWidth' in kwargs:
if type(kwargs['fractionWidth']) != types.IntType:
if not isinstance(kwargs['fractionWidth'], int):
raise AttributeError('invalid fractionWidth (%s) specified; expected integer' % repr(kwargs['fractionWidth']))
elif kwargs['fractionWidth'] < 0:
raise AttributeError('invalid fractionWidth (%s) specified; must be >= 0' % repr(kwargs['fractionWidth']))
@@ -687,7 +684,7 @@ class NumCtrl(BaseMaskedTextCtrl, NumCtrlAccessorsMixin):
## dbg('fracmask:', fracmask)
if 'integerWidth' in kwargs:
if type(kwargs['integerWidth']) != types.IntType:
if not isinstance(kwargs['integerWidth'], int):
## dbg(indent=0)
raise AttributeError('invalid integerWidth (%s) specified; expected integer' % repr(kwargs['integerWidth']))
elif kwargs['integerWidth'] < 0:
@@ -1546,7 +1543,7 @@ class NumCtrl(BaseMaskedTextCtrl, NumCtrlAccessorsMixin):
elif self._fractionWidth:
value = float(value)
else:
value = long(value)
value = int(value)
min = self.GetMin()
max = self.GetMax()
@@ -1554,7 +1551,7 @@ class NumCtrl(BaseMaskedTextCtrl, NumCtrlAccessorsMixin):
if max is None: max = value
# if bounds set, and value is None, return False
if value == None and (min is not None or max is not None):
if value is None and (min is not None or max is not None):
## dbg('finished IsInBounds', indent=0)
return 0
else:
@@ -1659,7 +1656,7 @@ class NumCtrl(BaseMaskedTextCtrl, NumCtrlAccessorsMixin):
if self._fractionWidth or value.find('.') != -1:
value = float(value)
else:
value = long(value)
value = int(value)
except Exception as e:
## dbg('exception raised:', e, indent=0)
raise ValueError ('NumCtrl requires numeric value, passed %s'% repr(value) )
@@ -1690,7 +1687,7 @@ class NumCtrl(BaseMaskedTextCtrl, NumCtrlAccessorsMixin):
## dbg('adjustwidth - groupSpace:', adjustwidth - self._groupSpace)
## dbg('adjustwidth:', adjustwidth)
if self._fractionWidth == 0:
s = str(long(value)).rjust(self._integerWidth)
s = str(int(value)).rjust(self._integerWidth)
else:
format = '%' + '%d.%df' % (self._integerWidth+self._fractionWidth+1, self._fractionWidth)
s = format % float(value)
@@ -1745,7 +1742,7 @@ class NumCtrl(BaseMaskedTextCtrl, NumCtrlAccessorsMixin):
## dbg("couldn't convert to float; returning None")
return None
else:
raise
raise ValueError
else:
try:
## dbg(indent=0)
@@ -1753,13 +1750,13 @@ class NumCtrl(BaseMaskedTextCtrl, NumCtrlAccessorsMixin):
except ValueError:
try:
## dbg(indent=0)
return long( value )
return int( value )
except ValueError:
## dbg("couldn't convert to long; returning None")
return None
else:
raise
raise ValueError
else:
## dbg('exception occurred; returning None')
return None

View File

@@ -278,7 +278,7 @@ class BaseMaskedTextCtrl( wx.TextCtrl, MaskedEditMixin ):
if self._isDate and self._4digityear:
dateparts = value.split(' ')
dateparts[0] = self._adjustDate(dateparts[0], fixcentury=True)
value = string.join(dateparts, ' ')
value = ' '.join(dateparts)
## dbg('adjusted value: "%s"' % value)
value, replace_to = self._Paste(value, raise_on_invalid=True, just_return_value=True)
else:
@@ -443,8 +443,7 @@ class PreMaskedTextCtrl( BaseMaskedTextCtrl, MaskedEditAccessorsMixin ):
_firstEventType = wx.EVT_SIZE
def __init__(self):
pre = wx.PreTextCtrl()
self.PostCreate(pre)
wx.TextCtrl.__init__(self)
self.Bind(self._firstEventType, self.OnCreate)

View File

@@ -276,10 +276,9 @@ IsLimited()
"""
import copy
import string
import types
import wx
import wx.lib.six as six
from wx.tools.dbg import Logger
from wx.lib.masked import Field, BaseMaskedTextCtrl
@@ -413,28 +412,28 @@ class TimeCtrl(BaseMaskedTextCtrl):
limited = self.__limited
self.__posCurrent = 0
# handle deprecated keword argument name:
if kwargs.has_key('display_seconds'):
if 'display_seconds' in kwargs:
kwargs['displaySeconds'] = kwargs['display_seconds']
del kwargs['display_seconds']
if not kwargs.has_key('displaySeconds'):
if 'displaySeconds' not in kwargs:
kwargs['displaySeconds'] = True
# (handle positional arg (from original release) differently from rest of kwargs:)
if not kwargs.has_key('format'):
if 'format' not in kwargs:
if fmt24hr:
if kwargs.has_key('displaySeconds') and kwargs['displaySeconds']:
if 'displaySeconds' in kwargs and kwargs['displaySeconds']:
kwargs['format'] = '24HHMMSS'
del kwargs['displaySeconds']
else:
kwargs['format'] = '24HHMM'
else:
if kwargs.has_key('displaySeconds') and kwargs['displaySeconds']:
if 'displaySeconds' in kwargs and kwargs['displaySeconds']:
kwargs['format'] = 'HHMMSS'
del kwargs['displaySeconds']
else:
kwargs['format'] = 'HHMM'
if not kwargs.has_key('useFixedWidthFont'):
if 'useFixedWidthFont' not in kwargs:
# allow control over font selection:
kwargs['useFixedWidthFont'] = self.__useFixedWidthFont
@@ -516,10 +515,10 @@ class TimeCtrl(BaseMaskedTextCtrl):
maskededit_kwargs = {}
reset_format = False
if kwargs.has_key('display_seconds'):
if 'display_seconds' in kwargs:
kwargs['displaySeconds'] = kwargs['display_seconds']
del kwargs['display_seconds']
if kwargs.has_key('format') and kwargs.has_key('displaySeconds'):
if 'format' in kwargs and 'displaySeconds' in kwargs:
del kwargs['displaySeconds'] # always apply format if specified
# assign keyword args as appropriate:
@@ -534,7 +533,7 @@ class TimeCtrl(BaseMaskedTextCtrl):
require24hr = True
else:
require24hr = False
except:
except Exception:
require24hr = True
# handle both local or generic 'maskededit' autoformat codes:
@@ -558,7 +557,7 @@ class TimeCtrl(BaseMaskedTextCtrl):
reset_format = True
elif key in ("displaySeconds", "display_seconds") and not kwargs.has_key('format'):
elif key in ("displaySeconds", "display_seconds") and 'format' not in kwargs:
self.__displaySeconds = param_value
reset_format = True
@@ -759,11 +758,9 @@ class TimeCtrl(BaseMaskedTextCtrl):
value = self.GetValue()
## dbg('value = "%s"' % value)
if type(value) == types.UnicodeType:
value = str(value) # convert to regular string
valid = True # assume true
if type(value) == types.StringType:
if isinstance(value, six.string_types):
value = six.text_type(value) # convert to regular string
# Construct constant wxDateTime, then try to parse the string:
wxdt = wx.DateTime.FromDMY(1, 0, 1970)
@@ -885,7 +882,7 @@ class TimeCtrl(BaseMaskedTextCtrl):
## dbg(suspend=1)
## dbg('TimeCtrl::GetMin, as_string?', as_string, indent=1)
if self.__min is None:
## dbg('(min == None)')
## dbg('(min is None)')
ret = self.__min
elif as_string:
ret = self.__min
@@ -949,7 +946,7 @@ class TimeCtrl(BaseMaskedTextCtrl):
## dbg(suspend=1)
## dbg('TimeCtrl::GetMin, as_string?', as_string, indent=1)
if self.__max is None:
## dbg('(max == None)')
## dbg('(max is None)')
ret = self.__max
elif as_string:
ret = self.__max
@@ -1385,7 +1382,7 @@ class TimeCtrl(BaseMaskedTextCtrl):
if self.IsLimited() and not self.IsInBounds(value):
## dbg(indent=0)
raise ValueError (
'value %s is not within the bounds of the control' % str(value) )
'value %s is not within the bounds of the control' % six.text_type(value) )
## dbg(indent=0)
return value

View File

@@ -11,6 +11,7 @@ import wx.lib.six as six
from . import dispatcher
from . import editwindow
from . import images
import inspect
from . import introspect
import types
@@ -139,8 +140,7 @@ class FillingTree(wx.TreeCtrl):
children = self.objGetChildren(obj)
if not children:
return
keys = children.keys()
keys.sort(key=lambda x: six.text_type(x).lower())
keys = sorted(children.keys(), key=lambda x: six.text_type(x).lower())
for key in keys:
itemtext = six.text_type(key)
# Show string dictionary items with single quotes, except
@@ -337,7 +337,6 @@ class FillingFrame(wx.Frame):
intro = 'PyFilling - The Tastiest Namespace Inspector'
self.CreateStatusBar()
self.SetStatusText(intro)
import images
self.SetIcon(images.getPyIcon())
self.filling = Filling(parent=self, rootObject=rootObject,
rootLabel=rootLabel,

View File

@@ -108,7 +108,7 @@ def getAllAttributeNames(object):
# This could(?) fail if the type is poorly defined without
# even a name.
key = type(object).__name__
except:
except Exception:
key = 'anonymous'
# Wake up sleepy objects - a hack for ZODB objects in "ghost" state.
wakeupcall = dir(object)
@@ -118,9 +118,8 @@ def getAllAttributeNames(object):
attrdict[(key, 'dir', len(attributes))] = attributes
# Get attributes from the object's dictionary, if it has one.
try:
attributes = object.__dict__.keys()
attributes.sort()
except: # Must catch all because object might have __getattr__.
attributes = sorted(object.__dict__.keys())
except Exception: # Must catch all because object might have __getattr__.
pass
else:
attrdict[(key, '__dict__', len(attributes))] = attributes