Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deadlock fix #4647

Merged
merged 10 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## Unreleased
## [0.68.0] - 2024-06-13

### Added

- Added `ContentSwitcher.add_content`

### Fixed

- Improved handling of non-tty input https://github.com/Textualize/textual/pull/4647

## [0.67.1] - 2024-06-12

### Changed
Expand Down Expand Up @@ -2128,6 +2132,7 @@ https://textual.textualize.io/blog/2022/11/08/version-040/#version-040
- New handler system for messages that doesn't require inheritance
- Improved traceback handling

[0.68.0]: https://github.com/Textualize/textual/compare/v0.67.1...v0.68.0
[0.67.1]: https://github.com/Textualize/textual/compare/v0.67.0...v0.67.1
[0.67.0]: https://github.com/Textualize/textual/compare/v0.66.0...v0.67.0
[0.66.0]: https://github.com/Textualize/textual/compare/v0.65.2...v0.66.0
Expand Down
1 change: 1 addition & 0 deletions examples/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ async def lookup_word(self, word: str) -> None:
results = response.json()
except Exception:
self.query_one("#results", Markdown).update(response.text)
return

if word == self.query_one(Input).value:
markdown = self.make_word_markdown(results)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "textual"
version = "0.67.1"
version = "0.68.0"
homepage = "https://github.com/Textualize/textual"
repository = "https://github.com/Textualize/textual"
documentation = "https://textual.textualize.io/"
Expand Down
15 changes: 11 additions & 4 deletions src/textual/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2564,6 +2564,7 @@ async def invoke_ready_callback() -> None:
console = Console()
console.print(self.screen._compositor)
console.print()

driver.stop_application_mode()
except Exception as error:
self._handle_exception(error)
Expand Down Expand Up @@ -2616,9 +2617,14 @@ async def recompose(self) -> None:

Recomposing will remove children and call `self.compose` again to remount.
"""
async with self.screen.batch():
await self.screen.query("*").exclude(".-textual-system").remove()
await self.screen.mount_all(compose(self))
if self._exit:
return
try:
async with self.screen.batch():
await self.screen.query("*").exclude(".-textual-system").remove()
await self.screen.mount_all(compose(self))
except ScreenStackError:
pass

def _register_child(
self, parent: DOMNode, child: Widget, before: int | None, after: int | None
Expand Down Expand Up @@ -3409,14 +3415,15 @@ async def _prune_node(self, root: Widget) -> None:
child._close_messages(wait=True) for child in close_children
]
try:
# Close all the children
await asyncio.wait_for(
asyncio.gather(*close_messages), self.CLOSE_TIMEOUT
)
except asyncio.TimeoutError:
# Likely a deadlock if we get here
# If not a deadlock, increase CLOSE_TIMEOUT, or set it to None
raise asyncio.TimeoutError(
f"Timeout waiting for {close_children!r} to close; possible deadlock\n"
f"Timeout waiting for {close_children!r} to close; possible deadlock (consider changing App.CLOSE_TIMEOUT)\n"
) from None
finally:
for child in children:
Expand Down
1 change: 0 additions & 1 deletion src/textual/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ def process_event(self, event: events.Event) -> None:
and not event.button
and self._last_move_event is not None
):

# Deduplicate self._down_buttons while preserving order.
buttons = list(dict.fromkeys(self._down_buttons).keys())
self._down_buttons.clear()
Expand Down
43 changes: 31 additions & 12 deletions src/textual/drivers/linux_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import rich.repr

from .. import events
from .._parser import ParseError
from .._xterm_parser import XTermParser
from ..driver import Driver
from ..geometry import Size
Expand Down Expand Up @@ -46,6 +47,7 @@ def __init__(
super().__init__(app, debug=debug, mouse=mouse, size=size)
self._file = sys.__stderr__
self.fileno = sys.__stdin__.fileno()
self.input_tty = sys.__stdin__.isatty()
self.attrs_before: list[Any] | None = None
self.exit_event = Event()
self._key_thread: Thread | None = None
Expand Down Expand Up @@ -235,7 +237,10 @@ def on_terminal_resize(signum, stack) -> None:
# defaults to ASCII EOT = Ctrl-D = 4.)
newattr[tty.CC][termios.VMIN] = 1

termios.tcsetattr(self.fileno, termios.TCSANOW, newattr)
try:
termios.tcsetattr(self.fileno, termios.TCSANOW, newattr)
except termios.error:
pass

self.write("\x1b[?25l") # Hide cursor
self.write("\x1b[?1004h") # Enable FocusIn/FocusOut.
Expand Down Expand Up @@ -264,6 +269,8 @@ def _request_terminal_sync_mode_support(self) -> None:
# Terminals should ignore this sequence if not supported.
# Apple terminal doesn't, and writes a single 'p' in to the terminal,
# so we will make a special case for Apple terminal (which doesn't support sync anyway).
if not self.input_tty:
return
if os.environ.get("TERM_PROGRAM", "") != "Apple_Terminal":
self.write("\033[?2026$p")
self.flush()
Expand Down Expand Up @@ -309,8 +316,11 @@ def disable_input(self) -> None:
if self._key_thread is not None:
self._key_thread.join()
self.exit_event.clear()
termios.tcflush(self.fileno, termios.TCIFLUSH)
except Exception as error:
try:
termios.tcflush(self.fileno, termios.TCIFLUSH)
except termios.error:
pass
except Exception:
# TODO: log this
pass

Expand All @@ -325,13 +335,14 @@ def stop_application_mode(self) -> None:
except termios.error:
pass

# Alt screen false, show cursor
self.write("\x1b[?1049l" + "\x1b[?25h")
self.write("\033[?1004l") # Disable FocusIn/FocusOut.
self.write(
"\x1b[<u"
) # Disable https://sw.kovidgoyal.net/kitty/keyboard-protocol/
self.flush()
# Alt screen false, show cursor
self.write("\x1b[?1049l")
self.write("\x1b[?25h")
self.write("\x1b[?1004l") # Disable FocusIn/FocusOut.
self.write(
"\x1b[<u"
) # Disable https://sw.kovidgoyal.net/kitty/keyboard-protocol/
self.flush()

def close(self) -> None:
"""Perform cleanup."""
Expand Down Expand Up @@ -375,18 +386,26 @@ def more_data() -> bool:
utf8_decoder = getincrementaldecoder("utf-8")().decode
decode = utf8_decoder
read = os.read
eof = False

try:
while not self.exit_event.is_set():
while not eof and not self.exit_event.is_set():
selector_events = selector.select(0.1)
for _selector_key, mask in selector_events:
if mask & EVENT_READ:
unicode_data = decode(
read(fileno, 1024), final=self.exit_event.is_set()
)
if not unicode_data:
# This can occur if the stdin is piped
eof = True
break
for event in feed(unicode_data):
self.process_event(event)
finally:
selector.close()
for event in feed(""):
try:
for event in feed(""):
pass
except ParseError:
pass
2 changes: 2 additions & 0 deletions src/textual/message_pump.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,8 @@ def app(self) -> "App[object]":
@property
def is_attached(self) -> bool:
"""Is this node linked to the app through the DOM?"""
if self.app._exit:
return False
node: MessagePump | None = self
while (node := node._parent) is not None:
if node.is_dom_root:
Expand Down
4 changes: 2 additions & 2 deletions src/textual/signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,13 @@ def subscribe(

if immediate:

def signal_callback(data: object):
def signal_callback(data: object) -> None:
"""Invoke the callback immediately."""
callback(data)

else:

def signal_callback(data: object):
def signal_callback(data: object) -> None:
"""Post the callback to the node, to call at the next opertunity."""
node.call_next(callback, data)

Expand Down
2 changes: 2 additions & 0 deletions src/textual/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -1005,6 +1005,8 @@ def mount_all(
Only one of ``before`` or ``after`` can be provided. If both are
provided a ``MountError`` will be raised.
"""
if self.app._exit:
return AwaitMount(self, [])
await_mount = self.mount(*widgets, before=before, after=after)
return await_mount

Expand Down
3 changes: 3 additions & 0 deletions src/textual/widgets/_footer.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,5 +172,8 @@ async def bindings_changed(screen: Screen) -> None:

self.screen.bindings_updated_signal.subscribe(self, bindings_changed)

def on_unmount(self) -> None:
self.screen.bindings_updated_signal.unsubscribe(self)

def watch_compact(self, compact: bool) -> None:
self.set_class(compact, "-compact")
11 changes: 9 additions & 2 deletions src/textual/widgets/_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from rich.text import Text

from ..app import RenderResult
from ..dom import NoScreen
from ..events import Click, Mount
from ..reactive import Reactive
from ..widget import Widget
Expand Down Expand Up @@ -213,10 +214,16 @@ def screen_sub_title(self) -> str:

def _on_mount(self, _: Mount) -> None:
async def set_title() -> None:
self.query_one(HeaderTitle).text = self.screen_title
try:
self.query_one(HeaderTitle).text = self.screen_title
except NoScreen:
pass

async def set_sub_title() -> None:
self.query_one(HeaderTitle).sub_text = self.screen_sub_title
try:
self.query_one(HeaderTitle).sub_text = self.screen_sub_title
except NoScreen:
pass

self.watch(self.app, "title", set_title)
self.watch(self.app, "sub_title", set_sub_title)
Expand Down
21 changes: 21 additions & 0 deletions tests/deadlock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""
Called by test_pipe.py

"""

from textual.app import App
from textual.binding import Binding
from textual.widgets import Footer


class MyApp(App[None]):
BINDINGS = [
Binding(key="q", action="quit", description="Quit the app"),
]

def compose(self):
yield Footer()


app = MyApp()
app.run()
20 changes: 20 additions & 0 deletions tests/test_pipe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import subprocess
import sys
from pathlib import Path

import pytest

skip_windows = pytest.mark.skipif(
sys.platform == "win32", reason="Syntax not supported on Windows"
)


@skip_windows
def test_deadlock():
"""Regression test for https://github.com/Textualize/textual/issues/4643"""
app_path = (Path(__file__) / "../deadlock.py").resolve().absolute()
result = subprocess.run(
f'echo q | python "{app_path}"', shell=True, capture_output=True
)
print(result.stdout)
assert result.returncode == 0
Loading