1
0
Fork 0
mirror of https://github.com/shlomif/PySolFC.git synced 2025-04-05 00:02:29 -04:00

use six.py.

This commit is contained in:
Shlomi Fish 2018-09-01 18:40:50 +03:00
parent ead4b9212a
commit 11bafeba44
22 changed files with 91 additions and 153 deletions

View file

@ -20,6 +20,7 @@
import sys import sys
import os import os
import re import re
import six
from six import string_types from six import string_types
from warnings import warn from warnings import warn
@ -27,9 +28,6 @@ INTP_VER = sys.version_info[:2]
if INTP_VER < (2, 2): if INTP_VER < (2, 2):
raise RuntimeError("Python v.2.2 or later needed") raise RuntimeError("Python v.2.2 or later needed")
if sys.version_info > (3,):
unicode = str
compiler = None compiler = None
try: try:
import compiler import compiler
@ -860,7 +858,8 @@ class Section(dict):
def decode(self, encoding): def decode(self, encoding):
""" """
Decode all strings and values to unicode, using the specified encoding. Decode all strings and values to unicode, using the specified
encoding.
Works with subsections and list values. Works with subsections and list values.
@ -871,12 +870,12 @@ class Section(dict):
>>> m.decode('ascii') >>> m.decode('ascii')
>>> def testuni(val): >>> def testuni(val):
... for entry in val: ... for entry in val:
... if not isinstance(entry, unicode): ... if not isinstance(entry, six.text_type):
... print >> sys.stderr, type(entry) ... print >> sys.stderr, type(entry)
... raise AssertionError, 'decode failed.' ... raise AssertionError, 'decode failed.'
... if isinstance(val[entry], dict): ... if isinstance(val[entry], dict):
... testuni(val[entry]) ... testuni(val[entry])
... elif not isinstance(val[entry], unicode): ... elif not isinstance(val[entry], six.text_type):
... raise AssertionError, 'decode failed.' ... raise AssertionError, 'decode failed.'
>>> testuni(m) >>> testuni(m)
>>> m.encode('ascii') >>> m.encode('ascii')
@ -904,7 +903,7 @@ class Section(dict):
def encode(self, encoding): def encode(self, encoding):
""" """
Encode all strings and values from unicode, Encode all strings and values from six.text_type,
using the specified encoding. using the specified encoding.
Works with subsections and list values. Works with subsections and list values.
@ -1174,7 +1173,7 @@ class ConfigObj(Section):
self.filename = infile self.filename = infile
if os.path.isfile(infile): if os.path.isfile(infile):
if sys.version_info > (3,): if sys.version_info > (3,):
infile = unicode(open(infile).read()) or [] infile = six.text_type(open(infile).read()) or []
else: else:
infile = open(infile).read() or [] infile = open(infile).read() or []
elif self.file_error: elif self.file_error:
@ -1275,7 +1274,7 @@ class ConfigObj(Section):
If an encoding is not specified, UTF8 or UTF16 BOM will be detected and If an encoding is not specified, UTF8 or UTF16 BOM will be detected and
removed. The BOM attribute will be set. UTF16 will be decoded to removed. The BOM attribute will be set. UTF16 will be decoded to
unicode. six.text_type.
NOTE: This method must not be called with an empty ``infile``. NOTE: This method must not be called with an empty ``infile``.
@ -1376,25 +1375,25 @@ class ConfigObj(Section):
def _decode(self, infile, encoding): def _decode(self, infile, encoding):
""" """
Decode infile to unicode. Using the specified encoding. Decode infile to six.text_type. Using the specified encoding.
if is a string, it also needs converting to a list. if is a string, it also needs converting to a list.
""" """
if isinstance(infile, string_types): if isinstance(infile, string_types):
# can't be unicode # can't be six.text_type
# NOTE: Could raise a ``UnicodeDecodeError`` # NOTE: Could raise a ``UnicodeDecodeError``
return infile.decode(encoding).splitlines(True) return infile.decode(encoding).splitlines(True)
for i, line in enumerate(infile): for i, line in enumerate(infile):
if not isinstance(line, unicode): if not isinstance(line, six.text_type):
# NOTE: The isinstance test here handles mixed # NOTE: The isinstance test here handles mixed
# lists of unicode/string # lists of six.text_type/string
# NOTE: But the decode will break on any non-string values # NOTE: But the decode will break on any non-string values
# NOTE: Or could raise a ``UnicodeDecodeError`` # NOTE: Or could raise a ``UnicodeDecodeError``
infile[i] = line.decode(encoding) infile[i] = line.decode(encoding)
return infile return infile
def _decode_element(self, line): def _decode_element(self, line):
"""Decode element to unicode if necessary.""" """Decode element to six.text_type if necessary."""
if not self.encoding: if not self.encoding:
return line return line
if isinstance(line, str) and self.default_encoding: if isinstance(line, str) and self.default_encoding:

View file

@ -125,6 +125,7 @@
""" """
import sys import sys
import six
import re import re
__docformat__ = "restructuredtext en" __docformat__ = "restructuredtext en"
@ -137,10 +138,7 @@ INTP_VER = sys.version_info[:2]
if INTP_VER < (2, 2): if INTP_VER < (2, 2):
raise RuntimeError("Python v.2.2 or later needed") raise RuntimeError("Python v.2.2 or later needed")
if sys.version_info > (3,): StringTypes = six.string_types
unicode = str
StringTypes = (str, unicode)
_list_arg = re.compile(r''' _list_arg = re.compile(r'''

View file

@ -21,7 +21,7 @@
# #
# ---------------------------------------------------------------------------## # ---------------------------------------------------------------------------##
import sys import six
from pysollib.gamedb import registerGame, GameInfo, GI from pysollib.gamedb import registerGame, GameInfo, GI
from pysollib.util import ACE, ANY_RANK, ANY_SUIT, \ from pysollib.util import ACE, ANY_RANK, ANY_SUIT, \
KING, \ KING, \
@ -68,14 +68,11 @@ from pysollib.wizardutil import WizardWidgets
# * # *
# ************************************************************************ # ************************************************************************
if sys.version_info > (3,):
basestring = str
def get_settings(ss): def get_settings(ss):
s = {} s = {}
for w in WizardWidgets: for w in WizardWidgets:
if isinstance(w, basestring): if isinstance(w, six.string_types):
continue continue
if w.var_name in ss: if w.var_name in ss:
v = ss[w.var_name] v = ss[w.var_name]

View file

@ -23,10 +23,10 @@
# imports # imports
import sys
import time import time
import math import math
import traceback import traceback
import six
from pysollib.mygettext import _ from pysollib.mygettext import _
from gettext import ungettext from gettext import ungettext
@ -66,9 +66,6 @@ if True: # This prevents from travis 'error' E402.
from pysollib.hint import DefaultHint from pysollib.hint import DefaultHint
from pysollib.help import help_about from pysollib.help import help_about
if sys.version_info > (3,):
basestring = str
PLAY_TIME_TIMEOUT = 200 PLAY_TIME_TIMEOUT = 200
# ************************************************************************ # ************************************************************************
@ -1039,7 +1036,7 @@ class Game(object):
# self.top.wm_title("%s - %s" # self.top.wm_title("%s - %s"
# % (TITLE, self.getTitleName())) # % (TITLE, self.getTitleName()))
continue continue
if isinstance(v, basestring): if isinstance(v, six.string_types):
if sb: if sb:
sb.updateText(gamenumber=v) sb.updateText(gamenumber=v)
# self.top.wm_title("%s - %s %s" % (TITLE, # self.top.wm_title("%s - %s %s" % (TITLE,
@ -1081,7 +1078,7 @@ class Game(object):
if tb: if tb:
tb.updateText(player=_("Player\n")) tb.updateText(player=_("Player\n"))
continue continue
if isinstance(v, basestring): if isinstance(v, six.string_types):
if tb: if tb:
# if self.app.opt.toolbar_size: # if self.app.opt.toolbar_size:
if self.app.toolbar.getSize(): if self.app.toolbar.getSize():
@ -1103,7 +1100,7 @@ class Game(object):
if v is None: if v is None:
if sb: if sb:
sb.updateText(time='') sb.updateText(time='')
if isinstance(v, basestring): if isinstance(v, six.string_types):
if sb: if sb:
sb.updateText(time=v) sb.updateText(time=v)
continue continue

View file

@ -23,7 +23,7 @@
# imports # imports
import sys import six
import imp import imp
# PySol imports # PySol imports
@ -33,10 +33,6 @@ import pysollib.settings
from pysollib.mygettext import _, n_ from pysollib.mygettext import _, n_
if sys.version_info > (3,):
basestring = str
unicode = str
# ************************************************************************ # ************************************************************************
# * constants # * constants
# ************************************************************************ # ************************************************************************
@ -454,13 +450,13 @@ class GameInfo(Struct):
): ):
# #
def to_unicode(s): def to_unicode(s):
if isinstance(s, unicode): if isinstance(s, six.text_type):
return s return s
try: try:
s = unicode(s, 'utf-8') s = six.text_type(s, 'utf-8')
except UnicodeDecodeError as err: except UnicodeDecodeError as err:
print_err(err) print_err(err)
s = unicode(s, 'utf-8', 'ignore') s = six.text_type(s, 'utf-8', 'ignore')
return s return s
ncards = decks * (len(suits) * len(ranks) + len(trumps)) ncards = decks * (len(suits) * len(ranks) + len(trumps))
game_flags = game_type & ~1023 game_flags = game_type & ~1023
@ -475,7 +471,7 @@ class GameInfo(Struct):
short_name = to_unicode(short_name) short_name = to_unicode(short_name)
if pysollib.settings.TRANSLATE_GAME_NAMES: if pysollib.settings.TRANSLATE_GAME_NAMES:
short_name = _(short_name) short_name = _(short_name)
if isinstance(altnames, basestring): if isinstance(altnames, six.string_types):
altnames = (altnames,) altnames = (altnames,)
altnames = [to_unicode(n) for n in altnames] altnames = [to_unicode(n) for n in altnames]
if pysollib.settings.TRANSLATE_GAME_NAMES: if pysollib.settings.TRANSLATE_GAME_NAMES:

View file

@ -28,6 +28,7 @@ import time
import subprocess import subprocess
import re import re
import sys import sys
import six
from io import BytesIO from io import BytesIO
# PySol imports # PySol imports
@ -37,8 +38,6 @@ from pysollib.mfxutil import destruct
from pysollib.util import KING from pysollib.util import KING
FCS_VERSION = None FCS_VERSION = None
if sys.version_info > (3,):
unicode = str
# ************************************************************************ # ************************************************************************
# * HintInterface is an abstract class that defines the public # * HintInterface is an abstract class that defines the public
@ -1000,7 +999,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint):
global FCS_VERSION global FCS_VERSION
if FCS_VERSION is None: if FCS_VERSION is None:
pout, _ = self.run_solver(FCS_COMMAND + ' --version', '') pout, _ = self.run_solver(FCS_COMMAND + ' --version', '')
s = unicode(pout.read(), encoding='utf-8') s = six.text_type(pout.read(), encoding='utf-8')
m = re.search(r'version ([0-9]+)\.([0-9]+)\.([0-9]+)', s) m = re.search(r'version ([0-9]+)\.([0-9]+)\.([0-9]+)', s)
if m: if m:
FCS_VERSION = (int(m.group(1)), int(m.group(2)), FCS_VERSION = (int(m.group(1)), int(m.group(2)),
@ -1064,7 +1063,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint):
states = 0 states = 0
for sbytes in pout: for sbytes in pout:
s = unicode(sbytes, encoding='utf-8') s = six.text_type(sbytes, encoding='utf-8')
if DEBUG >= 5: if DEBUG >= 5:
print(s) print(s)
@ -1085,7 +1084,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint):
hints = [] hints = []
for sbytes in pout: for sbytes in pout:
s = unicode(sbytes, encoding='utf-8') s = six.text_type(sbytes, encoding='utf-8')
if DEBUG: if DEBUG:
print(s) print(s)
if self._determineIfSolverState(s): if self._determineIfSolverState(s):
@ -1219,7 +1218,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint):
states = 0 states = 0
for sbytes in pout: for sbytes in pout:
s = unicode(sbytes, encoding='utf-8') s = six.text_type(sbytes, encoding='utf-8')
if DEBUG >= 5: if DEBUG >= 5:
print(s) print(s)
@ -1233,7 +1232,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint):
hints = [] hints = []
for sbytes in pout: for sbytes in pout:
s = unicode(sbytes, encoding='utf-8') s = six.text_type(sbytes, encoding='utf-8')
if DEBUG: if DEBUG:
print(s) print(s)
m = re.match('Total number of states checked is (\d+)\.', s) m = re.match('Total number of states checked is (\d+)\.', s)

View file

@ -24,6 +24,7 @@
# imports # imports
import re import re
import sys import sys
import six
import os import os
import time import time
import locale import locale
@ -54,8 +55,6 @@ USE_PIL = False
if TOOLKIT == 'tk' and Image and Image.VERSION >= '1.1.7': if TOOLKIT == 'tk' and Image and Image.VERSION >= '1.1.7':
USE_PIL = True USE_PIL = True
if sys.version_info > (3,):
unicode = str
# debug # debug
# Image = None # Image = None
# USE_PIL = False # USE_PIL = False
@ -158,7 +157,7 @@ if os.name == "posix":
def win32_getusername(): def win32_getusername():
user = os.environ.get('USERNAME', '').strip() user = os.environ.get('USERNAME', '').strip()
try: try:
user = unicode(user, locale.getpreferredencoding()) user = six.text_type(user, locale.getpreferredencoding())
except Exception: except Exception:
user = '' user = ''
return user return user

View file

@ -1,8 +1,6 @@
import gettext import gettext
import sys import sys
import six
if sys.version_info > (3,):
unicode = str
def n_(x): def n_(x):
@ -12,8 +10,8 @@ def n_(x):
def fix_gettext(): def fix_gettext():
def ugettext(message): def ugettext(message):
# unicoded gettext # unicoded gettext
if not isinstance(message, unicode): if not isinstance(message, six.text_type):
message = unicode(message, 'utf-8') message = six.text_type(message, 'utf-8')
domain = gettext._current_domain domain = gettext._current_domain
try: try:
t = gettext.translation(domain, t = gettext.translation(domain,
@ -29,10 +27,10 @@ def fix_gettext():
def ungettext(msgid1, msgid2, n): def ungettext(msgid1, msgid2, n):
# unicoded ngettext # unicoded ngettext
if not isinstance(msgid1, unicode): if not isinstance(msgid1, six.text_type):
msgid1 = unicode(msgid1, 'utf-8') msgid1 = six.text_type(msgid1, 'utf-8')
if not isinstance(msgid2, unicode): if not isinstance(msgid2, six.text_type):
msgid2 = unicode(msgid2, 'utf-8') msgid2 = six.text_type(msgid2, 'utf-8')
domain = gettext._current_domain domain = gettext._current_domain
try: try:
t = gettext.translation(domain, t = gettext.translation(domain,

View file

@ -23,6 +23,7 @@
# imports # imports
import sys import sys
import six
import os import os
import traceback import traceback
@ -37,9 +38,6 @@ from pysollib.pysoltk import TOOLBAR_BUTTONS, TOOLKIT
from pysollib.mygettext import _ from pysollib.mygettext import _
if sys.version_info > (3,):
unicode = str
# ************************************************************************ # ************************************************************************
# * Options # * Options
# ************************************************************************ # ************************************************************************
@ -516,7 +514,7 @@ class Options:
val = getattr(self, key) val = getattr(self, key)
if isinstance(val, str): if isinstance(val, str):
if sys.version_info < (3,): if sys.version_info < (3,):
val = unicode(val, 'utf-8') val = six.text_type(val, 'utf-8')
config['general'][key] = val config['general'][key] = val
config['general']['recent_gameid'] = self.recent_gameid config['general']['recent_gameid'] = self.recent_gameid

View file

@ -23,15 +23,12 @@
# imports # imports
import sys
import gtk import gtk
import six
# PySol imports # PySol imports
from pysollib.mygettext import _ from pysollib.mygettext import _
if sys.version_info > (3,):
unicode = str
# ************************************************************************ # ************************************************************************
# * # *
# ************************************************************************ # ************************************************************************
@ -69,7 +66,7 @@ class BasicStatusbar:
for k, v in kw.items(): for k, v in kw.items():
label = getattr(self, k + "_label") label = getattr(self, k + "_label")
label.pop(0) label.pop(0)
label.push(0, unicode(v)) label.push(0, six.text_type(v))
def config(self, name, show): def config(self, name, show):
# FIXME # FIXME
@ -79,7 +76,7 @@ class BasicStatusbar:
label = getattr(self, name + "_label") label = getattr(self, name + "_label")
# FIXME kw['fg'] # FIXME kw['fg']
label.pop(0) label.pop(0)
label.push(0, unicode(kw['text'])) label.push(0, six.text_type(kw['text']))
def show(self, show=True, resize=False): def show(self, show=True, resize=False):
if show: if show:

View file

@ -24,6 +24,7 @@
# imports # imports
import os import os
import sys import sys
import six
import htmllib import htmllib
import formatter import formatter
import traceback import traceback
@ -47,9 +48,6 @@ if __name__ == '__main__':
import gettext import gettext
gettext.install('pysol', d, unicode=True) gettext.install('pysol', d, unicode=True)
if sys.version_info > (3,):
unicode = str
REMOTE_PROTOCOLS = ('ftp:', 'gopher:', 'http:', 'mailto:', 'news:', 'telnet:') REMOTE_PROTOCOLS = ('ftp:', 'gopher:', 'http:', 'mailto:', 'news:', 'telnet:')
@ -72,7 +70,7 @@ class tkHTMLWriter(formatter.NullWriter):
self.indent = '' self.indent = ''
def write(self, data): def write(self, data):
data = unicode(data) data = six.text_type(data)
self.text.insert(self.text.get_end_iter(), data, len(data)) self.text.insert(self.text.get_end_iter(), data, len(data))
def anchor_bgn(self, href, name, type): def anchor_bgn(self, href, name, type):

View file

@ -24,9 +24,9 @@
# imports # imports
import os import os
import sys
import glob import glob
import traceback import traceback
import six
# PySol imports # PySol imports
from pysollib.mfxutil import Struct, KwStruct from pysollib.mfxutil import Struct, KwStruct
@ -38,9 +38,6 @@ from pysollib.mygettext import _
# * Abstract # * Abstract
# ************************************************************************ # ************************************************************************
if sys.version_info > (3,):
basestring = str
class Resource(Struct): class Resource(Struct):
def __init__(self, **kw): def __init__(self, **kw):
@ -386,7 +383,7 @@ class Cardset(Resource):
def updateCardback(self, backname=None, backindex=None): def updateCardback(self, backname=None, backindex=None):
# update default back # update default back
if isinstance(backname, basestring): if isinstance(backname, six.string_types):
if backname in self.backnames: if backname in self.backnames:
backindex = self.backnames.index(backname) backindex = self.backnames.index(backname)
if isinstance(backindex, int): if isinstance(backindex, int):

View file

@ -23,7 +23,7 @@
# imports # imports
import sys import six
from six.moves import tkinter from six.moves import tkinter
from six.moves import tkinter_colorchooser from six.moves import tkinter_colorchooser
from . import ttk from . import ttk
@ -39,10 +39,6 @@ from .selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode
from .selecttree import SelectDialogTreeCanvas from .selecttree import SelectDialogTreeCanvas
if sys.version_info > (3,):
basestring = str
# ************************************************************************ # ************************************************************************
# * Nodes # * Nodes
# ************************************************************************ # ************************************************************************
@ -169,7 +165,7 @@ class SelectTileDialogWithPreview(MfxDialog):
def mDone(self, button): def mDone(self, button):
if button == 0: # "OK" or double click if button == 0: # "OK" or double click
if isinstance(self.tree.selection_key, basestring): if isinstance(self.tree.selection_key, six.string_types):
self.key = str(self.tree.selection_key) self.key = str(self.tree.selection_key)
else: else:
self.key = self.tree.selection_key self.key = self.tree.selection_key
@ -197,7 +193,7 @@ class SelectTileDialogWithPreview(MfxDialog):
return return
canvas = self.preview.canvas canvas = self.preview.canvas
canvas.deleteAllItems() canvas.deleteAllItems()
if isinstance(key, basestring): if isinstance(key, six.string_types):
# solid color # solid color
canvas.config(bg=key) canvas.config(bg=key)
canvas.setTile(None) canvas.setTile(None)

View file

@ -24,6 +24,7 @@
# imports # imports
import os import os
import sys import sys
import six
from six.moves import tkinter from six.moves import tkinter
from . import ttk from . import ttk
@ -39,9 +40,6 @@ if __name__ == '__main__':
import gettext import gettext
gettext.install('pysol', d, unicode=True) gettext.install('pysol', d, unicode=True)
if sys.version_info > (3,):
unicode = str
# ************************************************************************ # ************************************************************************
# * # *
# ************************************************************************ # ************************************************************************
@ -99,7 +97,7 @@ class MfxStatusbar:
def updateText(self, **kw): def updateText(self, **kw):
for k, v in kw.items(): for k, v in kw.items():
label = getattr(self, k + '_label') label = getattr(self, k + '_label')
text = unicode(v) text = six.text_type(v)
width = label['width'] width = label['width']
if width and len(text) > width: if width and len(text) > width:
label['width'] = len(text) label['width'] = len(text)

View file

@ -22,7 +22,6 @@
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# imports # imports
import sys
import os import os
import time import time
import locale import locale
@ -30,6 +29,7 @@ from six.moves import tkinter
from . import ttk from . import ttk
from six.moves import tkinter_font from six.moves import tkinter_font
from six import PY2 from six import PY2
import six
import traceback import traceback
# PySol imports # PySol imports
@ -43,9 +43,6 @@ from pysollib.ui.tktile.tkutil import bind, unbind_destroy
from pysollib.ui.tktile.tkutil import makeToplevel, setTransient from pysollib.ui.tktile.tkutil import makeToplevel, setTransient
from pysollib.ui.tktile.tkcanvas import MfxCanvas from pysollib.ui.tktile.tkcanvas import MfxCanvas
if sys.version_info > (3,):
unicode = str
# ************************************************************************ # ************************************************************************
# * abstract base class for the dialogs in this module # * abstract base class for the dialogs in this module
# ************************************************************************ # ************************************************************************
@ -125,9 +122,9 @@ class MfxDialog: # ex. _ToplevelDialog
key = event.char key = event.char
try: try:
if os.name == 'nt': if os.name == 'nt':
key = unicode(key, locale.getpreferredencoding()) key = six.text_type(key, locale.getpreferredencoding())
else: else:
key = unicode(key, 'utf-8') key = six.text_type(key, 'utf-8')
except Exception: except Exception:
pass pass
else: else:
@ -294,7 +291,7 @@ class MfxExceptionDialog(MfxMessageDialog):
else: else:
t = str(ex) t = str(ex)
if PY2: if PY2:
t = unicode(t, errors='replace') t = six.text_type(t, errors='replace')
kw.text = text + t kw.text = text + t
MfxMessageDialog.__init__(self, parent, title, **kw.getKw()) MfxMessageDialog.__init__(self, parent, title, **kw.getKw())
@ -318,13 +315,10 @@ class PysolAboutDialog(MfxMessageDialog):
width=kw.width) width=kw.width)
msg.pack(fill='both', expand=True) msg.pack(fill='both', expand=True)
if sys.version_info >= (2, 4): # font_name = msg.lookup('TLabel', 'font')
# font_name = msg.lookup('TLabel', 'font') font_name = 'TkDefaultFont'
font_name = 'TkDefaultFont' font = tkinter_font.Font(parent, name=font_name, exists=True)
font = tkinter_font.Font(parent, name=font_name, exists=True) font = font.copy()
font = font.copy()
else:
font = tkinter_font.Font(parent, app.getFont('default'))
font.configure(underline=True) font.configure(underline=True)
url_label = ttk.Label(frame, text=kw.url, font=font, url_label = ttk.Label(frame, text=kw.url, font=font,
foreground='blue', cursor='hand2') foreground='blue', cursor='hand2')

View file

@ -16,18 +16,14 @@ __version__ = "0.3"
__author__ = "Guilherme Polo <ggpolo@gmail.com>" __author__ = "Guilherme Polo <ggpolo@gmail.com>"
import sys
from six.moves import tkinter from six.moves import tkinter
import six
_flatten = tkinter._flatten _flatten = tkinter._flatten
# Verify if Tk is new enough to not need Tile checking # Verify if Tk is new enough to not need Tile checking
_REQUIRE_TILE = True if tkinter.TkVersion < 8.5 else False _REQUIRE_TILE = True if tkinter.TkVersion < 8.5 else False
if sys.version_info > (3,):
basestring = str
unicode = str
def _loadttk(loadtk): def _loadttk(loadtk):
# This extends the default tkinter.Tk._loadtk method so we can be # This extends the default tkinter.Tk._loadtk method so we can be
@ -68,8 +64,8 @@ def _format_optdict(optdict, script=False, ignore=None):
if isinstance(value, (list, tuple)): if isinstance(value, (list, tuple)):
v = [] v = []
for val in value: for val in value:
if isinstance(val, basestring): if isinstance(val, six.string_types):
v.append(unicode(val) if val else '{}') v.append(six.text_type(val) if val else '{}')
else: else:
v.append(str(val)) v.append(str(val))
@ -226,11 +222,12 @@ def _script_from_settings(settings):
# will format specific keys according to Tcl code # will format specific keys according to Tcl code
if opts.get('configure'): # format 'configure' if opts.get('configure'): # format 'configure'
s = ' '.join( s = ' '.join(
map(unicode, _format_optdict(opts['configure'], True))) map(six.text_type, _format_optdict(opts['configure'], True)))
script.append("ttk::style configure %s %s;" % (name, s)) script.append("ttk::style configure %s %s;" % (name, s))
if opts.get('map'): # format 'map' if opts.get('map'): # format 'map'
s = ' '.join(map(unicode, _format_mapdict(opts['map'], True))) s = ' '.join(map(six.text_type,
_format_mapdict(opts['map'], True)))
script.append("ttk::style map %s %s;" % (name, s)) script.append("ttk::style map %s %s;" % (name, s))
if 'layout' in opts: # format 'layout' which may be empty if 'layout' in opts: # format 'layout' which may be empty
@ -338,7 +335,7 @@ def _val_or_dict(options, func, *args):
def _convert_stringval(value): def _convert_stringval(value):
"""Converts a value to, hopefully, a more appropriate Python object.""" """Converts a value to, hopefully, a more appropriate Python object."""
value = unicode(value) value = six.text_type(value)
try: try:
value = int(value) value = int(value)
except (ValueError, TypeError): except (ValueError, TypeError):
@ -351,7 +348,8 @@ def tclobjs_to_py(adict):
"""Returns adict with its values converted from Tcl objects to Python """Returns adict with its values converted from Tcl objects to Python
objects.""" objects."""
for opt, val in adict.items(): for opt, val in adict.items():
if val and hasattr(val, '__len__') and not isinstance(val, basestring): if val and hasattr(val, '__len__') and \
not isinstance(val, six.string_types):
if getattr(val[0], 'typename', None) == 'StateSpec': if getattr(val[0], 'typename', None) == 'StateSpec':
val = _list_from_statespec(val) val = _list_from_statespec(val)
else: else:
@ -1234,7 +1232,7 @@ class Treeview(Widget):
To configure the tree column heading, call this with column = "#0" """ To configure the tree column heading, call this with column = "#0" """
cmd = kw.get('command') cmd = kw.get('command')
if cmd and not isinstance(cmd, basestring): if cmd and not isinstance(cmd, six.string_types):
# callback not registered yet, do it now # callback not registered yet, do it now
kw['command'] = self.master.register(cmd, self._substitute) kw['command'] = self.master.register(cmd, self._substitute)

View file

@ -22,8 +22,8 @@
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# imports # imports
import sys
import six
from six.moves import tkinter from six.moves import tkinter
from . import ttk from . import ttk
@ -37,9 +37,6 @@ from pysollib.wizardpresets import presets
from .tkwidget import MfxDialog from .tkwidget import MfxDialog
from .tkwidget import PysolScale, PysolCombo from .tkwidget import PysolScale, PysolCombo
if sys.version_info > (3,):
basestring = str
# ************************************************************************ # ************************************************************************
# * # *
# ************************************************************************ # ************************************************************************
@ -60,7 +57,7 @@ class WizardDialog(MfxDialog):
notebook.pack(expand=True, fill='both') notebook.pack(expand=True, fill='both')
for w in WizardWidgets: for w in WizardWidgets:
if isinstance(w, basestring): if isinstance(w, six.string_types):
frame = ttk.Frame(notebook) frame = ttk.Frame(notebook)
notebook.add(frame, text=w, sticky='nsew', padding=5) notebook.add(frame, text=w, sticky='nsew', padding=5)
frame.columnconfigure(1, weight=1) frame.columnconfigure(1, weight=1)
@ -139,7 +136,7 @@ class WizardDialog(MfxDialog):
n = w.translation_map[n] n = w.translation_map[n]
p = presets[n] p = presets[n]
for w in WizardWidgets: for w in WizardWidgets:
if isinstance(w, basestring): if isinstance(w, six.string_types):
continue continue
if w.var_name in p: if w.var_name in p:
v = p[w.var_name] v = p[w.var_name]

View file

@ -23,7 +23,7 @@
# imports # imports
import sys import six
from six.moves import tkinter, tkinter_colorchooser from six.moves import tkinter, tkinter_colorchooser
# PySol imports # PySol imports
@ -37,10 +37,6 @@ from .selecttree import SelectDialogTreeCanvas
from pysollib.ui.tktile.selecttree import SelectDialogTreeData from pysollib.ui.tktile.selecttree import SelectDialogTreeData
if sys.version_info > (3,):
basestring = str
# ************************************************************************ # ************************************************************************
# * Nodes # * Nodes
# ************************************************************************ # ************************************************************************
@ -167,7 +163,7 @@ class SelectTileDialogWithPreview(MfxDialog):
def mDone(self, button): def mDone(self, button):
if button == 0: # "OK" or double click if button == 0: # "OK" or double click
if isinstance(self.tree.selection_key, basestring): if isinstance(self.tree.selection_key, six.string_types):
self.key = str(self.tree.selection_key) self.key = str(self.tree.selection_key)
else: else:
self.key = self.tree.selection_key self.key = self.tree.selection_key
@ -196,7 +192,7 @@ class SelectTileDialogWithPreview(MfxDialog):
return return
canvas = self.preview.canvas canvas = self.preview.canvas
canvas.deleteAllItems() canvas.deleteAllItems()
if isinstance(key, basestring): if isinstance(key, six.string_types):
# solid color # solid color
canvas.config(bg=key) canvas.config(bg=key)
canvas.setTile(None) canvas.setTile(None)

View file

@ -24,15 +24,12 @@
# imports # imports
import os import os
import sys import sys
import six
from six.moves import tkinter from six.moves import tkinter
from pysollib.mygettext import _ from pysollib.mygettext import _
from .tkwidget import MfxTooltip from .tkwidget import MfxTooltip
from pysollib.settings import WIN_SYSTEM from pysollib.settings import WIN_SYSTEM
if sys.version_info > (3,):
unicode = str
if __name__ == '__main__': if __name__ == '__main__':
d = os.path.abspath(os.path.join(sys.path[0], os.pardir, os.pardir)) d = os.path.abspath(os.path.join(sys.path[0], os.pardir, os.pardir))
sys.path.append(d) sys.path.append(d)
@ -97,7 +94,7 @@ class MfxStatusbar:
def updateText(self, **kw): def updateText(self, **kw):
for k, v in kw.items(): for k, v in kw.items():
label = getattr(self, k + '_label') label = getattr(self, k + '_label')
text = unicode(v) text = six.text_type(v)
width = label['width'] width = label['width']
if width and len(text) > width: if width and len(text) > width:
label['width'] = len(text) label['width'] = len(text)

View file

@ -22,7 +22,7 @@
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# imports # imports
import sys import six
import time import time
from six.moves import tkinter from six.moves import tkinter
from six.moves import tkinter_font from six.moves import tkinter_font
@ -39,9 +39,6 @@ from pysollib.ui.tktile.tkutil import bind, unbind_destroy
from pysollib.ui.tktile.tkutil import makeToplevel, setTransient from pysollib.ui.tktile.tkutil import makeToplevel, setTransient
from pysollib.ui.tktile.tkcanvas import MfxCanvas from pysollib.ui.tktile.tkcanvas import MfxCanvas
if sys.version_info > (3,):
unicode = str
# ************************************************************************ # ************************************************************************
# * abstract base class for the dialogs in this module # * abstract base class for the dialogs in this module
# ************************************************************************ # ************************************************************************
@ -136,7 +133,7 @@ class MfxDialog: # ex. _ToplevelDialog
def altKeyEvent(self, event): def altKeyEvent(self, event):
key = event.char key = event.char
key = unicode(key, 'utf-8') key = six.text_type(key, 'utf-8')
key = key.lower() key = key.lower()
button = self.accel_keys.get(key) button = self.accel_keys.get(key)
if button is not None: if button is not None:
@ -291,7 +288,7 @@ class MfxExceptionDialog(MfxMessageDialog):
(ex.errno, ex.strerror, repr(ex.filename)) (ex.errno, ex.strerror, repr(ex.filename))
else: else:
t = str(ex) t = str(ex)
kw.text = text + unicode(t, errors='replace') kw.text = text + six.text_type(t, errors='replace')
MfxMessageDialog.__init__(self, parent, title, **kw.getKw()) MfxMessageDialog.__init__(self, parent, title, **kw.getKw())

View file

@ -22,7 +22,7 @@
# ---------------------------------------------------------------------------## # ---------------------------------------------------------------------------##
# imports # imports
import sys import six
from six.moves import tkinter from six.moves import tkinter
from .tabpage import TabPageSet from .tabpage import TabPageSet
@ -36,10 +36,6 @@ from pysollib.wizardpresets import presets
from .tkwidget import MfxDialog from .tkwidget import MfxDialog
if sys.version_info > (3,):
basestring = str
# ************************************************************************ # ************************************************************************
# * # *
# ************************************************************************ # ************************************************************************
@ -59,7 +55,7 @@ class WizardDialog(MfxDialog):
notebook.pack(expand=True, fill='both') notebook.pack(expand=True, fill='both')
for w in WizardWidgets: for w in WizardWidgets:
if isinstance(w, basestring): if isinstance(w, six.string_types):
notebook.AddPage(w) notebook.AddPage(w)
frame = tkinter.Frame(notebook.pages[w]['page']) frame = tkinter.Frame(notebook.pages[w]['page'])
frame.pack(expand=True, fill='both', padx=2, pady=4) frame.pack(expand=True, fill='both', padx=2, pady=4)
@ -128,7 +124,7 @@ class WizardDialog(MfxDialog):
n = w.translation_map[v] n = w.translation_map[v]
p = presets[n] p = presets[n]
for w in WizardWidgets: for w in WizardWidgets:
if isinstance(w, basestring): if isinstance(w, six.string_types):
continue continue
if w.var_name in p: if w.var_name in p:
v = p[w.var_name] v = p[w.var_name]

View file

@ -21,8 +21,8 @@
# #
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
import sys
import os import os
import six
from pysollib.gamedb import GI, loadGame from pysollib.gamedb import GI, loadGame
from pysollib.util import ACE, ANY_RANK, KING, NO_RANK, UNLIMITED_MOVES from pysollib.util import ACE, ANY_RANK, KING, NO_RANK, UNLIMITED_MOVES
@ -60,10 +60,6 @@ from pysollib.wizardpresets import presets
from pysollib.mygettext import _, n_ from pysollib.mygettext import _, n_
if sys.version_info > (3,):
basestring = str
unicode = str
# ************************************************************************ # ************************************************************************
# * # *
# ************************************************************************ # ************************************************************************
@ -420,7 +416,7 @@ class MyCustomGame(CustomGame):
''') ''')
for w in WizardWidgets: for w in WizardWidgets:
if isinstance(w, basestring): if isinstance(w, six.string_types):
continue continue
v = w.variable.get() v = w.variable.get()
if w.widget in ('menu', 'preset'): if w.widget in ('menu', 'preset'):
@ -435,7 +431,7 @@ class MyCustomGame(CustomGame):
# escape # escape
v = v.replace('\\', '\\\\') v = v.replace('\\', '\\\\')
v = v.replace("'", "\\'") v = v.replace("'", "\\'")
if isinstance(v, unicode): if isinstance(v, six.text_type):
v = v.encode('utf-8') v = v.encode('utf-8')
if not v: if not v:
v = 'Invalid Game Name' v = 'Invalid Game Name'
@ -456,7 +452,7 @@ registerCustomGame(MyCustomGame)
def reset_wizard(game): def reset_wizard(game):
for w in WizardWidgets: for w in WizardWidgets:
if isinstance(w, basestring): if isinstance(w, six.string_types):
continue continue
if game is None: if game is None:
# set to default # set to default