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