repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
textual
examples/calculator.py
.py
""" An implementation of a classic calculator, with a layout inspired by macOS calculator. Works like a real calculator. Click the buttons or press the equivalent keys. """ from decimal import Decimal from textual import events, on from textual.app import App, ComposeResult from textual.containers import Container f...
172
5,930
textual
examples/five_by_five.py
.py
"""Simple version of 5x5, developed for/with Textual.""" from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING, cast from textual.app import App, ComposeResult from textual.binding import Binding from textual.containers import Horizontal from textual.css.query import DOMQuery f...
324
10,056
textual
examples/clock.py
.py
""" An App to show the current time. """ from datetime import datetime from textual.app import App, ComposeResult from textual.widgets import Digits class ClockApp(App): CSS = """ Screen { align: center middle; } Digits { width: auto; } """ def compose(self) -> ComposeResult: yield Digi...
32
628
textual
examples/sidebar.py
.py
""" A simple animated sidebar. See comments for details. """ from textual.app import App, ComposeResult from textual.containers import Vertical from textual.reactive import reactive from textual.widget import Widget from textual.widgets import Footer, Label TEXT = """I must not fear. Fear is the mind-killer. Fear i...
96
2,234
textual
examples/code_browser.py
.py
""" Code browser example. Run with: python code_browser.py PATH """ from __future__ import annotations import sys from pathlib import Path from rich.traceback import Traceback from textual.app import App, ComposeResult from textual.containers import Container, VerticalScroll from textual.highlight import high...
89
2,561
textual
examples/markdown.py
.py
from __future__ import annotations from pathlib import Path from sys import argv from textual.app import App, ComposeResult from textual.binding import Binding from textual.reactive import var from textual.widgets import Footer, MarkdownViewer class MarkdownApp(App): """A simple Markdown viewer application.""" ...
79
2,476
textual
examples/dictionary.py
.py
from __future__ import annotations try: import httpx except ImportError: raise ImportError("Please install httpx with 'pip install httpx' ") from textual import getters, work from textual.app import App, ComposeResult from textual.containers import VerticalScroll from textual.widgets import Input, Markdown ...
76
2,464
textual
examples/json_tree.py
.py
import json from pathlib import Path from rich.text import Text from textual.app import App, ComposeResult from textual.widgets import Header, Footer, Tree from textual.widgets.tree import TreeNode class TreeApp(App): BINDINGS = [ ("a", "add", "Add node"), ("c", "clear", "Clear"), ("t",...
94
2,808
textual
examples/theme_sandbox.py
.py
from __future__ import annotations from functools import partial from typing import Any from textual._on import on from textual.app import App, ComposeResult from textual.binding import Binding from textual.containers import Container, Grid, Horizontal, VerticalScroll from textual.widgets import ( Button, Col...
495
13,619
textual
examples/pride.py
.py
from textual.app import App, ComposeResult from textual.widgets import Static class PrideApp(App): """Displays a pride flag.""" COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] def compose(self) -> ComposeResult: for color in self.COLORS: stripe = Static() ...
20
469
textual
examples/mother.py
.py
""" A simple example of chatting to an LLM with Textual. Lots of room for improvement here. See https://textual.textualize.io/blog/2024/09/15/anatomy-of-a-textual-user-interface/ """ # /// script # requires-python = ">=3.12" # dependencies = [ # "llm", # "textual", # ] # /// from textual import on, work fro...
108
2,916
textual
examples/merlin.py
.py
from __future__ import annotations import random from datetime import timedelta from time import monotonic from textual import events from textual.app import App, ComposeResult from textual.containers import Grid from textual.reactive import var from textual.renderables.gradient import LinearGradient from textual.wid...
178
4,694
textual
examples/splash.py
.py
from time import time from textual.app import App, ComposeResult, RenderableType from textual.containers import Container from textual.renderables.gradient import LinearGradient from textual.widgets import Static COLORS = [ "#881177", "#aa3355", "#cc6666", "#ee9944", "#eedd00", "#99dd55", ...
59
1,223
textual
examples/color_command.py
.py
from dataclasses import dataclass from functools import partial from textual import on from textual._color_constants import COLOR_NAME_TO_RGB from textual.app import App, ComposeResult from textual.command import Hit, Hits, Provider from textual.message import Message from textual.widgets import Header, Static @data...
68
1,695
textual
src/textual/types.py
.py
""" Export some objects that are used by Textual and that help document other features. """ from textual._animator import Animatable, EasingFunction from textual._context import NoActiveAppError from textual._path import CSSPathError, CSSPathType from textual._types import ( AnimationLevel, CallbackType, I...
53
1,381
textual
src/textual/_extrema.py
.py
from __future__ import annotations from fractions import Fraction from typing import NamedTuple from textual.geometry import Size class Extrema(NamedTuple): """Specifies minimum and maximum dimensions.""" min_width: Fraction | None = None max_width: Fraction | None = None min_height: Fraction | Non...
65
1,662
textual
src/textual/layout.py
.py
from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass from typing import TYPE_CHECKING, ClassVar, Iterable, NamedTuple from textual._spatial_map import SpatialMap from textual.canvas import Canvas, Rectangle from textual.geometry import Offset, Region, Size, Spacing ...
315
9,963
textual
src/textual/_event_broker.py
.py
from __future__ import annotations from typing import Any, NamedTuple class NoHandler(Exception): """Raised when handler isn't found in the meta.""" class HandlerArguments(NamedTuple): """Information for event handler.""" modifiers: set[str] action: Any def extract_handler_actions(event_name: st...
38
999
textual
src/textual/_callback.py
.py
from __future__ import annotations import asyncio from functools import partial from inspect import isawaitable, signature from typing import TYPE_CHECKING, Any, Callable from textual import active_app if TYPE_CHECKING: from textual.app import App # Maximum seconds before warning about a slow callback INVOKE_TI...
97
2,753
textual
src/textual/canvas.py
.py
""" A Canvas class used to render keylines. !!! note This API is experimental, and may change in the near future. """ from __future__ import annotations import sys from array import array from collections import defaultdict from dataclasses import dataclass from operator import itemgetter from typing import Nam...
285
8,420
textual
src/textual/logging.py
.py
""" A Textual Logging handler. If there is an active Textual app, then log messages will go via the app (and logged via textual console). If there is *no* active app, then log messages will go to stderr or stdout, depending on configuration. """ import sys from logging import Handler, LogRecord from textual._contex...
41
1,187
textual
src/textual/_import_app.py
.py
from __future__ import annotations import os import runpy import shlex import sys from pathlib import Path from typing import TYPE_CHECKING, cast if TYPE_CHECKING: from textual.app import App class AppFail(Exception): pass def shebang_python(candidate: Path) -> bool: """Does the given file look like i...
127
3,609
textual
src/textual/_work_decorator.py
.py
""" A decorator used to create [workers](/guide/workers). """ from __future__ import annotations from functools import partial, wraps from inspect import iscoroutinefunction from typing import TYPE_CHECKING, Callable, Coroutine, TypeVar, Union, cast, overload from typing_extensions import ParamSpec, TypeAlias if TY...
159
5,109
textual
src/textual/notifications.py
.py
"""Provides classes for holding and managing notifications.""" from __future__ import annotations from dataclasses import dataclass, field from time import time from typing import Iterator from uuid import uuid4 from rich.repr import Result from typing_extensions import Literal, Self, TypeAlias from textual.message...
121
3,714
textual
src/textual/_border.py
.py
from __future__ import annotations from functools import lru_cache from typing import TYPE_CHECKING, Iterable, Tuple, cast from rich.segment import Segment from textual.color import Color from textual.css.types import AlignHorizontal, EdgeStyle, EdgeType from textual.style import Style if TYPE_CHECKING: from ty...
480
13,018
textual
src/textual/_wrap.py
.py
from __future__ import annotations import re from typing import Iterable from rich.cells import get_character_cell_size from textual._cells import cell_len from textual._loop import loop_last from textual.expand_tabs import get_tab_widths re_chunk = re.compile(r"\S+\s*|\s+") def chunks(text: str) -> Iterable[tupl...
148
5,986
textual
src/textual/_path.py
.py
from __future__ import annotations import inspect from pathlib import Path, PurePath from typing import List, Union from typing_extensions import TypeAlias CSSPathType: TypeAlias = Union[ str, PurePath, List[Union[str, PurePath]], ] """Valid ways of specifying paths to CSS files.""" class CSSPathError(...
73
2,062
textual
src/textual/render.py
.py
from __future__ import annotations from rich.cells import cell_len from rich.console import Console, RenderableType from rich.protocol import rich_cast def measure( console: Console, renderable: RenderableType, default: int, *, container_width: int | None = None, ) -> int: """Measure a rich r...
42
1,135
textual
src/textual/errors.py
.py
""" General exception classes. """ from __future__ import annotations class TextualError(Exception): """Base class for Textual errors.""" class NoWidget(TextualError): """Specified widget was not found.""" class RenderError(TextualError): """An object could not be rendered.""" class DuplicateKeyHa...
27
534
textual
src/textual/selection.py
.py
from __future__ import annotations from operator import attrgetter from typing import TYPE_CHECKING, Iterable, Iterator, NamedTuple from textual.geometry import Offset, Shape if TYPE_CHECKING: from textual.widget import Widget class Selection(NamedTuple): """A selected range of lines.""" start: Offset...
462
16,772
textual
src/textual/driver.py
.py
from __future__ import annotations import asyncio import threading from abc import ABC, abstractmethod from contextlib import contextmanager from pathlib import Path from typing import TYPE_CHECKING, Any, BinaryIO, Iterator, Literal, TextIO from textual import events, log, messages from textual.events import MouseUp ...
302
10,325
textual
src/textual/app.py
.py
""" Here you will find the [App][textual.app.App] class, which is the base class for Textual apps. See [app basics](/guide/app) for how to build Textual apps. """ from __future__ import annotations import asyncio import importlib import inspect import io import mimetypes import os import signal import sys import th...
5,041
184,776
textual
src/textual/_dispatch_key.py
.py
from __future__ import annotations from typing import Callable from textual import events from textual._callback import invoke from textual.dom import DOMNode from textual.errors import DuplicateKeyHandlers from textual.message_pump import MessagePump async def dispatch_key(node: DOMNode, event: events.Key) -> bool...
69
2,462
textual
src/textual/file_monitor.py
.py
from __future__ import annotations import os from pathlib import Path from typing import Callable, Iterable, Sequence import rich.repr from textual._callback import invoke @rich.repr.auto class FileMonitor: """Monitors files for changes and invokes a callback when it does.""" _paths: set[Path] def __...
65
1,945
textual
src/textual/suggester.py
.py
""" Contains the `Suggester` class, used by the [Input](/widgets/input) widget. """ from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Iterable from textual.cache import LRUCache from textual.dom import DOMNode from textual.message import Mes...
145
4,723
textual
src/textual/_compat.py
.py
from __future__ import annotations import sys from typing import Any, Generic, TypeVar, overload if sys.version_info >= (3, 12): from functools import cached_property else: # based on the code from Python 3.14: # https://github.com/python/cpython/blob/ # 5507eff19c757a908a2ff29dfe423e35595fda00/Lib/fu...
74
2,849
textual
src/textual/fuzzy.py
.py
""" Fuzzy matcher. This class is used by the [command palette](/guide/command_palette) to match search terms. """ from __future__ import annotations from functools import lru_cache from operator import itemgetter from re import finditer from typing import Iterable, Sequence import rich.repr from textual.cache imp...
225
6,973
textual
src/textual/compose.py
.py
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from textual.app import App, ComposeResult from textual.widget import Widget __all__ = ["compose"] def compose( node: App | Widget, compose_result: ComposeResult | None = None ) -> list[Widget]: """Compose child w...
100
3,129
textual
src/textual/_widget_navigation.py
.py
""" Utilities to move index-based selections backward/forward. These utilities concern themselves with selections where not all options are available, otherwise it would be enough to increment/decrement the index and use the operator `%` to implement wrapping. """ from __future__ import annotations from itertools im...
183
5,702
textual
src/textual/system_commands.py
.py
""" This module contains `SystemCommands`, a command palette command provider for Textual system commands. This is a simple command provider that makes the most obvious application actions available via the [command palette][textual.command.CommandPalette]. !!! note The App base class installs this automaticall...
65
2,041
textual
src/textual/eta.py
.py
from __future__ import annotations import bisect from math import ceil from time import monotonic import rich.repr @rich.repr.auto(angular=True) class ETA: """Calculate speed and estimate time to arrival.""" def __init__( self, estimation_period: float = 60, extrapolate_period: float = 30 ) -> ...
130
4,645
textual
src/textual/_binary_encode.py
.py
""" An encoding / decoding format suitable for serializing data structures to binary. This is based on https://en.wikipedia.org/wiki/Bencode with some extensions. The following data types may be encoded: - None - int - bool - bytes - str - list - tuple - dict """ from __future__ import annotations from typing imp...
326
7,653
textual
src/textual/await_complete.py
.py
from __future__ import annotations from asyncio import Future, gather from typing import TYPE_CHECKING, Any, Awaitable, Generator import rich.repr from typing_extensions import Self from textual._debug import get_caller_file_and_line from textual.message_pump import MessagePump if TYPE_CHECKING: from textual.ty...
86
2,598
textual
src/textual/screen.py
.py
""" This module contains the `Screen` class and related objects. The `Screen` class is a special widget which represents the content in the terminal. See [Screens](/guide/screens/) for details. """ from __future__ import annotations import asyncio from functools import partial from operator import attrgetter from ...
2,195
79,934
textual
src/textual/signal.py
.py
""" Signals are a simple pub-sub mechanism. DOMNodes can subscribe to a signal, which will invoke a callback when the signal is published. """ from __future__ import annotations from typing import TYPE_CHECKING, Any, Awaitable, Callable, Generic, TypeVar, Union from weakref import WeakKeyDictionary, ref import ric...
138
4,296
textual
src/textual/_arrange.py
.py
from __future__ import annotations from collections import defaultdict from fractions import Fraction from operator import attrgetter from typing import TYPE_CHECKING, Iterable, Mapping, Sequence from textual._partition import partition from textual.geometry import NULL_OFFSET, NULL_SPACING, Region, Size, Spacing fro...
254
9,045
textual
src/textual/rlock.py
.py
from __future__ import annotations from asyncio import Lock, Task, current_task class RLock: """A re-entrant asyncio lock.""" def __init__(self) -> None: self._owner: Task | None = None self._count = 0 self._lock = Lock() async def acquire(self) -> None: """Wait until th...
62
1,657
textual
src/textual/_easing.py
.py
""" Define a series of easing functions for more natural-looking animations. Taken from https://easings.net/ and translated from JavaScript. """ from math import cos, pi, sin, sqrt def _in_out_expo(x: float) -> float: """https://easings.net/#easeInOutExpo""" if 0 < x < 0.5: return pow(2, 20 * x - 10)...
132
4,101
textual
src/textual/_files.py
.py
from __future__ import annotations from datetime import datetime def generate_datetime_filename( prefix: str, suffix: str, datetime_format: str | None = None ) -> str: """Generate a filename which includes the current date and time. Useful for ensuring a degree of uniqueness when saving files. Args...
29
1,002
textual
src/textual/_ansi_sequences.py
.py
from __future__ import annotations from typing import Mapping, Tuple from typing_extensions import Final from textual.keys import Keys class IgnoredSequence: """Class used to mark that a sequence should be ignored.""" IGNORE_SEQUENCE: Final[IgnoredSequence] = IgnoredSequence() """Constant to indicate that a ...
455
18,565
textual
src/textual/_line_split.py
.py
from __future__ import annotations import re # Pre-compile the regular expression and store it in a global constant LINE_AND_ENDING_PATTERN = re.compile(r"(.*?)(\r\n|\r|\n|$)", re.S) def line_split(input_string: str) -> list[tuple[str, str]]: r""" Splits an arbitrary string into a list of tuples, where each...
24
846
textual
src/textual/containers.py
.py
""" Container widgets for quick styling. With the exception of `Center` and `Middle` containers will fill all of the space in the parent widget. """ from __future__ import annotations from typing import ClassVar from textual.binding import Binding, BindingType from textual.layout import Layout from textual.layouts...
312
8,693
textual
src/textual/_node_list.py
.py
from __future__ import annotations import sys import weakref from operator import attrgetter from typing import TYPE_CHECKING, Any, Callable, Iterator, Sequence, overload import rich.repr if TYPE_CHECKING: from _typeshed import SupportsRichComparison from textual.dom import DOMNode from textual.widget i...
237
7,599
textual
src/textual/color.py
.py
""" This module contains a powerful [Color][textual.color.Color] class which Textual uses to manipulate colors. ## Named colors The following named colors are used by the [parse][textual.color.Color.parse] method. ```{.rich columns="80" title="colors"} from textual._color_constants import COLOR_NAME_TO_RGB from tex...
857
28,040
textual
src/textual/clock.py
.py
from __future__ import annotations from time import monotonic from typing import Callable import rich.repr @rich.repr.auto(angular=True) class Clock: """An object to get relative time. The `time` attribute of clock will return the time in seconds since the Clock was created or reset. """ def ...
75
2,022
textual
src/textual/_on.py
.py
from __future__ import annotations from typing import Callable, TypeVar from textual.css.model import SelectorSet from textual.css.parse import parse_selectors from textual.css.tokenizer import TokenError from textual.message import Message DecoratedType = TypeVar("DecoratedType") class OnDecoratorError(Exception)...
94
3,336
textual
src/textual/_sleep.py
.py
from __future__ import annotations from asyncio import Future, get_running_loop from threading import Event, Thread from time import perf_counter, sleep class Sleeper(Thread): def __init__( self, ) -> None: self._exit = False self._sleep_time = 0.0 self._event = Event() ...
61
1,620
textual
src/textual/expand_tabs.py
.py
from __future__ import annotations import re from rich.cells import cell_len from rich.text import Text _TABS_SPLITTER_RE = re.compile(r"(.*?\t|.+?$)") def get_tab_widths(line: str, tab_size: int = 4) -> list[tuple[str, int]]: """Splits a string line into tuples (str, int). Each tuple represents a section...
109
3,538
textual
src/textual/__main__.py
.py
from rich import print from rich.panel import Panel from textual.demo.demo_app import DemoApp if __name__ == "__main__": app = DemoApp() app.run() print( Panel.fit( "[b magenta]Hope you liked the demo![/]\n\n" "Please consider sponsoring me if you get value from my work.\n\...
20
563
textual
src/textual/_opacity.py
.py
from typing import Iterable, cast from rich.segment import Segment from rich.style import Style from textual.color import Color def _apply_opacity( segments: Iterable[Segment], base_background: Color, opacity: float, ) -> Iterable[Segment]: """Takes an iterable of foreground Segments and blends them...
43
1,527
textual
src/textual/__init__.py
.py
""" The root Textual module. Exposes some commonly used symbols. """ from __future__ import annotations import inspect import weakref from typing import TYPE_CHECKING, Callable import rich.repr from textual import constants from textual._context import active_app from textual._log import LogGroup, LogVerbosity fr...
208
5,694
textual
src/textual/filter.py
.py
"""Filter classes. !!! note Filters are used internally, and not recommended for use by Textual app developers. Filters are used internally to process terminal output after it has been rendered. Currently this is used internally to convert the application to monochrome, when the NO_COLOR env var is set. In the ...
289
7,880
textual
src/textual/keys.py
.py
from __future__ import annotations import unicodedata from enum import Enum from functools import lru_cache # Adapted from prompt toolkit https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/prompt_toolkit/keys.py class Keys(str, Enum): # type: ignore[no-redef] """ List of keys for use in key...
369
10,258
textual
src/textual/_resolve.py
.py
from __future__ import annotations from fractions import Fraction from itertools import accumulate from typing import TYPE_CHECKING, Iterable, Sequence, cast from typing_extensions import Literal from textual.box_model import BoxModel from textual.css.scalar import Scalar from textual.css.styles import RenderStyles ...
348
11,050
textual
src/textual/_color_constants.py
.py
from __future__ import annotations ANSI_COLORS = [ "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "bright_black", "bright_red", "bright_green", "bright_yellow", "bright_blue", "bright_magenta", "bright_cyan", "bright_white", ] """T...
193
6,099
textual
src/textual/constants.py
.py
""" This module contains constants, which may be set in environment variables. """ from __future__ import annotations import os from typing import get_args from typing_extensions import Final, TypeGuard from textual._types import AnimationLevel get_environ = os.environ.get def _get_environ_bool(name: str) -> boo...
176
5,666
textual
src/textual/_slug.py
.py
"""Provides a utility function and class for creating Markdown-friendly slugs. The approach to creating slugs is designed to be as close to GitHub-flavoured Markdown as possible. However, because there doesn't appear to be any actual documentation for this 'standard', the code here involves some guesswork and also som...
141
4,392
textual
src/textual/geometry.py
.py
""" Functions and classes to manage terminal geometry (anything involving coordinates or dimensions). """ from __future__ import annotations import os from functools import lru_cache from operator import attrgetter, itemgetter from typing import ( TYPE_CHECKING, Any, Collection, Iterable, Literal...
1,501
45,783
textual
src/textual/_compositor.py
.py
""" The compositor handles combining widgets into a single screen (i.e. compositing). It also stores the results of that process, so that Textual knows the widgets on the screen and their locations. The compositor uses this information to answer queries regarding the widget under an offset, or the style under an offs...
1,273
44,251
textual
src/textual/_loop.py
.py
from __future__ import annotations from typing import Iterable, Literal, Sequence, TypeVar T = TypeVar("T") def loop_first(values: Iterable[T]) -> Iterable[tuple[bool, T]]: """Iterate and generate a tuple with a flag for first value.""" iter_values = iter(values) try: value = next(iter_values) ...
87
2,602
textual
src/textual/_layout_resolve.py
.py
from __future__ import annotations from fractions import Fraction from typing import Sequence, cast from typing_extensions import Protocol class EdgeProtocol(Protocol): """Any object that defines an edge (such as Layout).""" # Size of edge in cells, or None for no fixed size size: int | None # Port...
86
3,274
textual
src/textual/message.py
.py
""" The base class for all messages (including events). """ from __future__ import annotations from typing import TYPE_CHECKING, ClassVar import rich.repr from typing_extensions import Self from textual import _time from textual._context import active_message_pump from textual.case import camel_to_snake if TYPE_C...
159
4,893
textual
src/textual/_log.py
.py
from enum import Enum class LogGroup(Enum): """A log group is a classification of the log message (*not* a level).""" UNDEFINED = 0 # Mainly for testing EVENT = 1 DEBUG = 2 INFO = 3 WARNING = 4 ERROR = 5 PRINT = 6 SYSTEM = 7 LOGGING = 8 WORKER = 9 class LogVerbosity(Enu...
24
436
textual
src/textual/suggestions.py
.py
from __future__ import annotations from difflib import get_close_matches from typing import Sequence def get_suggestion(word: str, possible_words: Sequence[str]) -> str | None: """ Returns a close match of `word` amongst `possible_words`. Args: word: The word we want to find a close match for ...
39
1,415
textual
src/textual/style.py
.py
""" The Style class contains all the information needed to generate styled terminal output. You won't often need to create Style objects directly, if you are using [Content][textual.content.Content] for output. But you might want to use styles for more customized widgets. """ from __future__ import annotations from ...
538
15,973
textual
src/textual/case.py
.py
import re from typing import Match, Pattern def camel_to_snake( name: str, _re_snake: Pattern[str] = re.compile("[a-z][A-Z]") ) -> str: """Convert name from CamelCase to snake_case. Args: name: A symbol name, such as a class name. Returns: Name in snake case. """ def repl(ma...
24
524
textual
src/textual/_profile.py
.py
""" Timer context manager, only used in debug. """ import contextlib from time import perf_counter from typing import Generator from textual import log @contextlib.contextmanager def timer(subject: str = "time", threshold: float = 0) -> Generator[None, None, None]: """print the elapsed time. (only used in debug...
27
641
textual
src/textual/pilot.py
.py
""" This module contains the `Pilot` class used by [App.run_test][textual.app.App.run_test] to programmatically operate an app. See the guide on how to [test Textual apps](/guide/testing). """ from __future__ import annotations import asyncio from typing import Any, Generic import rich.repr from textual._wait im...
571
22,848
textual
src/textual/worker.py
.py
""" This module contains the `Worker` class and related objects. See the guide for how to use [workers](/guide/workers). """ from __future__ import annotations import asyncio import enum import inspect from contextvars import ContextVar from threading import Event from time import monotonic from typing import ( ...
456
13,799
textual
src/textual/_segment_tools.py
.py
""" Tools for processing Segments, or lists of Segments. """ from __future__ import annotations import re from functools import lru_cache from typing import Iterable from rich.segment import Segment from rich.style import Style from textual._cells import cell_len from textual.css.types import AlignHorizontal, Align...
308
8,708
textual
src/textual/lazy.py
.py
""" Tools for lazy loading widgets. """ from __future__ import annotations from textual.widget import Widget class Lazy(Widget): """Wraps a widget so that it is mounted *lazily*. Lazy widgets are mounted after the first refresh. This can be used to display some parts of the UI very quickly, followed by...
142
4,329
textual
src/textual/messages.py
.py
from __future__ import annotations from typing import TYPE_CHECKING import rich.repr from textual._types import CallbackType from textual.geometry import Region from textual.message import Message if TYPE_CHECKING: from textual.widget import Widget @rich.repr.auto class CloseMessages(Message, verbose=True): ...
141
3,834
textual
src/textual/_doc.py
.py
from __future__ import annotations import hashlib import inspect import os import shlex from pathlib import Path from typing import Awaitable, Callable, Iterable, cast from textual._import_app import import_app from textual.app import App from textual.pilot import Pilot SCREENSHOT_CACHE = ".screenshot_cache" # Thi...
192
5,708
textual
src/textual/_text_area_theme.py
.py
from __future__ import annotations from dataclasses import dataclass, field, fields from typing import TYPE_CHECKING from rich.style import Style from textual.color import Color if TYPE_CHECKING: from textual.widgets import TextArea @dataclass class TextAreaTheme: """A theme for the `TextArea` widget. ...
435
18,067
textual
src/textual/design.py
.py
from __future__ import annotations from typing import Iterable import rich.repr from rich.console import group from rich.padding import Padding from rich.table import Table from rich.text import Text from textual.color import TRANSPARENT, WHITE, Color NUMBER_OF_SHADES = 3 # Where no content exists DEFAULT_DARK_BAC...
560
22,000
textual
src/textual/scroll_view.py
.py
""" `ScrollView` is a base class for [Line API](/guide/widgets#line-api) widgets. """ from __future__ import annotations from rich.console import RenderableType from textual._animator import EasingFunction from textual._types import AnimationLevel, CallbackType from textual.containers import ScrollableContainer from...
197
6,447
textual
src/textual/coordinate.py
.py
""" A class to store a coordinate, used by the [DataTable][textual.widgets.DataTable]. """ from __future__ import annotations from typing import NamedTuple class Coordinate(NamedTuple): """An object representing a row/column coordinate within a grid.""" row: int """The row of the coordinate within a gr...
54
1,247
textual
src/textual/_time.py
.py
import asyncio import sys from asyncio import sleep as asyncio_sleep from time import monotonic, perf_counter WINDOWS = sys.platform == "win32" if WINDOWS: time = perf_counter else: time = monotonic if WINDOWS: # sleep on windows as a resolution of 15ms # Python3.11 is somewhat better, but this hom...
53
1,410
textual
src/textual/_animator.py
.py
from __future__ import annotations import asyncio from abc import ABC, abstractmethod from dataclasses import dataclass from functools import partial from typing import TYPE_CHECKING, Any, Callable, TypeVar from typing_extensions import Protocol, runtime_checkable from textual import _time from textual._callback imp...
591
20,673
textual
src/textual/_markup_playground.py
.py
import json from textual import containers, events, on from textual.app import App, ComposeResult from textual.content import Content from textual.reactive import reactive from textual.widgets import Footer, Pretty, Static, TextArea class MarkupPlayground(App): TITLE = "Markup Playground" CSS = """ Scre...
151
4,957
textual
src/textual/binding.py
.py
""" This module contains the `Binding` class and related objects. See [bindings](/guide/input#bindings) in the guide for details. """ from __future__ import annotations import dataclasses from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, Iterator, Mapping, NamedTuple import rich.repr f...
401
13,746
textual
src/textual/pad.py
.py
from typing import cast from rich.align import Align, AlignMethod from rich.console import ( Console, ConsoleOptions, JustifyMethod, RenderableType, RenderResult, ) from rich.measure import Measurement from rich.segment import Segment, Segments from rich.style import Style class HorizontalPad: ...
80
2,306
textual
src/textual/_xterm_parser.py
.py
from __future__ import annotations import os import re from functools import lru_cache from typing import Any, Generator, Iterable from typing_extensions import Final from textual import constants, events, messages from textual._ansi_sequences import ANSI_SEQUENCES_KEYS, IGNORE_SEQUENCE from textual._keyboard_protoc...
469
18,334
textual
src/textual/_cells.py
.py
from typing import Callable from textual.expand_tabs import get_tab_widths __all__ = ["cell_len", "cell_width_to_column_index"] cell_len: Callable[[str], int] try: from rich.cells import cached_cell_len as cell_len except ImportError: from rich.cells import cell_len def cell_width_to_column_index(line: st...
45
1,416
textual
src/textual/walk.py
.py
""" Functions for *walking* the DOM. !!! note For most purposes you would be better off using [query][textual.dom.DOMNode.query], which uses these functions internally. """ from __future__ import annotations from collections import deque from operator import attrgetter from typing import TYPE_CHECKING, Iterable...
224
6,206
textual
src/textual/box_model.py
.py
from __future__ import annotations from fractions import Fraction from typing import NamedTuple from textual.geometry import Spacing class BoxModel(NamedTuple): """The result of `get_box_model`.""" # Content + padding + border width: Fraction height: Fraction margin: Spacing # Additional margi...
16
322
textual
src/textual/timer.py
.py
""" Contains the `Timer` class. Timer objects are created by [set_interval][textual.message_pump.MessagePump.set_interval] or [set_timer][textual.message_pump.MessagePump.set_timer]. """ from __future__ import annotations import weakref from asyncio import CancelledError, Event, Task, create_task, gather from ty...
204
6,255
textual
src/textual/_parser.py
.py
from __future__ import annotations from collections import deque from typing import Callable, Deque, Generator, Generic, Iterable, NamedTuple, TypeVar from textual._time import get_time class ParseError(Exception): """Base class for parse related errors.""" class ParseEOF(ParseError): """End of Stream."""...
127
3,307
textual
src/textual/_win_sleep.py
.py
""" A version of `time.sleep` that is more accurate than the standard library (even on Python 3.11). This should only be imported on Windows. """ from __future__ import annotations import asyncio from time import sleep as time_sleep from typing import Coroutine __all__ = ["sleep"] INFINITE = 0xFFFFFFFF WAIT_FAILE...
122
3,773
textual
src/textual/_two_way_dict.py
.py
from __future__ import annotations from typing import Generic, TypeVar Key = TypeVar("Key") Value = TypeVar("Value") class TwoWayDict(Generic[Key, Value]): """ A two-way mapping offering O(1) access in both directions. Wraps two dictionaries and uses them to provide efficient access to both values ...
73
2,009