ยปCore Development>Code coverage>Lib/idlelib/IOBinding.py

Python code coverage for Lib/idlelib/IOBinding.py

#countcontent
1n/aimport os
2n/aimport types
3n/aimport shlex
4n/aimport sys
5n/aimport codecs
6n/aimport tempfile
7n/aimport tkinter.filedialog as tkFileDialog
8n/aimport tkinter.messagebox as tkMessageBox
9n/aimport re
10n/afrom tkinter import *
11n/afrom tkinter.simpledialog import askstring
12n/a
13n/afrom idlelib.configHandler import idleConf
14n/a
15n/afrom codecs import BOM_UTF8
16n/a
17n/a# Try setting the locale, so that we can find out
18n/a# what encoding to use
19n/atry:
20n/a import locale
21n/a locale.setlocale(locale.LC_CTYPE, "")
22n/aexcept (ImportError, locale.Error):
23n/a pass
24n/a
25n/a# Encoding for file names
26n/afilesystemencoding = sys.getfilesystemencoding() ### currently unused
27n/a
28n/alocale_encoding = 'ascii'
29n/aif sys.platform == 'win32':
30n/a # On Windows, we could use "mbcs". However, to give the user
31n/a # a portable encoding name, we need to find the code page
32n/a try:
33n/a locale_encoding = locale.getdefaultlocale()[1]
34n/a codecs.lookup(locale_encoding)
35n/a except LookupError:
36n/a pass
37n/aelse:
38n/a try:
39n/a # Different things can fail here: the locale module may not be
40n/a # loaded, it may not offer nl_langinfo, or CODESET, or the
41n/a # resulting codeset may be unknown to Python. We ignore all
42n/a # these problems, falling back to ASCII
43n/a locale_encoding = locale.nl_langinfo(locale.CODESET)
44n/a if locale_encoding is None or locale_encoding is '':
45n/a # situation occurs on Mac OS X
46n/a locale_encoding = 'ascii'
47n/a codecs.lookup(locale_encoding)
48n/a except (NameError, AttributeError, LookupError):
49n/a # Try getdefaultlocale: it parses environment variables,
50n/a # which may give a clue. Unfortunately, getdefaultlocale has
51n/a # bugs that can cause ValueError.
52n/a try:
53n/a locale_encoding = locale.getdefaultlocale()[1]
54n/a if locale_encoding is None or locale_encoding is '':
55n/a # situation occurs on Mac OS X
56n/a locale_encoding = 'ascii'
57n/a codecs.lookup(locale_encoding)
58n/a except (ValueError, LookupError):
59n/a pass
60n/a
61n/alocale_encoding = locale_encoding.lower()
62n/a
63n/aencoding = locale_encoding ### KBK 07Sep07 This is used all over IDLE, check!
64n/a ### 'encoding' is used below in encode(), check!
65n/a
66n/acoding_re = re.compile("coding[:=]\s*([-\w_.]+)")
67n/a
68n/adef coding_spec(data):
69n/a """Return the encoding declaration according to PEP 263.
70n/a
71n/a When checking encoded data, only the first two lines should be passed
72n/a in to avoid a UnicodeDecodeError if the rest of the data is not unicode.
73n/a The first two lines would contain the encoding specification.
74n/a
75n/a Raise a LookupError if the encoding is declared but unknown.
76n/a """
77n/a if isinstance(data, bytes):
78n/a # This encoding might be wrong. However, the coding
79n/a # spec must be ASCII-only, so any non-ASCII characters
80n/a # around here will be ignored. Decoding to Latin-1 should
81n/a # never fail (except for memory outage)
82n/a lines = data.decode('iso-8859-1')
83n/a else:
84n/a lines = data
85n/a # consider only the first two lines
86n/a if '\n' in lines:
87n/a lst = lines.split('\n')[:2]
88n/a elif '\r' in lines:
89n/a lst = lines.split('\r')[:2]
90n/a else:
91n/a lst = list(lines)
92n/a str = '\n'.join(lst)
93n/a match = coding_re.search(str)
94n/a if not match:
95n/a return None
96n/a name = match.group(1)
97n/a try:
98n/a codecs.lookup(name)
99n/a except LookupError:
100n/a # The standard encoding error does not indicate the encoding
101n/a raise LookupError("Unknown encoding: "+name)
102n/a return name
103n/a
104n/a
105n/aclass IOBinding:
106n/a
107n/a def __init__(self, editwin):
108n/a self.editwin = editwin
109n/a self.text = editwin.text
110n/a self.__id_open = self.text.bind("<<open-window-from-file>>", self.open)
111n/a self.__id_save = self.text.bind("<<save-window>>", self.save)
112n/a self.__id_saveas = self.text.bind("<<save-window-as-file>>",
113n/a self.save_as)
114n/a self.__id_savecopy = self.text.bind("<<save-copy-of-window-as-file>>",
115n/a self.save_a_copy)
116n/a self.fileencoding = None
117n/a self.__id_print = self.text.bind("<<print-window>>", self.print_window)
118n/a
119n/a def close(self):
120n/a # Undo command bindings
121n/a self.text.unbind("<<open-window-from-file>>", self.__id_open)
122n/a self.text.unbind("<<save-window>>", self.__id_save)
123n/a self.text.unbind("<<save-window-as-file>>",self.__id_saveas)
124n/a self.text.unbind("<<save-copy-of-window-as-file>>", self.__id_savecopy)
125n/a self.text.unbind("<<print-window>>", self.__id_print)
126n/a # Break cycles
127n/a self.editwin = None
128n/a self.text = None
129n/a self.filename_change_hook = None
130n/a
131n/a def get_saved(self):
132n/a return self.editwin.get_saved()
133n/a
134n/a def set_saved(self, flag):
135n/a self.editwin.set_saved(flag)
136n/a
137n/a def reset_undo(self):
138n/a self.editwin.reset_undo()
139n/a
140n/a filename_change_hook = None
141n/a
142n/a def set_filename_change_hook(self, hook):
143n/a self.filename_change_hook = hook
144n/a
145n/a filename = None
146n/a dirname = None
147n/a
148n/a def set_filename(self, filename):
149n/a if filename and os.path.isdir(filename):
150n/a self.filename = None
151n/a self.dirname = filename
152n/a else:
153n/a self.filename = filename
154n/a self.dirname = None
155n/a self.set_saved(1)
156n/a if self.filename_change_hook:
157n/a self.filename_change_hook()
158n/a
159n/a def open(self, event=None, editFile=None):
160n/a flist = self.editwin.flist
161n/a # Save in case parent window is closed (ie, during askopenfile()).
162n/a if flist:
163n/a if not editFile:
164n/a filename = self.askopenfile()
165n/a else:
166n/a filename=editFile
167n/a if filename:
168n/a # If editFile is valid and already open, flist.open will
169n/a # shift focus to its existing window.
170n/a # If the current window exists and is a fresh unnamed,
171n/a # unmodified editor window (not an interpreter shell),
172n/a # pass self.loadfile to flist.open so it will load the file
173n/a # in the current window (if the file is not already open)
174n/a # instead of a new window.
175n/a if (self.editwin and
176n/a not getattr(self.editwin, 'interp', None) and
177n/a not self.filename and
178n/a self.get_saved()):
179n/a flist.open(filename, self.loadfile)
180n/a else:
181n/a flist.open(filename)
182n/a else:
183n/a if self.text:
184n/a self.text.focus_set()
185n/a return "break"
186n/a
187n/a # Code for use outside IDLE:
188n/a if self.get_saved():
189n/a reply = self.maybesave()
190n/a if reply == "cancel":
191n/a self.text.focus_set()
192n/a return "break"
193n/a if not editFile:
194n/a filename = self.askopenfile()
195n/a else:
196n/a filename=editFile
197n/a if filename:
198n/a self.loadfile(filename)
199n/a else:
200n/a self.text.focus_set()
201n/a return "break"
202n/a
203n/a eol = r"(\r\n)|\n|\r" # \r\n (Windows), \n (UNIX), or \r (Mac)
204n/a eol_re = re.compile(eol)
205n/a eol_convention = os.linesep # default
206n/a
207n/a def loadfile(self, filename):
208n/a try:
209n/a # open the file in binary mode so that we can handle
210n/a # end-of-line convention ourselves.
211n/a with open(filename, 'rb') as f:
212n/a two_lines = f.readline() + f.readline()
213n/a f.seek(0)
214n/a bytes = f.read()
215n/a except OSError as msg:
216n/a tkMessageBox.showerror("I/O Error", str(msg), master=self.text)
217n/a return False
218n/a chars, converted = self._decode(two_lines, bytes)
219n/a if chars is None:
220n/a tkMessageBox.showerror("Decoding Error",
221n/a "File %s\nFailed to Decode" % filename,
222n/a parent=self.text)
223n/a return False
224n/a # We now convert all end-of-lines to '\n's
225n/a firsteol = self.eol_re.search(chars)
226n/a if firsteol:
227n/a self.eol_convention = firsteol.group(0)
228n/a chars = self.eol_re.sub(r"\n", chars)
229n/a self.text.delete("1.0", "end")
230n/a self.set_filename(None)
231n/a self.text.insert("1.0", chars)
232n/a self.reset_undo()
233n/a self.set_filename(filename)
234n/a if converted:
235n/a # We need to save the conversion results first
236n/a # before being able to execute the code
237n/a self.set_saved(False)
238n/a self.text.mark_set("insert", "1.0")
239n/a self.text.yview("insert")
240n/a self.updaterecentfileslist(filename)
241n/a return True
242n/a
243n/a def _decode(self, two_lines, bytes):
244n/a "Create a Unicode string."
245n/a chars = None
246n/a # Check presence of a UTF-8 signature first
247n/a if bytes.startswith(BOM_UTF8):
248n/a try:
249n/a chars = bytes[3:].decode("utf-8")
250n/a except UnicodeDecodeError:
251n/a # has UTF-8 signature, but fails to decode...
252n/a return None, False
253n/a else:
254n/a # Indicates that this file originally had a BOM
255n/a self.fileencoding = 'BOM'
256n/a return chars, False
257n/a # Next look for coding specification
258n/a try:
259n/a enc = coding_spec(two_lines)
260n/a except LookupError as name:
261n/a tkMessageBox.showerror(
262n/a title="Error loading the file",
263n/a message="The encoding '%s' is not known to this Python "\
264n/a "installation. The file may not display correctly" % name,
265n/a master = self.text)
266n/a enc = None
267n/a except UnicodeDecodeError:
268n/a return None, False
269n/a if enc:
270n/a try:
271n/a chars = str(bytes, enc)
272n/a self.fileencoding = enc
273n/a return chars, False
274n/a except UnicodeDecodeError:
275n/a pass
276n/a # Try ascii:
277n/a try:
278n/a chars = str(bytes, 'ascii')
279n/a self.fileencoding = None
280n/a return chars, False
281n/a except UnicodeDecodeError:
282n/a pass
283n/a # Try utf-8:
284n/a try:
285n/a chars = str(bytes, 'utf-8')
286n/a self.fileencoding = 'utf-8'
287n/a return chars, False
288n/a except UnicodeDecodeError:
289n/a pass
290n/a # Finally, try the locale's encoding. This is deprecated;
291n/a # the user should declare a non-ASCII encoding
292n/a try:
293n/a # Wait for the editor window to appear
294n/a self.editwin.text.update()
295n/a enc = askstring(
296n/a "Specify file encoding",
297n/a "The file's encoding is invalid for Python 3.x.\n"
298n/a "IDLE will convert it to UTF-8.\n"
299n/a "What is the current encoding of the file?",
300n/a initialvalue = locale_encoding,
301n/a parent = self.editwin.text)
302n/a
303n/a if enc:
304n/a chars = str(bytes, enc)
305n/a self.fileencoding = None
306n/a return chars, True
307n/a except (UnicodeDecodeError, LookupError):
308n/a pass
309n/a return None, False # None on failure
310n/a
311n/a def maybesave(self):
312n/a if self.get_saved():
313n/a return "yes"
314n/a message = "Do you want to save %s before closing?" % (
315n/a self.filename or "this untitled document")
316n/a confirm = tkMessageBox.askyesnocancel(
317n/a title="Save On Close",
318n/a message=message,
319n/a default=tkMessageBox.YES,
320n/a master=self.text)
321n/a if confirm:
322n/a reply = "yes"
323n/a self.save(None)
324n/a if not self.get_saved():
325n/a reply = "cancel"
326n/a elif confirm is None:
327n/a reply = "cancel"
328n/a else:
329n/a reply = "no"
330n/a self.text.focus_set()
331n/a return reply
332n/a
333n/a def save(self, event):
334n/a if not self.filename:
335n/a self.save_as(event)
336n/a else:
337n/a if self.writefile(self.filename):
338n/a self.set_saved(True)
339n/a try:
340n/a self.editwin.store_file_breaks()
341n/a except AttributeError: # may be a PyShell
342n/a pass
343n/a self.text.focus_set()
344n/a return "break"
345n/a
346n/a def save_as(self, event):
347n/a filename = self.asksavefile()
348n/a if filename:
349n/a if self.writefile(filename):
350n/a self.set_filename(filename)
351n/a self.set_saved(1)
352n/a try:
353n/a self.editwin.store_file_breaks()
354n/a except AttributeError:
355n/a pass
356n/a self.text.focus_set()
357n/a self.updaterecentfileslist(filename)
358n/a return "break"
359n/a
360n/a def save_a_copy(self, event):
361n/a filename = self.asksavefile()
362n/a if filename:
363n/a self.writefile(filename)
364n/a self.text.focus_set()
365n/a self.updaterecentfileslist(filename)
366n/a return "break"
367n/a
368n/a def writefile(self, filename):
369n/a self.fixlastline()
370n/a text = self.text.get("1.0", "end-1c")
371n/a if self.eol_convention != "\n":
372n/a text = text.replace("\n", self.eol_convention)
373n/a chars = self.encode(text)
374n/a try:
375n/a with open(filename, "wb") as f:
376n/a f.write(chars)
377n/a return True
378n/a except OSError as msg:
379n/a tkMessageBox.showerror("I/O Error", str(msg),
380n/a master=self.text)
381n/a return False
382n/a
383n/a def encode(self, chars):
384n/a if isinstance(chars, bytes):
385n/a # This is either plain ASCII, or Tk was returning mixed-encoding
386n/a # text to us. Don't try to guess further.
387n/a return chars
388n/a # Preserve a BOM that might have been present on opening
389n/a if self.fileencoding == 'BOM':
390n/a return BOM_UTF8 + chars.encode("utf-8")
391n/a # See whether there is anything non-ASCII in it.
392n/a # If not, no need to figure out the encoding.
393n/a try:
394n/a return chars.encode('ascii')
395n/a except UnicodeError:
396n/a pass
397n/a # Check if there is an encoding declared
398n/a try:
399n/a # a string, let coding_spec slice it to the first two lines
400n/a enc = coding_spec(chars)
401n/a failed = None
402n/a except LookupError as msg:
403n/a failed = msg
404n/a enc = None
405n/a else:
406n/a if not enc:
407n/a # PEP 3120: default source encoding is UTF-8
408n/a enc = 'utf-8'
409n/a if enc:
410n/a try:
411n/a return chars.encode(enc)
412n/a except UnicodeError:
413n/a failed = "Invalid encoding '%s'" % enc
414n/a tkMessageBox.showerror(
415n/a "I/O Error",
416n/a "%s.\nSaving as UTF-8" % failed,
417n/a master = self.text)
418n/a # Fallback: save as UTF-8, with BOM - ignoring the incorrect
419n/a # declared encoding
420n/a return BOM_UTF8 + chars.encode("utf-8")
421n/a
422n/a def fixlastline(self):
423n/a c = self.text.get("end-2c")
424n/a if c != '\n':
425n/a self.text.insert("end-1c", "\n")
426n/a
427n/a def print_window(self, event):
428n/a confirm = tkMessageBox.askokcancel(
429n/a title="Print",
430n/a message="Print to Default Printer",
431n/a default=tkMessageBox.OK,
432n/a master=self.text)
433n/a if not confirm:
434n/a self.text.focus_set()
435n/a return "break"
436n/a tempfilename = None
437n/a saved = self.get_saved()
438n/a if saved:
439n/a filename = self.filename
440n/a # shell undo is reset after every prompt, looks saved, probably isn't
441n/a if not saved or filename is None:
442n/a (tfd, tempfilename) = tempfile.mkstemp(prefix='IDLE_tmp_')
443n/a filename = tempfilename
444n/a os.close(tfd)
445n/a if not self.writefile(tempfilename):
446n/a os.unlink(tempfilename)
447n/a return "break"
448n/a platform = os.name
449n/a printPlatform = True
450n/a if platform == 'posix': #posix platform
451n/a command = idleConf.GetOption('main','General',
452n/a 'print-command-posix')
453n/a command = command + " 2>&1"
454n/a elif platform == 'nt': #win32 platform
455n/a command = idleConf.GetOption('main','General','print-command-win')
456n/a else: #no printing for this platform
457n/a printPlatform = False
458n/a if printPlatform: #we can try to print for this platform
459n/a command = command % shlex.quote(filename)
460n/a pipe = os.popen(command, "r")
461n/a # things can get ugly on NT if there is no printer available.
462n/a output = pipe.read().strip()
463n/a status = pipe.close()
464n/a if status:
465n/a output = "Printing failed (exit status 0x%x)\n" % \
466n/a status + output
467n/a if output:
468n/a output = "Printing command: %s\n" % repr(command) + output
469n/a tkMessageBox.showerror("Print status", output, master=self.text)
470n/a else: #no printing for this platform
471n/a message = "Printing is not enabled for this platform: %s" % platform
472n/a tkMessageBox.showinfo("Print status", message, master=self.text)
473n/a if tempfilename:
474n/a os.unlink(tempfilename)
475n/a return "break"
476n/a
477n/a opendialog = None
478n/a savedialog = None
479n/a
480n/a filetypes = [
481n/a ("Python files", "*.py *.pyw", "TEXT"),
482n/a ("Text files", "*.txt", "TEXT"),
483n/a ("All files", "*"),
484n/a ]
485n/a
486n/a defaultextension = '.py' if sys.platform == 'darwin' else ''
487n/a
488n/a def askopenfile(self):
489n/a dir, base = self.defaultfilename("open")
490n/a if not self.opendialog:
491n/a self.opendialog = tkFileDialog.Open(master=self.text,
492n/a filetypes=self.filetypes)
493n/a filename = self.opendialog.show(initialdir=dir, initialfile=base)
494n/a return filename
495n/a
496n/a def defaultfilename(self, mode="open"):
497n/a if self.filename:
498n/a return os.path.split(self.filename)
499n/a elif self.dirname:
500n/a return self.dirname, ""
501n/a else:
502n/a try:
503n/a pwd = os.getcwd()
504n/a except OSError:
505n/a pwd = ""
506n/a return pwd, ""
507n/a
508n/a def asksavefile(self):
509n/a dir, base = self.defaultfilename("save")
510n/a if not self.savedialog:
511n/a self.savedialog = tkFileDialog.SaveAs(
512n/a master=self.text,
513n/a filetypes=self.filetypes,
514n/a defaultextension=self.defaultextension)
515n/a filename = self.savedialog.show(initialdir=dir, initialfile=base)
516n/a return filename
517n/a
518n/a def updaterecentfileslist(self,filename):
519n/a "Update recent file list on all editor windows"
520n/a if self.editwin.flist:
521n/a self.editwin.update_recent_files_list(filename)
522n/a
523n/adef test():
524n/a root = Tk()
525n/a class MyEditWin:
526n/a def __init__(self, text):
527n/a self.text = text
528n/a self.flist = None
529n/a self.text.bind("<Control-o>", self.open)
530n/a self.text.bind("<Control-s>", self.save)
531n/a self.text.bind("<Alt-s>", self.save_as)
532n/a self.text.bind("<Alt-z>", self.save_a_copy)
533n/a def get_saved(self): return 0
534n/a def set_saved(self, flag): pass
535n/a def reset_undo(self): pass
536n/a def open(self, event):
537n/a self.text.event_generate("<<open-window-from-file>>")
538n/a def save(self, event):
539n/a self.text.event_generate("<<save-window>>")
540n/a def save_as(self, event):
541n/a self.text.event_generate("<<save-window-as-file>>")
542n/a def save_a_copy(self, event):
543n/a self.text.event_generate("<<save-copy-of-window-as-file>>")
544n/a text = Text(root)
545n/a text.pack()
546n/a text.focus_set()
547n/a editwin = MyEditWin(text)
548n/a io = IOBinding(editwin)
549n/a root.mainloop()
550n/a
551n/aif __name__ == "__main__":
552n/a test()