menus.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. from __future__ import unicode_literals
  2. from six.moves import zip_longest, range
  3. from prompt_toolkit.filters import HasCompletions, IsDone, Condition, to_cli_filter
  4. from prompt_toolkit.mouse_events import MouseEventType
  5. from prompt_toolkit.token import Token
  6. from prompt_toolkit.utils import get_cwidth
  7. from .containers import Window, HSplit, ConditionalContainer, ScrollOffsets
  8. from .controls import UIControl, UIContent
  9. from .dimension import LayoutDimension
  10. from .margins import ScrollbarMargin
  11. from .screen import Point, Char
  12. import math
  13. __all__ = (
  14. 'CompletionsMenu',
  15. 'MultiColumnCompletionsMenu',
  16. )
  17. class CompletionsMenuControl(UIControl):
  18. """
  19. Helper for drawing the complete menu to the screen.
  20. :param scroll_offset: Number (integer) representing the preferred amount of
  21. completions to be displayed before and after the current one. When this
  22. is a very high number, the current completion will be shown in the
  23. middle most of the time.
  24. """
  25. # Preferred minimum size of the menu control.
  26. # The CompletionsMenu class defines a width of 8, and there is a scrollbar
  27. # of 1.)
  28. MIN_WIDTH = 7
  29. def __init__(self):
  30. self.token = Token.Menu.Completions
  31. def has_focus(self, cli):
  32. return False
  33. def preferred_width(self, cli, max_available_width):
  34. complete_state = cli.current_buffer.complete_state
  35. if complete_state:
  36. menu_width = self._get_menu_width(500, complete_state)
  37. menu_meta_width = self._get_menu_meta_width(500, complete_state)
  38. return menu_width + menu_meta_width
  39. else:
  40. return 0
  41. def preferred_height(self, cli, width, max_available_height, wrap_lines):
  42. complete_state = cli.current_buffer.complete_state
  43. if complete_state:
  44. return len(complete_state.current_completions)
  45. else:
  46. return 0
  47. def create_content(self, cli, width, height):
  48. """
  49. Create a UIContent object for this control.
  50. """
  51. complete_state = cli.current_buffer.complete_state
  52. if complete_state:
  53. completions = complete_state.current_completions
  54. index = complete_state.complete_index # Can be None!
  55. # Calculate width of completions menu.
  56. menu_width = self._get_menu_width(width, complete_state)
  57. menu_meta_width = self._get_menu_meta_width(width - menu_width, complete_state)
  58. show_meta = self._show_meta(complete_state)
  59. def get_line(i):
  60. c = completions[i]
  61. is_current_completion = (i == index)
  62. result = self._get_menu_item_tokens(c, is_current_completion, menu_width)
  63. if show_meta:
  64. result += self._get_menu_item_meta_tokens(c, is_current_completion, menu_meta_width)
  65. return result
  66. return UIContent(get_line=get_line,
  67. cursor_position=Point(x=0, y=index or 0),
  68. line_count=len(completions),
  69. default_char=Char(' ', self.token))
  70. return UIContent()
  71. def _show_meta(self, complete_state):
  72. """
  73. Return ``True`` if we need to show a column with meta information.
  74. """
  75. return any(c.display_meta for c in complete_state.current_completions)
  76. def _get_menu_width(self, max_width, complete_state):
  77. """
  78. Return the width of the main column.
  79. """
  80. return min(max_width, max(self.MIN_WIDTH, max(get_cwidth(c.display)
  81. for c in complete_state.current_completions) + 2))
  82. def _get_menu_meta_width(self, max_width, complete_state):
  83. """
  84. Return the width of the meta column.
  85. """
  86. if self._show_meta(complete_state):
  87. return min(max_width, max(get_cwidth(c.display_meta)
  88. for c in complete_state.current_completions) + 2)
  89. else:
  90. return 0
  91. def _get_menu_item_tokens(self, completion, is_current_completion, width):
  92. if is_current_completion:
  93. token = self.token.Completion.Current
  94. else:
  95. token = self.token.Completion
  96. text, tw = _trim_text(completion.display, width - 2)
  97. padding = ' ' * (width - 2 - tw)
  98. return [(token, ' %s%s ' % (text, padding))]
  99. def _get_menu_item_meta_tokens(self, completion, is_current_completion, width):
  100. if is_current_completion:
  101. token = self.token.Meta.Current
  102. else:
  103. token = self.token.Meta
  104. text, tw = _trim_text(completion.display_meta, width - 2)
  105. padding = ' ' * (width - 2 - tw)
  106. return [(token, ' %s%s ' % (text, padding))]
  107. def mouse_handler(self, cli, mouse_event):
  108. """
  109. Handle mouse events: clicking and scrolling.
  110. """
  111. b = cli.current_buffer
  112. if mouse_event.event_type == MouseEventType.MOUSE_UP:
  113. # Select completion.
  114. b.go_to_completion(mouse_event.position.y)
  115. b.complete_state = None
  116. elif mouse_event.event_type == MouseEventType.SCROLL_DOWN:
  117. # Scroll up.
  118. b.complete_next(count=3, disable_wrap_around=True)
  119. elif mouse_event.event_type == MouseEventType.SCROLL_UP:
  120. # Scroll down.
  121. b.complete_previous(count=3, disable_wrap_around=True)
  122. def _trim_text(text, max_width):
  123. """
  124. Trim the text to `max_width`, append dots when the text is too long.
  125. Returns (text, width) tuple.
  126. """
  127. width = get_cwidth(text)
  128. # When the text is too wide, trim it.
  129. if width > max_width:
  130. # When there are no double width characters, just use slice operation.
  131. if len(text) == width:
  132. trimmed_text = (text[:max(1, max_width-3)] + '...')[:max_width]
  133. return trimmed_text, len(trimmed_text)
  134. # Otherwise, loop until we have the desired width. (Rather
  135. # inefficient, but ok for now.)
  136. else:
  137. trimmed_text = ''
  138. for c in text:
  139. if get_cwidth(trimmed_text + c) <= max_width - 3:
  140. trimmed_text += c
  141. trimmed_text += '...'
  142. return (trimmed_text, get_cwidth(trimmed_text))
  143. else:
  144. return text, width
  145. class CompletionsMenu(ConditionalContainer):
  146. def __init__(self, max_height=None, scroll_offset=0, extra_filter=True, display_arrows=False):
  147. extra_filter = to_cli_filter(extra_filter)
  148. display_arrows = to_cli_filter(display_arrows)
  149. super(CompletionsMenu, self).__init__(
  150. content=Window(
  151. content=CompletionsMenuControl(),
  152. width=LayoutDimension(min=8),
  153. height=LayoutDimension(min=1, max=max_height),
  154. scroll_offsets=ScrollOffsets(top=scroll_offset, bottom=scroll_offset),
  155. right_margins=[ScrollbarMargin(display_arrows=display_arrows)],
  156. dont_extend_width=True,
  157. ),
  158. # Show when there are completions but not at the point we are
  159. # returning the input.
  160. filter=HasCompletions() & ~IsDone() & extra_filter)
  161. class MultiColumnCompletionMenuControl(UIControl):
  162. """
  163. Completion menu that displays all the completions in several columns.
  164. When there are more completions than space for them to be displayed, an
  165. arrow is shown on the left or right side.
  166. `min_rows` indicates how many rows will be available in any possible case.
  167. When this is langer than one, in will try to use less columns and more
  168. rows until this value is reached.
  169. Be careful passing in a too big value, if less than the given amount of
  170. rows are available, more columns would have been required, but
  171. `preferred_width` doesn't know about that and reports a too small value.
  172. This results in less completions displayed and additional scrolling.
  173. (It's a limitation of how the layout engine currently works: first the
  174. widths are calculated, then the heights.)
  175. :param suggested_max_column_width: The suggested max width of a column.
  176. The column can still be bigger than this, but if there is place for two
  177. columns of this width, we will display two columns. This to avoid that
  178. if there is one very wide completion, that it doesn't significantly
  179. reduce the amount of columns.
  180. """
  181. _required_margin = 3 # One extra padding on the right + space for arrows.
  182. def __init__(self, min_rows=3, suggested_max_column_width=30):
  183. assert isinstance(min_rows, int) and min_rows >= 1
  184. self.min_rows = min_rows
  185. self.suggested_max_column_width = suggested_max_column_width
  186. self.token = Token.Menu.Completions
  187. self.scroll = 0
  188. # Info of last rendering.
  189. self._rendered_rows = 0
  190. self._rendered_columns = 0
  191. self._total_columns = 0
  192. self._render_pos_to_completion = {}
  193. self._render_left_arrow = False
  194. self._render_right_arrow = False
  195. self._render_width = 0
  196. def reset(self):
  197. self.scroll = 0
  198. def has_focus(self, cli):
  199. return False
  200. def preferred_width(self, cli, max_available_width):
  201. """
  202. Preferred width: prefer to use at least min_rows, but otherwise as much
  203. as possible horizontally.
  204. """
  205. complete_state = cli.current_buffer.complete_state
  206. column_width = self._get_column_width(complete_state)
  207. result = int(column_width * math.ceil(len(complete_state.current_completions) / float(self.min_rows)))
  208. # When the desired width is still more than the maximum available,
  209. # reduce by removing columns until we are less than the available
  210. # width.
  211. while result > column_width and result > max_available_width - self._required_margin:
  212. result -= column_width
  213. return result + self._required_margin
  214. def preferred_height(self, cli, width, max_available_height, wrap_lines):
  215. """
  216. Preferred height: as much as needed in order to display all the completions.
  217. """
  218. complete_state = cli.current_buffer.complete_state
  219. column_width = self._get_column_width(complete_state)
  220. column_count = max(1, (width - self._required_margin) // column_width)
  221. return int(math.ceil(len(complete_state.current_completions) / float(column_count)))
  222. def create_content(self, cli, width, height):
  223. """
  224. Create a UIContent object for this menu.
  225. """
  226. complete_state = cli.current_buffer.complete_state
  227. column_width = self._get_column_width(complete_state)
  228. self._render_pos_to_completion = {}
  229. def grouper(n, iterable, fillvalue=None):
  230. " grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx "
  231. args = [iter(iterable)] * n
  232. return zip_longest(fillvalue=fillvalue, *args)
  233. def is_current_completion(completion):
  234. " Returns True when this completion is the currently selected one. "
  235. return complete_state.complete_index is not None and c == complete_state.current_completion
  236. # Space required outside of the regular columns, for displaying the
  237. # left and right arrow.
  238. HORIZONTAL_MARGIN_REQUIRED = 3
  239. if complete_state:
  240. # There should be at least one column, but it cannot be wider than
  241. # the available width.
  242. column_width = min(width - HORIZONTAL_MARGIN_REQUIRED, column_width)
  243. # However, when the columns tend to be very wide, because there are
  244. # some very wide entries, shrink it anyway.
  245. if column_width > self.suggested_max_column_width:
  246. # `column_width` can still be bigger that `suggested_max_column_width`,
  247. # but if there is place for two columns, we divide by two.
  248. column_width //= (column_width // self.suggested_max_column_width)
  249. visible_columns = max(1, (width - self._required_margin) // column_width)
  250. columns_ = list(grouper(height, complete_state.current_completions))
  251. rows_ = list(zip(*columns_))
  252. # Make sure the current completion is always visible: update scroll offset.
  253. selected_column = (complete_state.complete_index or 0) // height
  254. self.scroll = min(selected_column, max(self.scroll, selected_column - visible_columns + 1))
  255. render_left_arrow = self.scroll > 0
  256. render_right_arrow = self.scroll < len(rows_[0]) - visible_columns
  257. # Write completions to screen.
  258. tokens_for_line = []
  259. for row_index, row in enumerate(rows_):
  260. tokens = []
  261. middle_row = row_index == len(rows_) // 2
  262. # Draw left arrow if we have hidden completions on the left.
  263. if render_left_arrow:
  264. tokens += [(Token.Scrollbar, '<' if middle_row else ' ')]
  265. # Draw row content.
  266. for column_index, c in enumerate(row[self.scroll:][:visible_columns]):
  267. if c is not None:
  268. tokens += self._get_menu_item_tokens(c, is_current_completion(c), column_width)
  269. # Remember render position for mouse click handler.
  270. for x in range(column_width):
  271. self._render_pos_to_completion[(column_index * column_width + x, row_index)] = c
  272. else:
  273. tokens += [(self.token.Completion, ' ' * column_width)]
  274. # Draw trailing padding. (_get_menu_item_tokens only returns padding on the left.)
  275. tokens += [(self.token.Completion, ' ')]
  276. # Draw right arrow if we have hidden completions on the right.
  277. if render_right_arrow:
  278. tokens += [(Token.Scrollbar, '>' if middle_row else ' ')]
  279. # Newline.
  280. tokens_for_line.append(tokens)
  281. else:
  282. tokens = []
  283. self._rendered_rows = height
  284. self._rendered_columns = visible_columns
  285. self._total_columns = len(columns_)
  286. self._render_left_arrow = render_left_arrow
  287. self._render_right_arrow = render_right_arrow
  288. self._render_width = column_width * visible_columns + render_left_arrow + render_right_arrow + 1
  289. def get_line(i):
  290. return tokens_for_line[i]
  291. return UIContent(get_line=get_line, line_count=len(rows_))
  292. def _get_column_width(self, complete_state):
  293. """
  294. Return the width of each column.
  295. """
  296. return max(get_cwidth(c.display) for c in complete_state.current_completions) + 1
  297. def _get_menu_item_tokens(self, completion, is_current_completion, width):
  298. if is_current_completion:
  299. token = self.token.Completion.Current
  300. else:
  301. token = self.token.Completion
  302. text, tw = _trim_text(completion.display, width)
  303. padding = ' ' * (width - tw - 1)
  304. return [(token, ' %s%s' % (text, padding))]
  305. def mouse_handler(self, cli, mouse_event):
  306. """
  307. Handle scoll and click events.
  308. """
  309. b = cli.current_buffer
  310. def scroll_left():
  311. b.complete_previous(count=self._rendered_rows, disable_wrap_around=True)
  312. self.scroll = max(0, self.scroll - 1)
  313. def scroll_right():
  314. b.complete_next(count=self._rendered_rows, disable_wrap_around=True)
  315. self.scroll = min(self._total_columns - self._rendered_columns, self.scroll + 1)
  316. if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
  317. scroll_right()
  318. elif mouse_event.event_type == MouseEventType.SCROLL_UP:
  319. scroll_left()
  320. elif mouse_event.event_type == MouseEventType.MOUSE_UP:
  321. x = mouse_event.position.x
  322. y = mouse_event.position.y
  323. # Mouse click on left arrow.
  324. if x == 0:
  325. if self._render_left_arrow:
  326. scroll_left()
  327. # Mouse click on right arrow.
  328. elif x == self._render_width - 1:
  329. if self._render_right_arrow:
  330. scroll_right()
  331. # Mouse click on completion.
  332. else:
  333. completion = self._render_pos_to_completion.get((x, y))
  334. if completion:
  335. b.apply_completion(completion)
  336. class MultiColumnCompletionsMenu(HSplit):
  337. """
  338. Container that displays the completions in several columns.
  339. When `show_meta` (a :class:`~prompt_toolkit.filters.CLIFilter`) evaluates
  340. to True, it shows the meta information at the bottom.
  341. """
  342. def __init__(self, min_rows=3, suggested_max_column_width=30, show_meta=True, extra_filter=True):
  343. show_meta = to_cli_filter(show_meta)
  344. extra_filter = to_cli_filter(extra_filter)
  345. # Display filter: show when there are completions but not at the point
  346. # we are returning the input.
  347. full_filter = HasCompletions() & ~IsDone() & extra_filter
  348. any_completion_has_meta = Condition(lambda cli:
  349. any(c.display_meta for c in cli.current_buffer.complete_state.current_completions))
  350. # Create child windows.
  351. completions_window = ConditionalContainer(
  352. content=Window(
  353. content=MultiColumnCompletionMenuControl(
  354. min_rows=min_rows, suggested_max_column_width=suggested_max_column_width),
  355. width=LayoutDimension(min=8),
  356. height=LayoutDimension(min=1)),
  357. filter=full_filter)
  358. meta_window = ConditionalContainer(
  359. content=Window(content=_SelectedCompletionMetaControl()),
  360. filter=show_meta & full_filter & any_completion_has_meta)
  361. # Initialise split.
  362. super(MultiColumnCompletionsMenu, self).__init__([
  363. completions_window,
  364. meta_window
  365. ])
  366. class _SelectedCompletionMetaControl(UIControl):
  367. """
  368. Control that shows the meta information of the selected token.
  369. """
  370. def preferred_width(self, cli, max_available_width):
  371. """
  372. Report the width of the longest meta text as the preferred width of this control.
  373. It could be that we use less width, but this way, we're sure that the
  374. layout doesn't change when we select another completion (E.g. that
  375. completions are suddenly shown in more or fewer columns.)
  376. """
  377. if cli.current_buffer.complete_state:
  378. state = cli.current_buffer.complete_state
  379. return 2 + max(get_cwidth(c.display_meta) for c in state.current_completions)
  380. else:
  381. return 0
  382. def preferred_height(self, cli, width, max_available_height, wrap_lines):
  383. return 1
  384. def create_content(self, cli, width, height):
  385. tokens = self._get_tokens(cli)
  386. def get_line(i):
  387. return tokens
  388. return UIContent(get_line=get_line, line_count=1 if tokens else 0)
  389. def _get_tokens(self, cli):
  390. token = Token.Menu.Completions.MultiColumnMeta
  391. state = cli.current_buffer.complete_state
  392. if state and state.current_completion and state.current_completion.display_meta:
  393. return [(token, ' %s ' % state.current_completion.display_meta)]
  394. return []