iomenu.py 20 KB

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