m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

594 lines
21 KiB

7 months ago
  1. # -*- coding: utf-8 -*-
  2. #*****************************************************************************
  3. # Copyright (C) 2003-2006 Gary Bishop.
  4. # Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
  5. #
  6. # Distributed under the terms of the BSD License. The full license is in
  7. # the file COPYING, distributed as part of this software.
  8. #*****************************************************************************
  9. from __future__ import print_function, unicode_literals, absolute_import
  10. ''' an attempt to implement readline for Python in Python using ctypes'''
  11. import sys,os,re,time
  12. from glob import glob
  13. from . import release
  14. from .py3k_compat import callable, execfile
  15. import pyreadline.lineeditor.lineobj as lineobj
  16. import pyreadline.lineeditor.history as history
  17. import pyreadline.clipboard as clipboard
  18. import pyreadline.console as console
  19. import pyreadline.logger as logger
  20. from pyreadline.keysyms.common import make_KeyPress_from_keydescr
  21. from pyreadline.unicode_helper import ensure_unicode, ensure_str
  22. from .logger import log
  23. from .modes import editingmodes
  24. from .error import ReadlineError, GetSetError
  25. in_ironpython = "IronPython" in sys.version
  26. if in_ironpython:#ironpython does not provide a prompt string to readline
  27. import System
  28. default_prompt = ">>> "
  29. else:
  30. default_prompt = ""
  31. class MockConsoleError(Exception):
  32. pass
  33. class MockConsole(object):
  34. """object used during refactoring. Should raise errors when someone tries to use it.
  35. """
  36. def __setattr__(self, x):
  37. raise MockConsoleError("Should not try to get attributes from MockConsole")
  38. def cursor(self, size=50):
  39. pass
  40. class BaseReadline(object):
  41. def __init__(self):
  42. self.allow_ctrl_c = False
  43. self.ctrl_c_tap_time_interval = 0.3
  44. self.debug = False
  45. self.bell_style = 'none'
  46. self.mark = -1
  47. self.console=MockConsole()
  48. self.disable_readline = False
  49. # this code needs to follow l_buffer and history creation
  50. self.editingmodes = [mode(self) for mode in editingmodes]
  51. for mode in self.editingmodes:
  52. mode.init_editing_mode(None)
  53. self.mode = self.editingmodes[0]
  54. self.read_inputrc()
  55. log("\n".join(self.mode.rl_settings_to_string()))
  56. self.callback = None
  57. def parse_and_bind(self, string):
  58. '''Parse and execute single line of a readline init file.'''
  59. try:
  60. log('parse_and_bind("%s")' % string)
  61. if string.startswith('#'):
  62. return
  63. if string.startswith('set'):
  64. m = re.compile(r'set\s+([-a-zA-Z0-9]+)\s+(.+)\s*$').match(string)
  65. if m:
  66. var_name = m.group(1)
  67. val = m.group(2)
  68. try:
  69. setattr(self.mode, var_name.replace('-','_'), val)
  70. except AttributeError:
  71. log('unknown var="%s" val="%s"' % (var_name, val))
  72. else:
  73. log('bad set "%s"' % string)
  74. return
  75. m = re.compile(r'\s*(.+)\s*:\s*([-a-zA-Z]+)\s*$').match(string)
  76. if m:
  77. key = m.group(1)
  78. func_name = m.group(2)
  79. py_name = func_name.replace('-', '_')
  80. try:
  81. func = getattr(self.mode, py_name)
  82. except AttributeError:
  83. log('unknown func key="%s" func="%s"' % (key, func_name))
  84. if self.debug:
  85. print('pyreadline parse_and_bind error, unknown function to bind: "%s"' % func_name)
  86. return
  87. self.mode._bind_key(key, func)
  88. except:
  89. log('error')
  90. raise
  91. def _set_prompt(self, prompt):
  92. self.mode.prompt = prompt
  93. def _get_prompt(self):
  94. return self.mode.prompt
  95. prompt = property(_get_prompt, _set_prompt)
  96. def get_line_buffer(self):
  97. '''Return the current contents of the line buffer.'''
  98. return self.mode.l_buffer.get_line_text()
  99. def insert_text(self, string):
  100. '''Insert text into the command line.'''
  101. self.mode.insert_text(string)
  102. def read_init_file(self, filename=None):
  103. '''Parse a readline initialization file. The default filename is the last filename used.'''
  104. log('read_init_file("%s")' % filename)
  105. #History file book keeping methods (non-bindable)
  106. def add_history(self, line):
  107. '''Append a line to the history buffer, as if it was the last line typed.'''
  108. self.mode._history.add_history(line)
  109. def get_current_history_length(self ):
  110. '''Return the number of lines currently in the history.
  111. (This is different from get_history_length(), which returns
  112. the maximum number of lines that will be written to a history file.)'''
  113. return self.mode._history.get_current_history_length()
  114. def get_history_length(self ):
  115. '''Return the desired length of the history file.
  116. Negative values imply unlimited history file size.'''
  117. return self.mode._history.get_history_length()
  118. def set_history_length(self, length):
  119. '''Set the number of lines to save in the history file.
  120. write_history_file() uses this value to truncate the history file
  121. when saving. Negative values imply unlimited history file size.
  122. '''
  123. self.mode._history.set_history_length(length)
  124. def get_history_item(self, index):
  125. '''Return the current contents of history item at index.'''
  126. return self.mode._history.get_history_item(index)
  127. def clear_history(self):
  128. '''Clear readline history'''
  129. self.mode._history.clear_history()
  130. def read_history_file(self, filename=None):
  131. '''Load a readline history file. The default filename is ~/.history.'''
  132. if filename is None:
  133. filename = self.mode._history.history_filename
  134. log("read_history_file from %s"%ensure_unicode(filename))
  135. self.mode._history.read_history_file(filename)
  136. def write_history_file(self, filename=None):
  137. '''Save a readline history file. The default filename is ~/.history.'''
  138. self.mode._history.write_history_file(filename)
  139. #Completer functions
  140. def set_completer(self, function=None):
  141. '''Set or remove the completer function.
  142. If function is specified, it will be used as the new completer
  143. function; if omitted or None, any completer function already
  144. installed is removed. The completer function is called as
  145. function(text, state), for state in 0, 1, 2, ..., until it returns a
  146. non-string value. It should return the next possible completion
  147. starting with text.
  148. '''
  149. log('set_completer')
  150. self.mode.completer = function
  151. def get_completer(self):
  152. '''Get the completer function.
  153. '''
  154. log('get_completer')
  155. return self.mode.completer
  156. def get_begidx(self):
  157. '''Get the beginning index of the readline tab-completion scope.'''
  158. return self.mode.begidx
  159. def get_endidx(self):
  160. '''Get the ending index of the readline tab-completion scope.'''
  161. return self.mode.endidx
  162. def set_completer_delims(self, string):
  163. '''Set the readline word delimiters for tab-completion.'''
  164. self.mode.completer_delims = string
  165. def get_completer_delims(self):
  166. '''Get the readline word delimiters for tab-completion.'''
  167. if sys.version_info[0] < 3:
  168. return self.mode.completer_delims.encode("ascii")
  169. else:
  170. return self.mode.completer_delims
  171. def set_startup_hook(self, function=None):
  172. '''Set or remove the startup_hook function.
  173. If function is specified, it will be used as the new startup_hook
  174. function; if omitted or None, any hook function already installed is
  175. removed. The startup_hook function is called with no arguments just
  176. before readline prints the first prompt.
  177. '''
  178. self.mode.startup_hook = function
  179. def set_pre_input_hook(self, function=None):
  180. '''Set or remove the pre_input_hook function.
  181. If function is specified, it will be used as the new pre_input_hook
  182. function; if omitted or None, any hook function already installed is
  183. removed. The pre_input_hook function is called with no arguments
  184. after the first prompt has been printed and just before readline
  185. starts reading input characters.
  186. '''
  187. self.mode.pre_input_hook = function
  188. #Functions that are not relevant for all Readlines but should at least have a NOP
  189. def _bell(self):
  190. pass
  191. #
  192. # Standard call, not available for all implementations
  193. #
  194. def readline(self, prompt=''):
  195. raise NotImplementedError
  196. #
  197. # Callback interface
  198. #
  199. def process_keyevent(self, keyinfo):
  200. return self.mode.process_keyevent(keyinfo)
  201. def readline_setup(self, prompt=""):
  202. return self.mode.readline_setup(prompt)
  203. def keyboard_poll(self):
  204. return self.mode._readline_from_keyboard_poll()
  205. def callback_handler_install(self, prompt, callback):
  206. '''bool readline_callback_handler_install ( string prompt, callback callback)
  207. Initializes the readline callback interface and terminal, prints the prompt and returns immediately
  208. '''
  209. self.callback = callback
  210. self.readline_setup(prompt)
  211. def callback_handler_remove(self):
  212. '''Removes a previously installed callback handler and restores terminal settings'''
  213. self.callback = None
  214. def callback_read_char(self):
  215. '''Reads a character and informs the readline callback interface when a line is received'''
  216. if self.keyboard_poll():
  217. line = self.get_line_buffer() + '\n'
  218. # however there is another newline added by
  219. # self.mode.readline_setup(prompt) which is called by callback_handler_install
  220. # this differs from GNU readline
  221. self.add_history(self.mode.l_buffer)
  222. # TADA:
  223. self.callback(line)
  224. def read_inputrc(self, #in 2.4 we cannot call expanduser with unicode string
  225. inputrcpath=os.path.expanduser(ensure_str("~/pyreadlineconfig.ini"))):
  226. modes = dict([(x.mode,x) for x in self.editingmodes])
  227. mode = self.editingmodes[0].mode
  228. def setmode(name):
  229. self.mode = modes[name]
  230. def bind_key(key, name):
  231. import types
  232. if callable(name):
  233. modes[mode]._bind_key(key, types.MethodType(name, modes[mode]))
  234. elif hasattr(modes[mode], name):
  235. modes[mode]._bind_key(key, getattr(modes[mode], name))
  236. else:
  237. print("Trying to bind unknown command '%s' to key '%s'"%(name, key))
  238. def un_bind_key(key):
  239. keyinfo = make_KeyPress_from_keydescr(key).tuple()
  240. if keyinfo in modes[mode].key_dispatch:
  241. del modes[mode].key_dispatch[keyinfo]
  242. def bind_exit_key(key):
  243. modes[mode]._bind_exit_key(key)
  244. def un_bind_exit_key(key):
  245. keyinfo = make_KeyPress_from_keydescr(key).tuple()
  246. if keyinfo in modes[mode].exit_dispatch:
  247. del modes[mode].exit_dispatch[keyinfo]
  248. def setkill_ring_to_clipboard(killring):
  249. import pyreadline.lineeditor.lineobj
  250. pyreadline.lineeditor.lineobj.kill_ring_to_clipboard = killring
  251. def sethistoryfilename(filename):
  252. self.mode._history.history_filename = os.path.expanduser(ensure_str(filename))
  253. def setbellstyle(mode):
  254. self.bell_style = mode
  255. def disable_readline(mode):
  256. self.disable_readline = mode
  257. def sethistorylength(length):
  258. self.mode._history.history_length = int(length)
  259. def allow_ctrl_c(mode):
  260. log("allow_ctrl_c:%s:%s"%(self.allow_ctrl_c, mode))
  261. self.allow_ctrl_c = mode
  262. def setbellstyle(mode):
  263. self.bell_style = mode
  264. def show_all_if_ambiguous(mode):
  265. self.mode.show_all_if_ambiguous = mode
  266. def ctrl_c_tap_time_interval(mode):
  267. self.ctrl_c_tap_time_interval = mode
  268. def mark_directories(mode):
  269. self.mode.mark_directories = mode
  270. def completer_delims(delims):
  271. self.mode.completer_delims = delims
  272. def complete_filesystem(delims):
  273. self.mode.complete_filesystem = delims.lower()
  274. def enable_ipython_paste_for_paths(boolean):
  275. self.mode.enable_ipython_paste_for_paths = boolean
  276. def debug_output(on, filename="pyreadline_debug_log.txt"): #Not implemented yet
  277. if on in ["on", "on_nologfile"]:
  278. self.debug=True
  279. if on == "on":
  280. logger.start_file_log(filename)
  281. logger.start_socket_log()
  282. logger.log("STARTING LOG")
  283. elif on == "on_nologfile":
  284. logger.start_socket_log()
  285. logger.log("STARTING LOG")
  286. else:
  287. logger.log("STOPING LOG")
  288. logger.stop_file_log()
  289. logger.stop_socket_log()
  290. _color_trtable={"black":0, "darkred":4, "darkgreen":2,
  291. "darkyellow":6, "darkblue":1, "darkmagenta":5,
  292. "darkcyan":3, "gray":7, "red":4+8,
  293. "green":2+8, "yellow":6+8, "blue":1+8,
  294. "magenta":5+8, "cyan":3+8, "white":7+8}
  295. def set_prompt_color(color):
  296. self.prompt_color = self._color_trtable.get(color.lower(),7)
  297. def set_input_color(color):
  298. self.command_color=self._color_trtable.get(color.lower(),7)
  299. loc = {"branch":release.branch,
  300. "version":release.version,
  301. "mode":mode,
  302. "modes":modes,
  303. "set_mode":setmode,
  304. "bind_key":bind_key,
  305. "disable_readline":disable_readline,
  306. "bind_exit_key":bind_exit_key,
  307. "un_bind_key":un_bind_key,
  308. "un_bind_exit_key":un_bind_exit_key,
  309. "bell_style":setbellstyle,
  310. "mark_directories":mark_directories,
  311. "show_all_if_ambiguous":show_all_if_ambiguous,
  312. "completer_delims":completer_delims,
  313. "complete_filesystem":complete_filesystem,
  314. "debug_output":debug_output,
  315. "history_filename":sethistoryfilename,
  316. "history_length":sethistorylength,
  317. "set_prompt_color":set_prompt_color,
  318. "set_input_color":set_input_color,
  319. "allow_ctrl_c":allow_ctrl_c,
  320. "ctrl_c_tap_time_interval":ctrl_c_tap_time_interval,
  321. "kill_ring_to_clipboard":setkill_ring_to_clipboard,
  322. "enable_ipython_paste_for_paths":enable_ipython_paste_for_paths,
  323. }
  324. if os.path.isfile(inputrcpath):
  325. try:
  326. execfile(inputrcpath, loc, loc)
  327. except Exception as x:
  328. raise
  329. import traceback
  330. print("Error reading .pyinputrc", file=sys.stderr)
  331. filepath, lineno = traceback.extract_tb(sys.exc_traceback)[1][:2]
  332. print("Line: %s in file %s"%(lineno, filepath), file=sys.stderr)
  333. print(x, file=sys.stderr)
  334. raise ReadlineError("Error reading .pyinputrc")
  335. class Readline(BaseReadline):
  336. """Baseclass for readline based on a console
  337. """
  338. def __init__(self):
  339. BaseReadline.__init__(self)
  340. self.console = console.Console()
  341. self.selection_color = self.console.saveattr<<4
  342. self.command_color = None
  343. self.prompt_color = None
  344. self.size = self.console.size()
  345. # variables you can control with parse_and_bind
  346. # To export as readline interface
  347. ## Internal functions
  348. def _bell(self):
  349. '''ring the bell if requested.'''
  350. if self.bell_style == 'none':
  351. pass
  352. elif self.bell_style == 'visible':
  353. raise NotImplementedError("Bellstyle visible is not implemented yet.")
  354. elif self.bell_style == 'audible':
  355. self.console.bell()
  356. else:
  357. raise ReadlineError("Bellstyle %s unknown."%self.bell_style)
  358. def _clear_after(self):
  359. c = self.console
  360. x, y = c.pos()
  361. w, h = c.size()
  362. c.rectangle((x, y, w+1, y+1))
  363. c.rectangle((0, y+1, w, min(y+3,h)))
  364. def _set_cursor(self):
  365. c = self.console
  366. xc, yc = self.prompt_end_pos
  367. w, h = c.size()
  368. xc += self.mode.l_buffer.visible_line_width()
  369. while(xc >= w):
  370. xc -= w
  371. yc += 1
  372. c.pos(xc, yc)
  373. def _print_prompt(self):
  374. c = self.console
  375. x, y = c.pos()
  376. n = c.write_scrolling(self.prompt, self.prompt_color)
  377. self.prompt_begin_pos = (x, y - n)
  378. self.prompt_end_pos = c.pos()
  379. self.size = c.size()
  380. def _update_prompt_pos(self, n):
  381. if n != 0:
  382. bx, by = self.prompt_begin_pos
  383. ex, ey = self.prompt_end_pos
  384. self.prompt_begin_pos = (bx, by - n)
  385. self.prompt_end_pos = (ex, ey - n)
  386. def _update_line(self):
  387. c = self.console
  388. l_buffer = self.mode.l_buffer
  389. c.cursor(0) #Hide cursor avoiding flicking
  390. c.pos(*self.prompt_begin_pos)
  391. self._print_prompt()
  392. ltext = l_buffer.quoted_text()
  393. if l_buffer.enable_selection and (l_buffer.selection_mark >= 0):
  394. start = len(l_buffer[:l_buffer.selection_mark].quoted_text())
  395. stop = len(l_buffer[:l_buffer.point].quoted_text())
  396. if start > stop:
  397. stop,start = start,stop
  398. n = c.write_scrolling(ltext[:start], self.command_color)
  399. n = c.write_scrolling(ltext[start:stop], self.selection_color)
  400. n = c.write_scrolling(ltext[stop:], self.command_color)
  401. else:
  402. n = c.write_scrolling(ltext, self.command_color)
  403. x, y = c.pos() #Preserve one line for Asian IME(Input Method Editor) statusbar
  404. w, h = c.size()
  405. if (y >= h - 1) or (n > 0):
  406. c.scroll_window(-1)
  407. c.scroll((0, 0, w, h), 0, -1)
  408. n += 1
  409. self._update_prompt_pos(n)
  410. if hasattr(c, "clear_to_end_of_window"): #Work around function for ironpython due
  411. c.clear_to_end_of_window() #to System.Console's lack of FillFunction
  412. else:
  413. self._clear_after()
  414. #Show cursor, set size vi mode changes size in insert/overwrite mode
  415. c.cursor(1, size=self.mode.cursor_size)
  416. self._set_cursor()
  417. def callback_read_char(self):
  418. #Override base to get automatic newline
  419. '''Reads a character and informs the readline callback interface when a line is received'''
  420. if self.keyboard_poll():
  421. line = self.get_line_buffer() + '\n'
  422. self.console.write("\r\n")
  423. # however there is another newline added by
  424. # self.mode.readline_setup(prompt) which is called by callback_handler_install
  425. # this differs from GNU readline
  426. self.add_history(self.mode.l_buffer)
  427. # TADA:
  428. self.callback(line)
  429. def event_available(self):
  430. return self.console.peek() or (len(self.paste_line_buffer) > 0)
  431. def _readline_from_keyboard(self):
  432. while 1:
  433. if self._readline_from_keyboard_poll():
  434. break
  435. def _readline_from_keyboard_poll(self):
  436. pastebuffer = self.mode.paste_line_buffer
  437. if len(pastebuffer) > 0:
  438. #paste first line in multiline paste buffer
  439. self.l_buffer = lineobj.ReadLineTextBuffer(pastebuffer[0])
  440. self._update_line()
  441. self.mode.paste_line_buffer = pastebuffer[1:]
  442. return True
  443. c = self.console
  444. def nop(e):
  445. pass
  446. try:
  447. event = c.getkeypress()
  448. except KeyboardInterrupt:
  449. event = self.handle_ctrl_c()
  450. try:
  451. result = self.mode.process_keyevent(event.keyinfo)
  452. except EOFError:
  453. logger.stop_logging()
  454. raise
  455. self._update_line()
  456. return result
  457. def readline_setup(self, prompt=''):
  458. BaseReadline.readline_setup(self, prompt)
  459. self._print_prompt()
  460. self._update_line()
  461. def readline(self, prompt=''):
  462. self.readline_setup(prompt)
  463. self.ctrl_c_timeout = time.time()
  464. self._readline_from_keyboard()
  465. self.console.write('\r\n')
  466. log('returning(%s)' % self.get_line_buffer())
  467. return self.get_line_buffer() + '\n'
  468. def handle_ctrl_c(self):
  469. from pyreadline.keysyms.common import KeyPress
  470. from pyreadline.console.event import Event
  471. log("KBDIRQ")
  472. event = Event(0,0)
  473. event.char = "c"
  474. event.keyinfo = KeyPress("c", shift=False, control=True,
  475. meta=False, keyname=None)
  476. if self.allow_ctrl_c:
  477. now = time.time()
  478. if (now - self.ctrl_c_timeout) < self.ctrl_c_tap_time_interval:
  479. log("Raise KeyboardInterrupt")
  480. raise KeyboardInterrupt
  481. else:
  482. self.ctrl_c_timeout = now
  483. else:
  484. raise KeyboardInterrupt
  485. return event