Debian Codegraph @

Lib/idlelib/iomenu.py

raw
1 import io
2 import os
3 import shlex
4 import sys
5 import tempfile
6 import tokenize
7
8 from tkinter import filedialog
9 from tkinter import messagebox
10 from tkinter.simpledialog import askstring # loadfile encoding.
11
12 from idlelib.config import idleConf
13 from idlelib.util import py_extensions
14
15 py_extensions = ' '.join("*"+ext for ext in py_extensions)
16 encoding = 'utf-8'
17 errors = 'surrogatepass' if sys.platform == 'win32' else 'surrogateescape'
18
19
20 class IOBinding:
21 # One instance per editor Window so methods know which to save, close.
22 # Open returns focus to self.editwin if aborted.
23 # EditorWindow.open_module, others, belong here.
24
25 def __init__(self, editwin):
26 self.editwin = editwin
27 self.text = editwin.text
28 self.__id_open = self.text.bind("<<open-window-from-file>>", self.open)
29 self.__id_save = self.text.bind("<<save-window>>", self.save)
30 self.__id_saveas = self.text.bind("<<save-window-as-file>>",
31 self.save_as)
32 self.__id_savecopy = self.text.bind("<<save-copy-of-window-as-file>>",
33 self.save_a_copy)
34 self.fileencoding = 'utf-8'
35 self.__id_print = self.text.bind("<<print-window>>", self.print_window)
36
37 def close(self):
38 # Undo command bindings
39 self.text.unbind("<<open-window-from-file>>", self.__id_open)
40 self.text.unbind("<<save-window>>", self.__id_save)
41 self.text.unbind("<<save-window-as-file>>",self.__id_saveas)
42 self.text.unbind("<<save-copy-of-window-as-file>>", self.__id_savecopy)
43 self.text.unbind("<<print-window>>", self.__id_print)
44 # Break cycles
45 self.editwin = None
46 self.text = None
47 self.filename_change_hook = None
48
49 def get_saved(self):
50 return self.editwin.get_saved()
51
52 def set_saved(self, flag):
53 self.editwin.set_saved(flag)
54
55 def reset_undo(self):
56 self.editwin.reset_undo()
57
58 filename_change_hook = None
59
60 def set_filename_change_hook(self, hook):
61 self.filename_change_hook = hook
62
63 filename = None
64 file_timestamp = None
65 dirname = None
66
67 def set_filename(self, filename):
68 if filename and os.path.isdir(filename):
69 self.filename = None
70 self.dirname = filename
71 else:
72 self.filename = filename
73 self.dirname = None
74 self.set_saved(1)
75 if self.filename_change_hook:
76 self.filename_change_hook()
77
78 def open(self, event=None, editFile=None):
79 flist = self.editwin.flist
80 # Save in case parent window is closed (ie, during askopenfile()).
81 if flist:
82 if not editFile:
83 filename = self.askopenfile()
84 else:
85 filename=editFile
86 if filename:
87 # If editFile is valid and already open, flist.open will
88 # shift focus to its existing window.
89 # If the current window exists and is a fresh unnamed,
90 # unmodified editor window (not an interpreter shell),
91 # pass self.loadfile to flist.open so it will load the file
92 # in the current window (if the file is not already open)
93 # instead of a new window.
94 if (self.editwin and
95 not getattr(self.editwin, 'interp', None) and
96 not self.filename and
97 self.get_saved()):
98 flist.open(filename, self.loadfile)
99 else:
100 flist.open(filename)
101 else:
102 if self.text:
103 self.text.focus_set()
104 return "break"
105
106 # Code for use outside IDLE:
107 if self.get_saved():
108 reply = self.maybesave()
109 if reply == "cancel":
110 self.text.focus_set()
111 return "break"
112 if not editFile:
113 filename = self.askopenfile()
114 else:
115 filename=editFile
116 if filename:
117 self.loadfile(filename)
118 else:
119 self.text.focus_set()
120 return "break"
121
122 eol_convention = os.linesep # default
123
124 def loadfile(self, filename):
125 try:
126 try:
127 with tokenize.open(filename) as f:
128 chars = f.read()
129 fileencoding = f.encoding
130 eol_convention = f.newlines
131 file_timestamp = self.getmtime(filename)
132 converted = False
133 except (UnicodeDecodeError, SyntaxError):
134 # Wait for the editor window to appear
135 self.editwin.text.update()
136 enc = askstring(
137 "Specify file encoding",
138 "The file's encoding is invalid for Python 3.x.\n"
139 "IDLE will convert it to UTF-8.\n"
140 "What is the current encoding of the file?",
141 initialvalue='utf-8',
142 parent=self.editwin.text)
143 with open(filename, encoding=enc) as f:
144 chars = f.read()
145 fileencoding = f.encoding
146 eol_convention = f.newlines
147 file_timestamp = self.getmtime(filename)
148 converted = True
149 except OSError as err:
150 messagebox.showerror("I/O Error", str(err), parent=self.text)
151 return False
152 except UnicodeDecodeError:
153 messagebox.showerror("Decoding Error",
154 "File %s\nFailed to Decode" % filename,
155 parent=self.text)
156 return False
157
158 if not isinstance(eol_convention, str):
159 # If the file does not contain line separators, it is None.
160 # If the file contains mixed line separators, it is a tuple.
161 if eol_convention is not None:
162 messagebox.showwarning("Mixed Newlines",
163 "Mixed newlines detected.\n"
164 "The file will be changed on save.",
165 parent=self.text)
166 converted = True
167 eol_convention = os.linesep # default
168
169 self.text.delete("1.0", "end")
170 self.set_filename(None)
171 self.fileencoding = fileencoding
172 self.eol_convention = eol_convention
173 self.text.insert("1.0", chars)
174 self.reset_undo()
175 self.set_filename(filename)
176 self.file_timestamp = file_timestamp
177 if converted:
178 # We need to save the conversion results first
179 # before being able to execute the code
180 self.set_saved(False)
181 self.text.mark_set("insert", "1.0")
182 self.text.yview("insert")
183 self.updaterecentfileslist(filename)
184 return True
185
186 def maybesave(self):
187 """Return 'yes', 'no', 'cancel' as appropriate.
188
189 Tkinter messagebox.askyesnocancel converts these tk responses
190 to True, False, None. Convert back, as now expected elsewhere.
191 """
192 if self.get_saved():
193 return "yes"
194 message = ("Do you want to save "
195 f"{self.filename or 'this untitled document'}"
196 " before closing?")
197 confirm = messagebox.askyesnocancel(
198 title="Save On Close",
199 message=message,
200 default=messagebox.YES,
201 parent=self.text)
202 if confirm:
203 self.save(None)
204 reply = "yes" if self.get_saved() else "cancel"
205 else: reply = "cancel" if confirm is None else "no"
206 self.text.focus_set()
207 return reply
208
209 def save(self, event):
210 if not self.filename:
211 self.save_as(event)
212 else:
213 # Check the time of most recent content modification so the
214 # user doesn't accidentally overwrite a newer version of the file.
215 try:
216 file_timestamp = self.getmtime(self.filename)
217 except OSError:
218 pass
219 else:
220 if self.file_timestamp != file_timestamp:
221 confirm = messagebox.askokcancel(
222 title="File has changed",
223 message=(
224 "The file has changed on disk since reading it!\n\n"
225 "Do you really want to overwrite it?"),
226 default=messagebox.CANCEL,
227 parent=self.text)
228 if not confirm:
229 return "break"
230
231 if self.writefile(self.filename):
232 self.file_timestamp = self.getmtime(self.filename)
233 self.set_saved(True)
234 try:
235 self.editwin.store_file_breaks()
236 except AttributeError: # may be a PyShell
237 pass
238 self.text.focus_set()
239 return "break"
240
241 def save_as(self, event):
242 filename = self.asksavefile()
243 if filename:
244 if self.writefile(filename):
245 self.file_timestamp = self.getmtime(filename)
246 self.set_filename(filename)
247 self.set_saved(1)
248 try:
249 self.editwin.store_file_breaks()
250 except AttributeError:
251 pass
252 self.text.focus_set()
253 self.updaterecentfileslist(filename)
254 return "break"
255
256 def save_a_copy(self, event):
257 filename = self.asksavefile()
258 if filename:
259 self.writefile(filename)
260 self.text.focus_set()
261 self.updaterecentfileslist(filename)
262 return "break"
263
264 def writefile(self, filename):
265 text = self.fixnewlines()
266 chars = self.encode(text)
267 try:
268 with open(filename, "wb") as f:
269 f.write(chars)
270 f.flush()
271 os.fsync(f.fileno())
272 return True
273 except OSError as msg:
274 messagebox.showerror("I/O Error", str(msg),
275 parent=self.text)
276 return False
277
278 def getmtime(self, filename):
279 return os.stat(filename).st_mtime
280
281 def fixnewlines(self):
282 """Return text with os eols.
283
284 Add prompts if shell else final \n if missing.
285 """
286
287 if hasattr(self.editwin, "interp"): # Saving shell.
288 text = self.editwin.get_prompt_text('1.0', self.text.index('end-1c'))
289 else:
290 if self.text.get("end-2c") != '\n':
291 self.text.insert("end-1c", "\n") # Changes 'end-1c' value.
292 text = self.text.get('1.0', "end-1c")
293 if self.eol_convention != "\n":
294 text = text.replace("\n", self.eol_convention)
295 return text
296
297 def encode(self, chars):
298 if isinstance(chars, bytes):
299 # This is either plain ASCII, or Tk was returning mixed-encoding
300 # text to us. Don't try to guess further.
301 return chars
302 # Preserve a BOM that might have been present on opening
303 if self.fileencoding == 'utf-8-sig':
304 return chars.encode('utf-8-sig')
305 # See whether there is anything non-ASCII in it.
306 # If not, no need to figure out the encoding.
307 try:
308 return chars.encode('ascii')
309 except UnicodeEncodeError:
310 pass
311 # Check if there is an encoding declared
312 try:
313 encoded = chars.encode('ascii', 'replace')
314 enc, _ = tokenize.detect_encoding(io.BytesIO(encoded).readline)
315 return chars.encode(enc)
316 except SyntaxError as err:
317 failed = str(err)
318 except UnicodeEncodeError:
319 failed = "Invalid encoding '%s'" % enc
320 messagebox.showerror(
321 "I/O Error",
322 "%s.\nSaving as UTF-8" % failed,
323 parent=self.text)
324 # Fallback: save as UTF-8, with BOM - ignoring the incorrect
325 # declared encoding
326 return chars.encode('utf-8-sig')
327
328 def print_window(self, event):
329 confirm = messagebox.askokcancel(
330 title="Print",
331 message="Print to Default Printer",
332 default=messagebox.OK,
333 parent=self.text)
334 if not confirm:
335 self.text.focus_set()
336 return "break"
337 tempfilename = None
338 saved = self.get_saved()
339 if saved:
340 filename = self.filename
341 # shell undo is reset after every prompt, looks saved, probably isn't
342 if not saved or filename is None:
343 (tfd, tempfilename) = tempfile.mkstemp(prefix='IDLE_tmp_')
344 filename = tempfilename
345 os.close(tfd)
346 if not self.writefile(tempfilename):
347 os.unlink(tempfilename)
348 return "break"
349 platform = os.name
350 printPlatform = True
351 if platform == 'posix': #posix platform
352 command = idleConf.GetOption('main','General',
353 'print-command-posix')
354 command = command + " 2>&1"
355 elif platform == 'nt': #win32 platform
356 command = idleConf.GetOption('main','General','print-command-win')
357 else: #no printing for this platform
358 printPlatform = False
359 if printPlatform: #we can try to print for this platform
360 command = command % shlex.quote(filename)
361 pipe = os.popen(command, "r")
362 # things can get ugly on NT if there is no printer available.
363 output = pipe.read().strip()
364 status = pipe.close()
365 if status:
366 output = "Printing failed (exit status 0x%x)\n" % \
367 status + output
368 if output:
369 output = "Printing command: %s\n" % repr(command) + output
370 messagebox.showerror("Print status", output, parent=self.text)
371 else: #no printing for this platform
372 message = "Printing is not enabled for this platform: %s" % platform
373 messagebox.showinfo("Print status", message, parent=self.text)
374 if tempfilename:
375 os.unlink(tempfilename)
376 return "break"
377
378 opendialog = None
379 savedialog = None
380
381 filetypes = (
382 ("Python files", py_extensions, "TEXT"),
383 ("Text files", "*.txt", "TEXT"),
384 ("All files", "*"),
385 )
386
387 defaultextension = '.py' if sys.platform == 'darwin' else ''
388
389 def askopenfile(self):
390 dir, base = self.defaultfilename("open")
391 if not self.opendialog:
392 self.opendialog = filedialog.Open(parent=self.text,
393 filetypes=self.filetypes)
394 filename = self.opendialog.show(initialdir=dir, initialfile=base)
395 return filename
396
397 def defaultfilename(self, mode="open"):
398 if self.filename:
399 return os.path.split(self.filename)
400 elif self.dirname:
401 return self.dirname, ""
402 else:
403 try:
404 pwd = os.getcwd()
405 except OSError:
406 pwd = ""
407 return pwd, ""
408
409 def asksavefile(self):
410 dir, base = self.defaultfilename("save")
411 if not self.savedialog:
412 self.savedialog = filedialog.SaveAs(
413 parent=self.text,
414 filetypes=self.filetypes,
415 defaultextension=self.defaultextension)
416 filename = self.savedialog.show(initialdir=dir, initialfile=base)
417 return filename
418
419 def updaterecentfileslist(self,filename):
420 "Update recent file list on all editor windows"
421 if self.editwin.flist:
422 self.editwin.update_recent_files_list(filename)
423
424
425 def _io_binding(parent): # htest #
426 from tkinter import Toplevel, Text
427
428 top = Toplevel(parent)
429 top.title("Test IOBinding")
430 x, y = map(int, parent.geometry().split('+')[1:])
431 top.geometry("+%d+%d" % (x, y + 175))
432
433 class MyEditWin:
434 def __init__(self, text):
435 self.text = text
436 self.flist = None
437 self.text.bind("<Control-o>", self.open)
438 self.text.bind('<Control-p>', self.print)
439 self.text.bind("<Control-s>", self.save)
440 self.text.bind("<Alt-s>", self.saveas)
441 self.text.bind('<Control-c>', self.savecopy)
442 def get_saved(self): return 0
443 def set_saved(self, flag): pass
444 def reset_undo(self): pass
445 def open(self, event):
446 self.text.event_generate("<<open-window-from-file>>")
447 def print(self, event):
448 self.text.event_generate("<<print-window>>")
449 def save(self, event):
450 self.text.event_generate("<<save-window>>")
451 def saveas(self, event):
452 self.text.event_generate("<<save-window-as-file>>")
453 def savecopy(self, event):
454 self.text.event_generate("<<save-copy-of-window-as-file>>")
455
456 text = Text(top)
457 text.pack()
458 text.focus_set()
459 editwin = MyEditWin(text)
460 IOBinding(editwin)
461
462
463 if __name__ == "__main__":
464 from unittest import main
465 main('idlelib.idle_test.test_iomenu', verbosity=2, exit=False)
466
467 from idlelib.idle_test.htest import run
468 run(_io_binding)