Debian Codegraph @

git_delete_merged_branches/_multiselect.py

raw symbols SCIP
1 # Copyright (C) 2020 Sebastian Pipping <[email protected]>
2 # Licensed under GPL v3 or later
3
4 from abc import ABC
5 from dataclasses import dataclass
6 from typing import Any
7
8 from prompt_toolkit.application import Application
9 from prompt_toolkit.buffer import Buffer
10 from prompt_toolkit.document import Document
11 from prompt_toolkit.filters import is_searching
12 from prompt_toolkit.formatted_text.base import StyleAndTextTuples
13 from prompt_toolkit.key_binding import KeyBindings
14 from prompt_toolkit.layout import HSplit, Layout, Window
15 from prompt_toolkit.layout.containers import Container, VerticalAlign
16 from prompt_toolkit.layout.controls import BufferControl
17 from prompt_toolkit.layout.dimension import Dimension
18 from prompt_toolkit.layout.mouse_handlers import MouseHandlers
19 from prompt_toolkit.layout.processors import Processor, Transformation, TransformationInput
20 from prompt_toolkit.layout.screen import Screen, WritePosition
21 from prompt_toolkit.layout.scrollable_pane import ScrollablePane, ScrollOffsets
22 from prompt_toolkit.search import SearchState
23 from prompt_toolkit.widgets import SearchToolbar
24
25 from ._messenger import Messenger
26
27
28 class _ItemRenderProcessor(Processor):
29 """
30 A Prompt Toolkit input processor for Buffer that formats lines for display to the user.
31 """
32
33 def __init__(self, prompt: "_MultiSelectPrompt"):
34 self._prompt = prompt
35
36 def apply_transformation(self, transformation_input: TransformationInput) -> Transformation:
37 line_info = self._prompt.item_lines[transformation_input.lineno]
38
39 new_fragments: StyleAndTextTuples = []
40
41 highlighted = transformation_input.lineno == self._prompt.get_cursor_line()
42 cursor = "▶" if highlighted else " "
43 checkmark = "x" if line_info.selected else " "
44 fallback_style = (
45 self._prompt.highlighted_style if highlighted else self._prompt.neutral_style
46 )
47 new_fragments.append((fallback_style, f"{cursor} [{checkmark}] "))
48
49 # Apply new style where adequate
50 for fragment in transformation_input.fragments:
51 old_style, text = fragment
52
53 # NOTE: The idea is to respect search result markers (that have been inserted
54 # by HighlightSearchProcessor or HighlightIncrementalSearchProcessor)
55 # in item text, and only there.
56 new_style = old_style or fallback_style
57 new_fragments.append((new_style, text))
58
59 # Add right padding
60 padding_width = 2 + (self._prompt.peak_item_label_length - len(line_info.text))
61 new_fragments.append((fallback_style, " " * padding_width))
62
63 return Transformation(fragments=new_fragments)
64
65
66 class _NonItemRenderProcessor(Processor):
67 """
68 A Prompt Toolkit input processor for Buffer that formats lines for display to the user.
69 """
70
71 def __init__(self, prompt: "_MultiSelectPrompt", lines: list):
72 self._prompt = prompt
73 self._lines = lines
74
75 def apply_transformation(self, transformation_input: TransformationInput) -> Transformation:
76 line_info = self._lines[transformation_input.lineno]
77
78 if isinstance(line_info, self._prompt.HeaderLine):
79 new_style = self._prompt.header_style
80 else:
81 new_style = self._prompt.neutral_style
82
83 new_fragments: StyleAndTextTuples = [
84 (new_style, text) for _old_style, text in transformation_input.fragments
85 ]
86
87 return Transformation(fragments=new_fragments)
88
89
90 class _LineJumpingBuffer(Buffer):
91 """
92 A Prompt Toolkit Buffer that will skip all but the first search match per line
93 when iterating search matches using keys "n" and "N".
94 """
95
96 def apply_search(
97 self,
98 search_state: SearchState,
99 include_current_position: bool = True,
100 count: int = 1,
101 ) -> None:
102 previous_cursor_position = self.cursor_position
103 previous_line_index, _ = self.document.translate_index_to_position(self.cursor_position)
104
105 while True:
106 super().apply_search(
107 search_state=search_state,
108 include_current_position=include_current_position,
109 count=count,
110 )
111 if self.cursor_position == previous_cursor_position:
112 # The call to search has not moved the cursor, search has ended
113 return
114
115 current_line_index, _ = self.document.translate_index_to_position(self.cursor_position)
116 if current_line_index != previous_line_index:
117 # We changed lines already, that's all we wanted
118 return
119
120 previous_cursor_position = self.cursor_position
121 previous_line_index = current_line_index
122
123
124 class _HeightTrackingScrollablePane(ScrollablePane):
125 """
126 A copy of ``ScrollablePane`` that remembers the latest rendering height.
127 """
128
129 def __init__(self, content: Container, **kwargs):
130 super().__init__(content=content, **kwargs)
131 self.current_height = None
132
133 def write_to_screen(
134 self,
135 screen: Screen,
136 mouse_handlers: MouseHandlers,
137 write_position: WritePosition,
138 parent_style: str,
139 erase_bg: bool,
140 z_index: int | None,
141 ) -> None:
142 self.current_height = write_position.height
143 super().write_to_screen(
144 screen=screen,
145 mouse_handlers=mouse_handlers,
146 write_position=write_position,
147 parent_style=parent_style,
148 erase_bg=erase_bg,
149 z_index=z_index,
150 )
151
152
153 class _MultiSelectPrompt:
154 """
155 An interactive multi-select using the terminal, based on Prompt Toolkit.
156 """
157
158 @dataclass
159 class _LineBase(ABC):
160 text: str
161
162 @dataclass
163 class PlainLine(_LineBase):
164 pass
165
166 @dataclass
167 class HeaderLine(_LineBase):
168 pass
169
170 @dataclass
171 class ItemLine(_LineBase):
172 value: Any
173 selected: bool
174
175 def __init__(
176 self,
177 highlighted_style: str = "",
178 header_style: str = "",
179 initial_cursor_index=0,
180 min_selection_count=0,
181 ):
182 self.neutral_style: str = ""
183 self.highlighted_style: str = highlighted_style
184 self.header_style: str = header_style
185
186 self._initial_cursor_item_index: int = initial_cursor_index
187 self._min_selection_count: int = min_selection_count
188
189 self.peak_item_label_length: int = 0
190 self.item_lines: [_MultiSelectPrompt.ItemLine] = []
191 self._header_lines: [_MultiSelectPrompt.HeaderLine] = []
192 self._footer_lines: [_MultiSelectPrompt.PlainLine] = []
193
194 self._item_selection_pane: _HeightTrackingScrollablePane | None = None
195 self._buffer: Buffer | None = None
196 self._document: Document | None = None
197 self._accepted_selection: list[Any] = None
198
199 def _move_cursor_one_page_vertically(self, upwards: bool):
200 render_cursor_line = (
201 self._item_selection_pane.content.render_info.cursor_position.y
202 - self._item_selection_pane.vertical_scroll
203 )
204 page_height_in_lines = self._item_selection_pane.current_height
205
206 if upwards and render_cursor_line > 0:
207 new_line_index = self.get_cursor_line() - render_cursor_line
208 elif not upwards and render_cursor_line < page_height_in_lines - 1:
209 new_line_index = self.get_cursor_line() + (
210 page_height_in_lines - render_cursor_line - 1
211 )
212 else:
213 current_line_index = self.get_cursor_line()
214 if upwards:
215 new_line_index = max(0, current_line_index - page_height_in_lines)
216 else:
217 new_line_index = min(
218 len(self.item_lines) - 1, current_line_index + page_height_in_lines
219 )
220
221 self._move_cursor_to_line(new_line_index)
222
223 def _move_cursor_to_line(self, line_index: int):
224 self._buffer.cursor_position = self._document.translate_row_col_to_index(
225 row=line_index, col=0
226 )
227
228 def get_cursor_line(self):
229 row, col = self._document.translate_index_to_position(self._buffer.cursor_position)
230 return row
231
232 def _move_cursor_one_step_vertically(self, upwards: bool):
233 if len(self.item_lines) < 2:
234 return
235
236 current_line_index = self.get_cursor_line()
237
238 # Can we even move any further in that direction?
239 if (upwards and current_line_index == 0) or (
240 not upwards and current_line_index == len(self.item_lines) - 1
241 ):
242 return
243
244 self._move_cursor_to_line(current_line_index + (-1 if upwards else 1))
245
246 def _on_move_line_down(self, _event):
247 self._move_cursor_one_step_vertically(upwards=False)
248
249 def _on_move_line_up(self, _event):
250 self._move_cursor_one_step_vertically(upwards=True)
251
252 def _on_move_page_up(self, _event):
253 self._move_cursor_one_page_vertically(upwards=True)
254
255 def _on_move_page_down(self, _event):
256 self._move_cursor_one_page_vertically(upwards=False)
257
258 def _on_move_to_first(self, _event):
259 self._move_cursor_to_line(0)
260
261 def _on_move_to_last(self, _event):
262 self._move_cursor_to_line(len(self.item_lines) - 1)
263
264 def _on_toggle(self, _event):
265 line_index = self.get_cursor_line()
266 line_info = self.item_lines[line_index]
267 line_info.selected = not line_info.selected
268
269 def _on_accept(self, event):
270 selected_values = self._collect_selected_values()
271 if len(selected_values) < self._min_selection_count:
272 return
273 self._accepted_selection = selected_values
274 event.app.exit()
275
276 def _on_abort(self, event):
277 event.app.exit()
278
279 def add_header(self, text):
280 self._header_lines.append(self.HeaderLine(text))
281
282 def add_item(self, value: Any, label: str = None, selected: bool = False):
283 if label is None:
284 label = str(value)
285
286 self.peak_item_label_length = max(self.peak_item_label_length, len(label))
287
288 item_line = self.ItemLine(selected=selected, text=label, value=value)
289
290 self.item_lines.append(item_line)
291
292 def add_footer(self, text):
293 self._footer_lines.append(self.PlainLine(text))
294
295 def _create_key_bindings(self):
296 key_bindings = KeyBindings()
297
298 key_bindings.add("c-c")(self._on_abort)
299 key_bindings.add("q", filter=~is_searching)(self._on_abort)
300
301 key_bindings.add("space", filter=~is_searching)(self._on_toggle)
302
303 for key in ("enter", "right"):
304 key_bindings.add(key, filter=~is_searching)(self._on_accept)
305
306 for key in ("up", "k"):
307 key_bindings.add(key, filter=~is_searching)(self._on_move_line_up)
308 for key in ("down", "j"):
309 key_bindings.add(key, filter=~is_searching)(self._on_move_line_down)
310
311 key_bindings.add("pageup", filter=~is_searching)(self._on_move_page_up)
312 key_bindings.add("pagedown", filter=~is_searching)(self._on_move_page_down)
313 key_bindings.add("home", filter=~is_searching)(self._on_move_to_first)
314 key_bindings.add("end", filter=~is_searching)(self._on_move_to_last)
315
316 return key_bindings
317
318 def _create_text_display_window_for(self, lines: list[_LineBase]) -> Window:
319 document = Document(text="\n".join(line.text for line in lines))
320 buffer = Buffer(read_only=True, document=document)
321 buffer_control = BufferControl(
322 buffer=buffer, input_processors=[_NonItemRenderProcessor(prompt=self, lines=lines)]
323 )
324 return Window(buffer_control, wrap_lines=True, height=Dimension(min=len(lines)))
325
326 def _create_layout(self) -> tuple[Layout, _HeightTrackingScrollablePane]:
327 header = self._create_text_display_window_for(self._header_lines)
328 footer = self._create_text_display_window_for(self._footer_lines)
329
330 search = SearchToolbar(ignore_case=True)
331 buffer_control = BufferControl(
332 buffer=self._buffer,
333 input_processors=[_ItemRenderProcessor(prompt=self)],
334 preview_search=True,
335 search_buffer_control=search.control,
336 )
337 item_selection_window = Window(buffer_control, always_hide_cursor=True, wrap_lines=True)
338
339 pane_scroll_offsets = ScrollOffsets(top=0, bottom=0)
340 pane_height = Dimension(
341 min=1, max=self._document.line_count, preferred=self._document.line_count
342 )
343 item_selection_pane = _HeightTrackingScrollablePane(
344 item_selection_window, height=pane_height, scroll_offsets=pane_scroll_offsets
345 )
346 item_selection_pane.show_scrollbar = lambda: (
347 (item_selection_pane.current_height or 0) < self._document.line_count
348 )
349
350 item_selection_pane_plus_search = HSplit([item_selection_pane, search])
351 hsplit = HSplit(
352 [header, item_selection_pane_plus_search, footer], padding=1, align=VerticalAlign.TOP
353 )
354 return Layout(hsplit, focused_element=item_selection_pane), item_selection_pane
355
356 def _collect_selected_values(self):
357 return [item.value for item in self.item_lines if item.selected]
358
359 def get_selected_values(self) -> list[Any]:
360 self._document = Document(text="\n".join(line.text for line in self.item_lines))
361 self._buffer = _LineJumpingBuffer(read_only=True, document=self._document)
362 layout, self._item_selection_pane = self._create_layout()
363 app = Application(key_bindings=self._create_key_bindings(), layout=layout)
364
365 self._move_cursor_to_line(self._initial_cursor_item_index)
366 app.run()
367
368 return self._accepted_selection
369
370
371 def multiselect(
372 messenger: Messenger,
373 options: list[str],
374 initial_selection: list[int],
375 title: str,
376 help: str,
377 min_selection_count: int,
378 colorize: bool,
379 ) -> list[str]:
380 assert len(options) >= min_selection_count
381
382 menu = _MultiSelectPrompt(
383 highlighted_style="bold fg:black bg:white" if colorize else "",
384 header_style="bold fg:ansibrightgreen" if colorize else "",
385 initial_cursor_index=initial_selection[0] if initial_selection else 0,
386 min_selection_count=min_selection_count,
387 )
388
389 menu.add_header(title)
390
391 for i, option in enumerate(options):
392 menu.add_item(option, selected=i in initial_selection)
393
394 menu.add_footer(help)
395
396 messenger.produce_air()
397
398 selected_options = menu.get_selected_values()
399 if selected_options is None:
400 raise KeyboardInterrupt
401
402 messenger.request_air("\n")
403
404 return selected_options