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

Python code coverage for Lib/idlelib/iomenu.py

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