jpayne@68: import codecs jpayne@68: from codecs import BOM_UTF8 jpayne@68: import os jpayne@68: import re jpayne@68: import shlex jpayne@68: import sys jpayne@68: import tempfile jpayne@68: jpayne@68: import tkinter.filedialog as tkFileDialog jpayne@68: import tkinter.messagebox as tkMessageBox jpayne@68: from tkinter.simpledialog import askstring jpayne@68: jpayne@68: import idlelib jpayne@68: from idlelib.config import idleConf jpayne@68: jpayne@68: if idlelib.testing: # Set True by test.test_idle to avoid setlocale. jpayne@68: encoding = 'utf-8' jpayne@68: errors = 'surrogateescape' jpayne@68: else: jpayne@68: # Try setting the locale, so that we can find out jpayne@68: # what encoding to use jpayne@68: try: jpayne@68: import locale jpayne@68: locale.setlocale(locale.LC_CTYPE, "") jpayne@68: except (ImportError, locale.Error): jpayne@68: pass jpayne@68: jpayne@68: if sys.platform == 'win32': jpayne@68: encoding = 'utf-8' jpayne@68: errors = 'surrogateescape' jpayne@68: else: jpayne@68: try: jpayne@68: # Different things can fail here: the locale module may not be jpayne@68: # loaded, it may not offer nl_langinfo, or CODESET, or the jpayne@68: # resulting codeset may be unknown to Python. We ignore all jpayne@68: # these problems, falling back to ASCII jpayne@68: locale_encoding = locale.nl_langinfo(locale.CODESET) jpayne@68: if locale_encoding: jpayne@68: codecs.lookup(locale_encoding) jpayne@68: except (NameError, AttributeError, LookupError): jpayne@68: # Try getdefaultlocale: it parses environment variables, jpayne@68: # which may give a clue. Unfortunately, getdefaultlocale has jpayne@68: # bugs that can cause ValueError. jpayne@68: try: jpayne@68: locale_encoding = locale.getdefaultlocale()[1] jpayne@68: if locale_encoding: jpayne@68: codecs.lookup(locale_encoding) jpayne@68: except (ValueError, LookupError): jpayne@68: pass jpayne@68: jpayne@68: if locale_encoding: jpayne@68: encoding = locale_encoding.lower() jpayne@68: errors = 'strict' jpayne@68: else: jpayne@68: # POSIX locale or macOS jpayne@68: encoding = 'ascii' jpayne@68: errors = 'surrogateescape' jpayne@68: # Encoding is used in multiple files; locale_encoding nowhere. jpayne@68: # The only use of 'encoding' below is in _decode as initial value jpayne@68: # of deprecated block asking user for encoding. jpayne@68: # Perhaps use elsewhere should be reviewed. jpayne@68: jpayne@68: coding_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII) jpayne@68: blank_re = re.compile(r'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII) jpayne@68: jpayne@68: def coding_spec(data): jpayne@68: """Return the encoding declaration according to PEP 263. jpayne@68: jpayne@68: When checking encoded data, only the first two lines should be passed jpayne@68: in to avoid a UnicodeDecodeError if the rest of the data is not unicode. jpayne@68: The first two lines would contain the encoding specification. jpayne@68: jpayne@68: Raise a LookupError if the encoding is declared but unknown. jpayne@68: """ jpayne@68: if isinstance(data, bytes): jpayne@68: # This encoding might be wrong. However, the coding jpayne@68: # spec must be ASCII-only, so any non-ASCII characters jpayne@68: # around here will be ignored. Decoding to Latin-1 should jpayne@68: # never fail (except for memory outage) jpayne@68: lines = data.decode('iso-8859-1') jpayne@68: else: jpayne@68: lines = data jpayne@68: # consider only the first two lines jpayne@68: if '\n' in lines: jpayne@68: lst = lines.split('\n', 2)[:2] jpayne@68: elif '\r' in lines: jpayne@68: lst = lines.split('\r', 2)[:2] jpayne@68: else: jpayne@68: lst = [lines] jpayne@68: for line in lst: jpayne@68: match = coding_re.match(line) jpayne@68: if match is not None: jpayne@68: break jpayne@68: if not blank_re.match(line): jpayne@68: return None jpayne@68: else: jpayne@68: return None jpayne@68: name = match.group(1) jpayne@68: try: jpayne@68: codecs.lookup(name) jpayne@68: except LookupError: jpayne@68: # The standard encoding error does not indicate the encoding jpayne@68: raise LookupError("Unknown encoding: "+name) jpayne@68: return name jpayne@68: jpayne@68: jpayne@68: class IOBinding: jpayne@68: # One instance per editor Window so methods know which to save, close. jpayne@68: # Open returns focus to self.editwin if aborted. jpayne@68: # EditorWindow.open_module, others, belong here. jpayne@68: jpayne@68: def __init__(self, editwin): jpayne@68: self.editwin = editwin jpayne@68: self.text = editwin.text jpayne@68: self.__id_open = self.text.bind("<>", self.open) jpayne@68: self.__id_save = self.text.bind("<>", self.save) jpayne@68: self.__id_saveas = self.text.bind("<>", jpayne@68: self.save_as) jpayne@68: self.__id_savecopy = self.text.bind("<>", jpayne@68: self.save_a_copy) jpayne@68: self.fileencoding = None jpayne@68: self.__id_print = self.text.bind("<>", self.print_window) jpayne@68: jpayne@68: def close(self): jpayne@68: # Undo command bindings jpayne@68: self.text.unbind("<>", self.__id_open) jpayne@68: self.text.unbind("<>", self.__id_save) jpayne@68: self.text.unbind("<>",self.__id_saveas) jpayne@68: self.text.unbind("<>", self.__id_savecopy) jpayne@68: self.text.unbind("<>", self.__id_print) jpayne@68: # Break cycles jpayne@68: self.editwin = None jpayne@68: self.text = None jpayne@68: self.filename_change_hook = None jpayne@68: jpayne@68: def get_saved(self): jpayne@68: return self.editwin.get_saved() jpayne@68: jpayne@68: def set_saved(self, flag): jpayne@68: self.editwin.set_saved(flag) jpayne@68: jpayne@68: def reset_undo(self): jpayne@68: self.editwin.reset_undo() jpayne@68: jpayne@68: filename_change_hook = None jpayne@68: jpayne@68: def set_filename_change_hook(self, hook): jpayne@68: self.filename_change_hook = hook jpayne@68: jpayne@68: filename = None jpayne@68: dirname = None jpayne@68: jpayne@68: def set_filename(self, filename): jpayne@68: if filename and os.path.isdir(filename): jpayne@68: self.filename = None jpayne@68: self.dirname = filename jpayne@68: else: jpayne@68: self.filename = filename jpayne@68: self.dirname = None jpayne@68: self.set_saved(1) jpayne@68: if self.filename_change_hook: jpayne@68: self.filename_change_hook() jpayne@68: jpayne@68: def open(self, event=None, editFile=None): jpayne@68: flist = self.editwin.flist jpayne@68: # Save in case parent window is closed (ie, during askopenfile()). jpayne@68: if flist: jpayne@68: if not editFile: jpayne@68: filename = self.askopenfile() jpayne@68: else: jpayne@68: filename=editFile jpayne@68: if filename: jpayne@68: # If editFile is valid and already open, flist.open will jpayne@68: # shift focus to its existing window. jpayne@68: # If the current window exists and is a fresh unnamed, jpayne@68: # unmodified editor window (not an interpreter shell), jpayne@68: # pass self.loadfile to flist.open so it will load the file jpayne@68: # in the current window (if the file is not already open) jpayne@68: # instead of a new window. jpayne@68: if (self.editwin and jpayne@68: not getattr(self.editwin, 'interp', None) and jpayne@68: not self.filename and jpayne@68: self.get_saved()): jpayne@68: flist.open(filename, self.loadfile) jpayne@68: else: jpayne@68: flist.open(filename) jpayne@68: else: jpayne@68: if self.text: jpayne@68: self.text.focus_set() jpayne@68: return "break" jpayne@68: jpayne@68: # Code for use outside IDLE: jpayne@68: if self.get_saved(): jpayne@68: reply = self.maybesave() jpayne@68: if reply == "cancel": jpayne@68: self.text.focus_set() jpayne@68: return "break" jpayne@68: if not editFile: jpayne@68: filename = self.askopenfile() jpayne@68: else: jpayne@68: filename=editFile jpayne@68: if filename: jpayne@68: self.loadfile(filename) jpayne@68: else: jpayne@68: self.text.focus_set() jpayne@68: return "break" jpayne@68: jpayne@68: eol = r"(\r\n)|\n|\r" # \r\n (Windows), \n (UNIX), or \r (Mac) jpayne@68: eol_re = re.compile(eol) jpayne@68: eol_convention = os.linesep # default jpayne@68: jpayne@68: def loadfile(self, filename): jpayne@68: try: jpayne@68: # open the file in binary mode so that we can handle jpayne@68: # end-of-line convention ourselves. jpayne@68: with open(filename, 'rb') as f: jpayne@68: two_lines = f.readline() + f.readline() jpayne@68: f.seek(0) jpayne@68: bytes = f.read() jpayne@68: except OSError as msg: jpayne@68: tkMessageBox.showerror("I/O Error", str(msg), parent=self.text) jpayne@68: return False jpayne@68: chars, converted = self._decode(two_lines, bytes) jpayne@68: if chars is None: jpayne@68: tkMessageBox.showerror("Decoding Error", jpayne@68: "File %s\nFailed to Decode" % filename, jpayne@68: parent=self.text) jpayne@68: return False jpayne@68: # We now convert all end-of-lines to '\n's jpayne@68: firsteol = self.eol_re.search(chars) jpayne@68: if firsteol: jpayne@68: self.eol_convention = firsteol.group(0) jpayne@68: chars = self.eol_re.sub(r"\n", chars) jpayne@68: self.text.delete("1.0", "end") jpayne@68: self.set_filename(None) jpayne@68: self.text.insert("1.0", chars) jpayne@68: self.reset_undo() jpayne@68: self.set_filename(filename) jpayne@68: if converted: jpayne@68: # We need to save the conversion results first jpayne@68: # before being able to execute the code jpayne@68: self.set_saved(False) jpayne@68: self.text.mark_set("insert", "1.0") jpayne@68: self.text.yview("insert") jpayne@68: self.updaterecentfileslist(filename) jpayne@68: return True jpayne@68: jpayne@68: def _decode(self, two_lines, bytes): jpayne@68: "Create a Unicode string." jpayne@68: chars = None jpayne@68: # Check presence of a UTF-8 signature first jpayne@68: if bytes.startswith(BOM_UTF8): jpayne@68: try: jpayne@68: chars = bytes[3:].decode("utf-8") jpayne@68: except UnicodeDecodeError: jpayne@68: # has UTF-8 signature, but fails to decode... jpayne@68: return None, False jpayne@68: else: jpayne@68: # Indicates that this file originally had a BOM jpayne@68: self.fileencoding = 'BOM' jpayne@68: return chars, False jpayne@68: # Next look for coding specification jpayne@68: try: jpayne@68: enc = coding_spec(two_lines) jpayne@68: except LookupError as name: jpayne@68: tkMessageBox.showerror( jpayne@68: title="Error loading the file", jpayne@68: message="The encoding '%s' is not known to this Python "\ jpayne@68: "installation. The file may not display correctly" % name, jpayne@68: parent = self.text) jpayne@68: enc = None jpayne@68: except UnicodeDecodeError: jpayne@68: return None, False jpayne@68: if enc: jpayne@68: try: jpayne@68: chars = str(bytes, enc) jpayne@68: self.fileencoding = enc jpayne@68: return chars, False jpayne@68: except UnicodeDecodeError: jpayne@68: pass jpayne@68: # Try ascii: jpayne@68: try: jpayne@68: chars = str(bytes, 'ascii') jpayne@68: self.fileencoding = None jpayne@68: return chars, False jpayne@68: except UnicodeDecodeError: jpayne@68: pass jpayne@68: # Try utf-8: jpayne@68: try: jpayne@68: chars = str(bytes, 'utf-8') jpayne@68: self.fileencoding = 'utf-8' jpayne@68: return chars, False jpayne@68: except UnicodeDecodeError: jpayne@68: pass jpayne@68: # Finally, try the locale's encoding. This is deprecated; jpayne@68: # the user should declare a non-ASCII encoding jpayne@68: try: jpayne@68: # Wait for the editor window to appear jpayne@68: self.editwin.text.update() jpayne@68: enc = askstring( jpayne@68: "Specify file encoding", jpayne@68: "The file's encoding is invalid for Python 3.x.\n" jpayne@68: "IDLE will convert it to UTF-8.\n" jpayne@68: "What is the current encoding of the file?", jpayne@68: initialvalue = encoding, jpayne@68: parent = self.editwin.text) jpayne@68: jpayne@68: if enc: jpayne@68: chars = str(bytes, enc) jpayne@68: self.fileencoding = None jpayne@68: return chars, True jpayne@68: except (UnicodeDecodeError, LookupError): jpayne@68: pass jpayne@68: return None, False # None on failure jpayne@68: jpayne@68: def maybesave(self): jpayne@68: if self.get_saved(): jpayne@68: return "yes" jpayne@68: message = "Do you want to save %s before closing?" % ( jpayne@68: self.filename or "this untitled document") jpayne@68: confirm = tkMessageBox.askyesnocancel( jpayne@68: title="Save On Close", jpayne@68: message=message, jpayne@68: default=tkMessageBox.YES, jpayne@68: parent=self.text) jpayne@68: if confirm: jpayne@68: reply = "yes" jpayne@68: self.save(None) jpayne@68: if not self.get_saved(): jpayne@68: reply = "cancel" jpayne@68: elif confirm is None: jpayne@68: reply = "cancel" jpayne@68: else: jpayne@68: reply = "no" jpayne@68: self.text.focus_set() jpayne@68: return reply jpayne@68: jpayne@68: def save(self, event): jpayne@68: if not self.filename: jpayne@68: self.save_as(event) jpayne@68: else: jpayne@68: if self.writefile(self.filename): jpayne@68: self.set_saved(True) jpayne@68: try: jpayne@68: self.editwin.store_file_breaks() jpayne@68: except AttributeError: # may be a PyShell jpayne@68: pass jpayne@68: self.text.focus_set() jpayne@68: return "break" jpayne@68: jpayne@68: def save_as(self, event): jpayne@68: filename = self.asksavefile() jpayne@68: if filename: jpayne@68: if self.writefile(filename): jpayne@68: self.set_filename(filename) jpayne@68: self.set_saved(1) jpayne@68: try: jpayne@68: self.editwin.store_file_breaks() jpayne@68: except AttributeError: jpayne@68: pass jpayne@68: self.text.focus_set() jpayne@68: self.updaterecentfileslist(filename) jpayne@68: return "break" jpayne@68: jpayne@68: def save_a_copy(self, event): jpayne@68: filename = self.asksavefile() jpayne@68: if filename: jpayne@68: self.writefile(filename) jpayne@68: self.text.focus_set() jpayne@68: self.updaterecentfileslist(filename) jpayne@68: return "break" jpayne@68: jpayne@68: def writefile(self, filename): jpayne@68: text = self.fixnewlines() jpayne@68: chars = self.encode(text) jpayne@68: try: jpayne@68: with open(filename, "wb") as f: jpayne@68: f.write(chars) jpayne@68: f.flush() jpayne@68: os.fsync(f.fileno()) jpayne@68: return True jpayne@68: except OSError as msg: jpayne@68: tkMessageBox.showerror("I/O Error", str(msg), jpayne@68: parent=self.text) jpayne@68: return False jpayne@68: jpayne@68: def fixnewlines(self): jpayne@68: "Return text with final \n if needed and os eols." jpayne@68: if (self.text.get("end-2c") != '\n' jpayne@68: and not hasattr(self.editwin, "interp")): # Not shell. jpayne@68: self.text.insert("end-1c", "\n") jpayne@68: text = self.text.get("1.0", "end-1c") jpayne@68: if self.eol_convention != "\n": jpayne@68: text = text.replace("\n", self.eol_convention) jpayne@68: return text jpayne@68: jpayne@68: def encode(self, chars): jpayne@68: if isinstance(chars, bytes): jpayne@68: # This is either plain ASCII, or Tk was returning mixed-encoding jpayne@68: # text to us. Don't try to guess further. jpayne@68: return chars jpayne@68: # Preserve a BOM that might have been present on opening jpayne@68: if self.fileencoding == 'BOM': jpayne@68: return BOM_UTF8 + chars.encode("utf-8") jpayne@68: # See whether there is anything non-ASCII in it. jpayne@68: # If not, no need to figure out the encoding. jpayne@68: try: jpayne@68: return chars.encode('ascii') jpayne@68: except UnicodeError: jpayne@68: pass jpayne@68: # Check if there is an encoding declared jpayne@68: try: jpayne@68: # a string, let coding_spec slice it to the first two lines jpayne@68: enc = coding_spec(chars) jpayne@68: failed = None jpayne@68: except LookupError as msg: jpayne@68: failed = msg jpayne@68: enc = None jpayne@68: else: jpayne@68: if not enc: jpayne@68: # PEP 3120: default source encoding is UTF-8 jpayne@68: enc = 'utf-8' jpayne@68: if enc: jpayne@68: try: jpayne@68: return chars.encode(enc) jpayne@68: except UnicodeError: jpayne@68: failed = "Invalid encoding '%s'" % enc jpayne@68: tkMessageBox.showerror( jpayne@68: "I/O Error", jpayne@68: "%s.\nSaving as UTF-8" % failed, jpayne@68: parent = self.text) jpayne@68: # Fallback: save as UTF-8, with BOM - ignoring the incorrect jpayne@68: # declared encoding jpayne@68: return BOM_UTF8 + chars.encode("utf-8") jpayne@68: jpayne@68: def print_window(self, event): jpayne@68: confirm = tkMessageBox.askokcancel( jpayne@68: title="Print", jpayne@68: message="Print to Default Printer", jpayne@68: default=tkMessageBox.OK, jpayne@68: parent=self.text) jpayne@68: if not confirm: jpayne@68: self.text.focus_set() jpayne@68: return "break" jpayne@68: tempfilename = None jpayne@68: saved = self.get_saved() jpayne@68: if saved: jpayne@68: filename = self.filename jpayne@68: # shell undo is reset after every prompt, looks saved, probably isn't jpayne@68: if not saved or filename is None: jpayne@68: (tfd, tempfilename) = tempfile.mkstemp(prefix='IDLE_tmp_') jpayne@68: filename = tempfilename jpayne@68: os.close(tfd) jpayne@68: if not self.writefile(tempfilename): jpayne@68: os.unlink(tempfilename) jpayne@68: return "break" jpayne@68: platform = os.name jpayne@68: printPlatform = True jpayne@68: if platform == 'posix': #posix platform jpayne@68: command = idleConf.GetOption('main','General', jpayne@68: 'print-command-posix') jpayne@68: command = command + " 2>&1" jpayne@68: elif platform == 'nt': #win32 platform jpayne@68: command = idleConf.GetOption('main','General','print-command-win') jpayne@68: else: #no printing for this platform jpayne@68: printPlatform = False jpayne@68: if printPlatform: #we can try to print for this platform jpayne@68: command = command % shlex.quote(filename) jpayne@68: pipe = os.popen(command, "r") jpayne@68: # things can get ugly on NT if there is no printer available. jpayne@68: output = pipe.read().strip() jpayne@68: status = pipe.close() jpayne@68: if status: jpayne@68: output = "Printing failed (exit status 0x%x)\n" % \ jpayne@68: status + output jpayne@68: if output: jpayne@68: output = "Printing command: %s\n" % repr(command) + output jpayne@68: tkMessageBox.showerror("Print status", output, parent=self.text) jpayne@68: else: #no printing for this platform jpayne@68: message = "Printing is not enabled for this platform: %s" % platform jpayne@68: tkMessageBox.showinfo("Print status", message, parent=self.text) jpayne@68: if tempfilename: jpayne@68: os.unlink(tempfilename) jpayne@68: return "break" jpayne@68: jpayne@68: opendialog = None jpayne@68: savedialog = None jpayne@68: jpayne@68: filetypes = ( jpayne@68: ("Python files", "*.py *.pyw", "TEXT"), jpayne@68: ("Text files", "*.txt", "TEXT"), jpayne@68: ("All files", "*"), jpayne@68: ) jpayne@68: jpayne@68: defaultextension = '.py' if sys.platform == 'darwin' else '' jpayne@68: jpayne@68: def askopenfile(self): jpayne@68: dir, base = self.defaultfilename("open") jpayne@68: if not self.opendialog: jpayne@68: self.opendialog = tkFileDialog.Open(parent=self.text, jpayne@68: filetypes=self.filetypes) jpayne@68: filename = self.opendialog.show(initialdir=dir, initialfile=base) jpayne@68: return filename jpayne@68: jpayne@68: def defaultfilename(self, mode="open"): jpayne@68: if self.filename: jpayne@68: return os.path.split(self.filename) jpayne@68: elif self.dirname: jpayne@68: return self.dirname, "" jpayne@68: else: jpayne@68: try: jpayne@68: pwd = os.getcwd() jpayne@68: except OSError: jpayne@68: pwd = "" jpayne@68: return pwd, "" jpayne@68: jpayne@68: def asksavefile(self): jpayne@68: dir, base = self.defaultfilename("save") jpayne@68: if not self.savedialog: jpayne@68: self.savedialog = tkFileDialog.SaveAs( jpayne@68: parent=self.text, jpayne@68: filetypes=self.filetypes, jpayne@68: defaultextension=self.defaultextension) jpayne@68: filename = self.savedialog.show(initialdir=dir, initialfile=base) jpayne@68: return filename jpayne@68: jpayne@68: def updaterecentfileslist(self,filename): jpayne@68: "Update recent file list on all editor windows" jpayne@68: if self.editwin.flist: jpayne@68: self.editwin.update_recent_files_list(filename) jpayne@68: jpayne@68: def _io_binding(parent): # htest # jpayne@68: from tkinter import Toplevel, Text jpayne@68: jpayne@68: root = Toplevel(parent) jpayne@68: root.title("Test IOBinding") jpayne@68: x, y = map(int, parent.geometry().split('+')[1:]) jpayne@68: root.geometry("+%d+%d" % (x, y + 175)) jpayne@68: class MyEditWin: jpayne@68: def __init__(self, text): jpayne@68: self.text = text jpayne@68: self.flist = None jpayne@68: self.text.bind("", self.open) jpayne@68: self.text.bind('', self.print) jpayne@68: self.text.bind("", self.save) jpayne@68: self.text.bind("", self.saveas) jpayne@68: self.text.bind('', self.savecopy) jpayne@68: def get_saved(self): return 0 jpayne@68: def set_saved(self, flag): pass jpayne@68: def reset_undo(self): pass jpayne@68: def open(self, event): jpayne@68: self.text.event_generate("<>") jpayne@68: def print(self, event): jpayne@68: self.text.event_generate("<>") jpayne@68: def save(self, event): jpayne@68: self.text.event_generate("<>") jpayne@68: def saveas(self, event): jpayne@68: self.text.event_generate("<>") jpayne@68: def savecopy(self, event): jpayne@68: self.text.event_generate("<>") jpayne@68: jpayne@68: text = Text(root) jpayne@68: text.pack() jpayne@68: text.focus_set() jpayne@68: editwin = MyEditWin(text) jpayne@68: IOBinding(editwin) jpayne@68: jpayne@68: if __name__ == "__main__": jpayne@68: from unittest import main jpayne@68: main('idlelib.idle_test.test_iomenu', verbosity=2, exit=False) jpayne@68: jpayne@68: from idlelib.idle_test.htest import run jpayne@68: run(_io_binding)