fix tests

This commit is contained in:
Will McGugan
2022-09-26 09:51:33 +01:00
parent 53d8e02d0d
commit 3f0955cbe5
19 changed files with 314 additions and 39 deletions

View File

@@ -16,6 +16,6 @@ The `Click` event is sent to a widget when the user clicks a mouse button.
| `button` | int | Index of mouse button |
| `shift` | bool | Shift key pressed if True |
| `meta` | bool | Meta key pressed if True |
| `ctrl` | bool | Ctrl key pressed if True |
| `ctrl` | bool | Ctrl key pressed if True |
| `screen_x` | int | Mouse x coordinate relative to the screen |
| `screen_y` | int | Mouse y coordinate relative to the screen |

View File

@@ -0,0 +1,7 @@
Bar {
height: 5;
content-align: center middle;
text-style: bold;
margin: 1 2;
color: $text;
}

View File

@@ -0,0 +1,31 @@
from textual.app import App, ComposeResult
from textual.color import Color
from textual.widgets import Footer, Static
class Bar(Static):
pass
class BindingApp(App):
CSS_PATH = "binding01.css"
BINDINGS = [
("r", "add_bar('red')", "Add Red"),
("g", "add_bar('green')", "Add Green"),
("b", "add_bar('blue')", "Add Blue"),
]
def compose(self) -> ComposeResult:
yield Footer()
def action_add_bar(self, color: str) -> None:
bar = Bar(color)
bar.styles.background = Color.parse(color).with_alpha(0.5)
self.mount(bar)
self.call_later(self.screen.scroll_end, animate=False)
if __name__ == "__main__":
app = BindingApp()
app.run()

View File

@@ -1,12 +0,0 @@
Screen {
layout: horizontal;
}
KeyLogger {
width: 1fr;
border: blank;
}
KeyLogger:focus {
border: wide $accent;
}

View File

@@ -3,19 +3,17 @@ from textual.widgets import TextLog
from textual import events
class KeyLogger(TextLog):
def on_key(self, event: events.Key) -> None:
self.write(event)
class InputApp(App):
"""App to display key events."""
CSS_PATH = "input02.css"
def compose(self) -> ComposeResult:
yield KeyLogger()
yield KeyLogger()
yield TextLog()
def on_key(self, event: events.Key) -> None:
self.query_one(TextLog).write(event)
def key_space(self) -> None:
self.bell()
if __name__ == "__main__":

View File

@@ -0,0 +1,17 @@
Screen {
layout: grid;
grid-size: 2 2;
grid-columns: 1fr;
}
KeyLogger {
border: blank;
}
KeyLogger:hover {
border: wide $secondary;
}
KeyLogger:focus {
border: wide $accent;
}

View File

@@ -0,0 +1,25 @@
from textual.app import App, ComposeResult
from textual.widgets import TextLog
from textual import events
class KeyLogger(TextLog):
def on_key(self, event: events.Key) -> None:
self.write(event)
class InputApp(App):
"""App to display key events."""
CSS_PATH = "key03.css"
def compose(self) -> ComposeResult:
yield KeyLogger()
yield KeyLogger()
yield KeyLogger()
yield KeyLogger()
if __name__ == "__main__":
app = InputApp()
app.run()

View File

@@ -8,9 +8,9 @@ This chapter will discuss how to make your app respond to input in the form of k
— Johnny Five
## Key events
## Keyboard input
The most fundamental way to receive input in via [Key](./events/key) events. Let's take a closer look at key events with an app that will display key events as you type.
The most fundamental way to receive input in via [Key](./events/key) events. Let's write an app to show key events as you type.
=== "key01.py"
@@ -23,4 +23,176 @@ The most fundamental way to receive input in via [Key](./events/key) events. Let
```{.textual path="docs/examples/guide/input/key01.py", press="T,e,x,t,u,a,l,!,_"}
```
Note the key event handler which
Note the key event handler on the app which logs all key events. if you press any key it will show up on the screen.
### Attributes
There are two main attributes on a key event. The `key` attribute is the _name_ of the key which may be a single character, or a longer identifier. Textual insures that the `key` attribute could always be used in a method name.
Key events also contain a `char` attribute which contains a printable character.
To illustrate the difference, try `key01.py` with the space key. You should see something like the following:
```{.textual path="docs/examples/guide/input/key01.py", press="space,_"}
```
The `key` attribute contains the word "space" while the `char` attribute contains a literal space.
### Key methods
Textual offers a convenient way of handling specific keys. If you create a method beginning with `key_` followed by the name of a key, then that method will be called in response to the key.
Let's add a key method to the example code.
```python title="key02.py" hl_lines="15-16"
--8<-- "docs/examples/guide/input/key01.py"
```
Note the addition of a `key_space` method which is called in response to the space key, and plays the terminal bell noise.
!!! note
Consider key methods to be a convenience for experimenting with Textual features. In nearly all cases, key [bindings](#bindings) and actions are referable.
## Input focus
Only a single widget may receive key events at a time. The widget which is actively receiving key events is said to have input _focus_.
The following example shows how focus works in practice.
=== "key03.py"
```python title="key03.py" hl_lines="16-20"
--8<-- "docs/examples/guide/input/key03.py"
```
=== "key03.css"
```python title="key03.css" hl_lines="15-17"
--8<-- "docs/examples/guide/input/key03.css"
```
=== "Output"
```{.textual path="docs/examples/guide/input/key03.py", press="tab,H,e,l,l,o,tab,W,o,r,l,d,!,_"}
```
The app splits the screen in to quarters, with a TextLog widget in each quarter. If you click any of the text logs, you should see that it is highlighted to show that thw widget has focus. Key events will be sent to the focused widget only.
!!! tip
the `:focus` CSS pseudo-selector can be used to apply a style to the focused widget.
You can also move focus by pressing the ++tab++ key which moves the focus to the next widget. Pressing ++shift+tab++ moves the focus in the opposite direction.
### Controlling focus
Textual will handle keyboard focus automatically, but you can tell Textual to focus a widget by calling the widget's [focus()][textual.widget.Widget.focus] method.
### Focus events
When a widget receives focus, it is sent a [Focus](../events/focus.md) event. When a widget loses focus it is sent a [Blur](../events/blur.md) event.
## Bindings
Keys may be associated with [actions](../guide/actions.md) for a given widget. This association is known as a key _binding_.
To create bindings, add a `BINDINGS` class variable to your app or widget. This should be a list of tuples of three strings. The first value is the key, the second is the action, the third value is a short human readable description.
The following example binds the keys ++r++, ++g++, and ++b++ to an action which adds a bar widget to the screen.
=== "binding01.py"
```python title="binding01.py" hl_lines="13-17"
--8<-- "docs/examples/guide/input/binding01.py"
```
=== "binding01.css"
```python title="binding01.css"
--8<-- "docs/examples/guide/input/binding01.css"
```
=== "Output"
```{.textual path="docs/examples/guide/input/binding01.py", press="r,g,b,b"}
```
Note how the footer displays bindings and makes them clickable, as an alternative to pressing the key.
### Binding class
The tuple of three strings may be enough for simple bindings, but you can also replace the tuple with a [Binding][textual.binding.Binding] instance which exposes a few more options.
### Why use bindings?
Bindings are particularly useful for configurable hot-keys. Bindings can also be inspected in widgets such as [Footer](../widgets/footer.md).
In a future version of Textual it will also be possible to specify bindings in a configuration file, which will allow users to override app bindings.
## Mouse Input
Textual will send events in response to mouse movement and mouse clicks. These events contain the coordinates of the mouse cursor relative to the terminal or widget.
!!! information
The trackpad (and possibly other pointer devices) are treated the same as the mouse in terminals.
Terminal coordinates are given by a pair values named `x` and `y`. The X coordinate is an offset in characters, extending from the left to the right of the screen. The Y coordinate is an offset in _lines_, extending from the top of the screen to the bottom.
Coordinates may be relative to the screen, so `(0, 0)` would be the top left of the screen. Coordinates may also be relative to a widget, where `(0, 0)` would be the top left of the widget itself.
<div class="excalidraw">
--8<-- "docs/images/input/coords.excalidraw.svg"
</div>
### Mouse movements
When you move the mouse cursor over a widget it will receive [MouseMove](../events/mouse_move.md) events which contain the coordinate of the mouse and information about what modified keys (++ctrl++, ++shift++ etc).
The following example shows mouse movements being used to _attach_ a widget to the mouse cursor.
=== "mouse01.py"
```python title="mouse01.py" hl_lines="12-14"
--8<-- "docs/examples/guide/input/mouse01.py"
```
=== "mouse01.css"
```python title="mouse01.css"
--8<-- "docs/examples/guide/input/mouse01.css"
```
If you run `mouse01.py` you should find that it logs the mouse move event, and keeps a widget pinned directly under the cursor.
The `on_mouse_move` handler sets the [offset](../styles/offset.md) style of the ball (a rectangular one) to match the mouse coordinates.
### Mouse capture
In the `mouse01.py` example there was a call to `capture_mouse()` in the mount handler. Textual will send mouse move events to the widget directly under the cursor. You can tell Textual to send all mouse events to a widget regardless of the position of the mouse cursor by calling [capture_mouse][textual.widget.Widget.capture_mouse].
Call [release_mouse][textual.widget.Widget.release_mouse] to restore the default behavior.
!!! warning
If you capture the mouse, be aware you might get negative mouse coordinates if the cursor is to the left of the widget.
Textual will send a [MouseCapture](../events/mouse_capture.md) event when the mouse is captured, and a [MouseRelease](../events/mouse_release.md) event when it is released.
### Click events
There are three events associated with clicking a button on your mouse. When the button is initially pressed, Textual sends a [MouseDown](../events/mouse_down.md) event, followed by [MouseUp](../events/mouse_up.md) when the button is released. Textual then sends a final [Click](../events/mouse_click.md) event.
If you want your app to respond to a mouse click you should prefer the Click event (and not MouseDown or MouseUp). This is because a future version of Textual may support other pointing devices which don't have up and down states.
### Scroll events
Most mice have a scroll wheel which you can use to scroll window underneath the cursor. Scrollable containers in Textual will handle these automatically, but you can handle [MouseDown](../events/mouse_scroll_down.md) and [MouseUp](../events/mouse_scroll_up) if you want build your own scrolling functionality.
!!! information
Terminal emulators will typically convert trackpad gestures in to scroll events.

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 21 KiB

View File

@@ -0,0 +1 @@
::: textual.binding.Binding

View File

@@ -38,7 +38,7 @@ nav:
- "events/load.md"
- "events/mount.md"
- "events/mouse_capture.md"
- "events/mouse_click.md"
- "events/click.md"
- "events/mouse_down.md"
- "events/mouse_move.md"
- "events/mouse_release.md"

View File

@@ -15,7 +15,7 @@ ANSI_SEQUENCES_KEYS: Mapping[str, Tuple[Keys, ...]] = {
"\x05": (Keys.ControlE,), # Control-E (end)
"\x06": (Keys.ControlF,), # Control-F (cursor forward)
"\x07": (Keys.ControlG,), # Control-G
"\x08": (Keys.ControlH,), # Control-H (8) (Identical to '\b')
"\x08": (Keys.Backspace,), # Control-H (8) (Identical to '\b')
"\x09": (Keys.Tab,), # Control-I (9) (Identical to '\t')
"\x0a": (Keys.ControlJ,), # Control-J (10) (Identical to '\n')
"\x0b": (Keys.ControlK,), # Control-K (delete until end of line; vertical tab)
@@ -47,7 +47,7 @@ ANSI_SEQUENCES_KEYS: Mapping[str, Tuple[Keys, ...]] = {
# handle backspace and control-h individually for the few terminals that
# support it. (Most terminals send ControlH when backspace is pressed.)
# See: http://www.ibb.net/~anne/keyboard.html
"\x7f": (Keys.ControlH,),
"\x7f": (Keys.Backspace,),
"\x1b\x7f": (Keys.ControlW,),
# Various
"\x1b[1~": (Keys.Home,), # tmux

View File

@@ -13,7 +13,7 @@ from ._types import MessageTarget
# When trying to determine whether the current sequence is a supported/valid
# escape sequence, at which length should we give up and consider our search
# to be unsuccessful?
from .keys import Keys
from .keys import KEY_NAME_REPLACEMENTS
_MAX_SEQUENCE_SEARCH_THRESHOLD = 20
@@ -102,7 +102,7 @@ class XTermParser(Parser[events.Event]):
key_events = sequence_to_key_events(character)
for event in key_events:
if event.key == "escape":
event = events.Key(event.sender, "^", None)
event = events.Key(event.sender, "circumflex_accent", "^")
on_token(event)
while not self.is_eof:
@@ -259,6 +259,7 @@ class XTermParser(Parser[events.Event]):
)
else:
name = sequence
name = KEY_NAME_REPLACEMENTS.get(name, name)
yield events.Key(self.sender, name, sequence)
except:
yield events.Key(self.sender, sequence, sequence)

View File

@@ -26,11 +26,17 @@ class NoBinding(Exception):
@dataclass
class Binding:
key: str
"""Key to bind."""
action: str
"""Action to bind to."""
description: str
"""Description of action."""
show: bool = True
"""Show the action in Footer, or False to hide."""
key_display: str | None = None
"""How the key should be shown in footer."""
allow_forward: bool = True
"""Allow forwarding from app to focused widget."""
@rich.repr.auto

View File

@@ -160,7 +160,7 @@ class ColorSystem:
("primary-background", primary),
("secondary-background", secondary),
("background", background),
("foregroud", foreground),
("foreground", foreground),
("panel", panel),
("boost", boost),
("surface", surface),

View File

@@ -318,14 +318,22 @@ class MouseEvent(InputEvent, bubble=True):
@property
def offset(self) -> Offset:
"""The mouse coordinate as an offset."""
return Offset(self.x, self.y)
@property
def screen_offset(self) -> Offset:
"""Mouse coordinate relative to the screen."""
return Offset(self.screen_x, self.screen_y)
@property
def delta(self) -> Offset:
"""Mouse coordinate delta (change since last event)."""
return Offset(self.delta_x, self.delta_y)
@property
def style(self) -> Style:
"""The (Rich) Style under the cursor."""
return self._style or Style()
@style.setter

View File

@@ -200,4 +200,9 @@ class Keys(str, Enum):
ShiftControlEnd = ControlShiftEnd
KEY_VALUES = frozenset(Keys.__members__.values())
# Unicode db contains some obscure names
# This mapping replaces them with more common terms
KEY_NAME_REPLACEMENTS = {
"solidus": "slash",
"reverse_solidus": "backslash",
}

View File

@@ -43,7 +43,7 @@ class TextWidgetBase(Widget):
changed = False
if event.char is not None and event.is_printable:
changed = self._editor.insert(event.char)
elif key == "ctrl+h":
elif key == "backspace":
changed = self._editor.delete_back()
elif key == "ctrl+d":
changed = self._editor.delete_forward()
@@ -358,7 +358,7 @@ class TextInput(TextWidgetBase, can_focus=True):
)
else:
self.app.bell()
elif key == "ctrl+h":
elif key == "backspace":
if cursor_index == start and self._editor.query_cursor_left():
self._slide_window(-1)
self._update_suggestion(event)

View File

@@ -101,12 +101,12 @@ def test_cant_match_escape_sequence_too_long(parser):
assert all(isinstance(event, Key) for event in events)
# When we backtrack '\x1b' is translated to '^'
assert events[0].key == "^"
assert events[0].key == "circumflex_accent"
# The rest of the characters correspond to the expected key presses
events = events[1:]
for index, character in enumerate(sequence[1:]):
assert events[index].key == character
assert events[index].char == character
@pytest.mark.parametrize(
@@ -141,9 +141,9 @@ def test_unknown_sequence_followed_by_known_sequence(parser, chunk_size):
events = list(itertools.chain.from_iterable(list(event) for event in events))
assert [event.key for event in events] == [
"^",
"[",
"?",
"circumflex_accent",
"left_square_bracket",
"question_mark",
"end",
]