From 04a9b4c910880fe29908a82081b9d3d98e49b967 Mon Sep 17 00:00:00 2001 From: Shlomi Fish Date: Mon, 30 Apr 2018 20:33:23 +0300 Subject: [PATCH] Handle the utf-8 BOM in the import. --- pysollib/hint.py | 14 +++++++++++++- pysollib/ui/tktile/menubar.py | 11 +++++++---- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/pysollib/hint.py b/pysollib/hint.py index 70496272..0a2c6a38 100644 --- a/pysollib/hint.py +++ b/pysollib/hint.py @@ -875,7 +875,19 @@ class FreeCellSolver_Hint(Base_Solver_Hint): assert re.match(r'^\s*(?:' + RE + r')?(?:\s+' + RE + r')*\s*$', s) return re.findall(r'\b' + RE + r'\b', s) - for line_p in fh: + # Based on https://stackoverflow.com/questions/8898294 - thanks! + def mydecode(s): + if sys.version_info < (3,): + return s + for encoding in "utf-8-sig", "utf-8": + try: + return s.decode(encoding) + except UnicodeDecodeError: + continue + return s.decode("latin-1") # will always work + + mytext = mydecode(fh.read()) + for line_p in mytext.splitlines(): line = line_p.rstrip('\r\n') m = re.match(r'^(?:Foundations:|Founds?:)\s*(.*)', line) if m: diff --git a/pysollib/ui/tktile/menubar.py b/pysollib/ui/tktile/menubar.py index 69266463..c363ec66 100644 --- a/pysollib/ui/tktile/menubar.py +++ b/pysollib/ui/tktile/menubar.py @@ -1226,14 +1226,17 @@ Unsupported game for import. if not idir: idir = self.app.dn.savegames d = tkinter_tkfiledialog.Open() - filename = d.show(filetypes=self.FILETYPES, - defaultextension=self.DEFAULTEXTENSION, - initialdir=idir, initialfile=ifile) + if True: + filename = d.show(filetypes=self.FILETYPES, + defaultextension=self.DEFAULTEXTENSION, + initialdir=idir, initialfile=ifile) + else: + filename = '/home/shlomif/m2.txt' if filename: filename = os.path.normpath(filename) # filename = os.path.normcase(filename) if os.path.isfile(filename): - with open(filename, 'r') as fh: + with open(filename, 'r+b') as fh: game = self.game game.Solver_Class(game, self).importFile(fh, game, self)