Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/prompt_toolkit/layout/layout.py: 25%
187 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:07 +0000
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:07 +0000
1"""
2Wrapper for the layout.
3"""
4from __future__ import annotations
6from typing import Dict, Generator, Iterable, List, Optional, Union
8from prompt_toolkit.buffer import Buffer
10from .containers import (
11 AnyContainer,
12 ConditionalContainer,
13 Container,
14 Window,
15 to_container,
16)
17from .controls import BufferControl, SearchBufferControl, UIControl
19__all__ = [
20 "Layout",
21 "InvalidLayoutError",
22 "walk",
23]
25FocusableElement = Union[str, Buffer, UIControl, AnyContainer]
28class Layout:
29 """
30 The layout for a prompt_toolkit
31 :class:`~prompt_toolkit.application.Application`.
32 This also keeps track of which user control is focused.
34 :param container: The "root" container for the layout.
35 :param focused_element: element to be focused initially. (Can be anything
36 the `focus` function accepts.)
37 """
39 def __init__(
40 self,
41 container: AnyContainer,
42 focused_element: FocusableElement | None = None,
43 ) -> None:
44 self.container = to_container(container)
45 self._stack: list[Window] = []
47 # Map search BufferControl back to the original BufferControl.
48 # This is used to keep track of when exactly we are searching, and for
49 # applying the search.
50 # When a link exists in this dictionary, that means the search is
51 # currently active.
52 # Map: search_buffer_control -> original buffer control.
53 self.search_links: dict[SearchBufferControl, BufferControl] = {}
55 # Mapping that maps the children in the layout to their parent.
56 # This relationship is calculated dynamically, each time when the UI
57 # is rendered. (UI elements have only references to their children.)
58 self._child_to_parent: dict[Container, Container] = {}
60 if focused_element is None:
61 try:
62 self._stack.append(next(self.find_all_windows()))
63 except StopIteration as e:
64 raise InvalidLayoutError(
65 "Invalid layout. The layout does not contain any Window object."
66 ) from e
67 else:
68 self.focus(focused_element)
70 # List of visible windows.
71 self.visible_windows: list[Window] = [] # List of `Window` objects.
73 def __repr__(self) -> str:
74 return f"Layout({self.container!r}, current_window={self.current_window!r})"
76 def find_all_windows(self) -> Generator[Window, None, None]:
77 """
78 Find all the :class:`.UIControl` objects in this layout.
79 """
80 for item in self.walk():
81 if isinstance(item, Window):
82 yield item
84 def find_all_controls(self) -> Iterable[UIControl]:
85 for container in self.find_all_windows():
86 yield container.content
88 def focus(self, value: FocusableElement) -> None:
89 """
90 Focus the given UI element.
92 `value` can be either:
94 - a :class:`.UIControl`
95 - a :class:`.Buffer` instance or the name of a :class:`.Buffer`
96 - a :class:`.Window`
97 - Any container object. In this case we will focus the :class:`.Window`
98 from this container that was focused most recent, or the very first
99 focusable :class:`.Window` of the container.
100 """
101 # BufferControl by buffer name.
102 if isinstance(value, str):
103 for control in self.find_all_controls():
104 if isinstance(control, BufferControl) and control.buffer.name == value:
105 self.focus(control)
106 return
107 raise ValueError(f"Couldn't find Buffer in the current layout: {value!r}.")
109 # BufferControl by buffer object.
110 elif isinstance(value, Buffer):
111 for control in self.find_all_controls():
112 if isinstance(control, BufferControl) and control.buffer == value:
113 self.focus(control)
114 return
115 raise ValueError(f"Couldn't find Buffer in the current layout: {value!r}.")
117 # Focus UIControl.
118 elif isinstance(value, UIControl):
119 if value not in self.find_all_controls():
120 raise ValueError(
121 "Invalid value. Container does not appear in the layout."
122 )
123 if not value.is_focusable():
124 raise ValueError("Invalid value. UIControl is not focusable.")
126 self.current_control = value
128 # Otherwise, expecting any Container object.
129 else:
130 value = to_container(value)
132 if isinstance(value, Window):
133 # This is a `Window`: focus that.
134 if value not in self.find_all_windows():
135 raise ValueError(
136 "Invalid value. Window does not appear in the layout: %r"
137 % (value,)
138 )
140 self.current_window = value
141 else:
142 # Focus a window in this container.
143 # If we have many windows as part of this container, and some
144 # of them have been focused before, take the last focused
145 # item. (This is very useful when the UI is composed of more
146 # complex sub components.)
147 windows = []
148 for c in walk(value, skip_hidden=True):
149 if isinstance(c, Window) and c.content.is_focusable():
150 windows.append(c)
152 # Take the first one that was focused before.
153 for w in reversed(self._stack):
154 if w in windows:
155 self.current_window = w
156 return
158 # None was focused before: take the very first focusable window.
159 if windows:
160 self.current_window = windows[0]
161 return
163 raise ValueError(
164 f"Invalid value. Container cannot be focused: {value!r}"
165 )
167 def has_focus(self, value: FocusableElement) -> bool:
168 """
169 Check whether the given control has the focus.
170 :param value: :class:`.UIControl` or :class:`.Window` instance.
171 """
172 if isinstance(value, str):
173 if self.current_buffer is None:
174 return False
175 return self.current_buffer.name == value
176 if isinstance(value, Buffer):
177 return self.current_buffer == value
178 if isinstance(value, UIControl):
179 return self.current_control == value
180 else:
181 value = to_container(value)
182 if isinstance(value, Window):
183 return self.current_window == value
184 else:
185 # Check whether this "container" is focused. This is true if
186 # one of the elements inside is focused.
187 for element in walk(value):
188 if element == self.current_window:
189 return True
190 return False
192 @property
193 def current_control(self) -> UIControl:
194 """
195 Get the :class:`.UIControl` to currently has the focus.
196 """
197 return self._stack[-1].content
199 @current_control.setter
200 def current_control(self, control: UIControl) -> None:
201 """
202 Set the :class:`.UIControl` to receive the focus.
203 """
204 for window in self.find_all_windows():
205 if window.content == control:
206 self.current_window = window
207 return
209 raise ValueError("Control not found in the user interface.")
211 @property
212 def current_window(self) -> Window:
213 "Return the :class:`.Window` object that is currently focused."
214 return self._stack[-1]
216 @current_window.setter
217 def current_window(self, value: Window) -> None:
218 "Set the :class:`.Window` object to be currently focused."
219 self._stack.append(value)
221 @property
222 def is_searching(self) -> bool:
223 "True if we are searching right now."
224 return self.current_control in self.search_links
226 @property
227 def search_target_buffer_control(self) -> BufferControl | None:
228 """
229 Return the :class:`.BufferControl` in which we are searching or `None`.
230 """
231 # Not every `UIControl` is a `BufferControl`. This only applies to
232 # `BufferControl`.
233 control = self.current_control
235 if isinstance(control, SearchBufferControl):
236 return self.search_links.get(control)
237 else:
238 return None
240 def get_focusable_windows(self) -> Iterable[Window]:
241 """
242 Return all the :class:`.Window` objects which are focusable (in the
243 'modal' area).
244 """
245 for w in self.walk_through_modal_area():
246 if isinstance(w, Window) and w.content.is_focusable():
247 yield w
249 def get_visible_focusable_windows(self) -> list[Window]:
250 """
251 Return a list of :class:`.Window` objects that are focusable.
252 """
253 # focusable windows are windows that are visible, but also part of the
254 # modal container. Make sure to keep the ordering.
255 visible_windows = self.visible_windows
256 return [w for w in self.get_focusable_windows() if w in visible_windows]
258 @property
259 def current_buffer(self) -> Buffer | None:
260 """
261 The currently focused :class:`~.Buffer` or `None`.
262 """
263 ui_control = self.current_control
264 if isinstance(ui_control, BufferControl):
265 return ui_control.buffer
266 return None
268 def get_buffer_by_name(self, buffer_name: str) -> Buffer | None:
269 """
270 Look in the layout for a buffer with the given name.
271 Return `None` when nothing was found.
272 """
273 for w in self.walk():
274 if isinstance(w, Window) and isinstance(w.content, BufferControl):
275 if w.content.buffer.name == buffer_name:
276 return w.content.buffer
277 return None
279 @property
280 def buffer_has_focus(self) -> bool:
281 """
282 Return `True` if the currently focused control is a
283 :class:`.BufferControl`. (For instance, used to determine whether the
284 default key bindings should be active or not.)
285 """
286 ui_control = self.current_control
287 return isinstance(ui_control, BufferControl)
289 @property
290 def previous_control(self) -> UIControl:
291 """
292 Get the :class:`.UIControl` to previously had the focus.
293 """
294 try:
295 return self._stack[-2].content
296 except IndexError:
297 return self._stack[-1].content
299 def focus_last(self) -> None:
300 """
301 Give the focus to the last focused control.
302 """
303 if len(self._stack) > 1:
304 self._stack = self._stack[:-1]
306 def focus_next(self) -> None:
307 """
308 Focus the next visible/focusable Window.
309 """
310 windows = self.get_visible_focusable_windows()
312 if len(windows) > 0:
313 try:
314 index = windows.index(self.current_window)
315 except ValueError:
316 index = 0
317 else:
318 index = (index + 1) % len(windows)
320 self.focus(windows[index])
322 def focus_previous(self) -> None:
323 """
324 Focus the previous visible/focusable Window.
325 """
326 windows = self.get_visible_focusable_windows()
328 if len(windows) > 0:
329 try:
330 index = windows.index(self.current_window)
331 except ValueError:
332 index = 0
333 else:
334 index = (index - 1) % len(windows)
336 self.focus(windows[index])
338 def walk(self) -> Iterable[Container]:
339 """
340 Walk through all the layout nodes (and their children) and yield them.
341 """
342 yield from walk(self.container)
344 def walk_through_modal_area(self) -> Iterable[Container]:
345 """
346 Walk through all the containers which are in the current 'modal' part
347 of the layout.
348 """
349 # Go up in the tree, and find the root. (it will be a part of the
350 # layout, if the focus is in a modal part.)
351 root: Container = self.current_window
352 while not root.is_modal() and root in self._child_to_parent:
353 root = self._child_to_parent[root]
355 yield from walk(root)
357 def update_parents_relations(self) -> None:
358 """
359 Update child->parent relationships mapping.
360 """
361 parents = {}
363 def walk(e: Container) -> None:
364 for c in e.get_children():
365 parents[c] = e
366 walk(c)
368 walk(self.container)
370 self._child_to_parent = parents
372 def reset(self) -> None:
373 # Remove all search links when the UI starts.
374 # (Important, for instance when control-c is been pressed while
375 # searching. The prompt cancels, but next `run()` call the search
376 # links are still there.)
377 self.search_links.clear()
379 self.container.reset()
381 def get_parent(self, container: Container) -> Container | None:
382 """
383 Return the parent container for the given container, or ``None``, if it
384 wasn't found.
385 """
386 try:
387 return self._child_to_parent[container]
388 except KeyError:
389 return None
392class InvalidLayoutError(Exception):
393 pass
396def walk(container: Container, skip_hidden: bool = False) -> Iterable[Container]:
397 """
398 Walk through layout, starting at this container.
399 """
400 # When `skip_hidden` is set, don't go into disabled ConditionalContainer containers.
401 if (
402 skip_hidden
403 and isinstance(container, ConditionalContainer)
404 and not container.filter()
405 ):
406 return
408 yield container
410 for c in container.get_children():
411 # yield from walk(c)
412 yield from walk(c, skip_hidden=skip_hidden)