|
| 1 | +import io |
| 2 | +from pathlib import Path |
| 3 | +from textual import on |
| 4 | +from textual.app import App, ComposeResult |
| 5 | +from textual.events import DeliveryComplete |
| 6 | +from textual.widgets import Button, Input, Label |
| 7 | + |
| 8 | + |
| 9 | +class ScreenshotApp(App[None]): |
| 10 | + def compose(self) -> ComposeResult: |
| 11 | + yield Button("screenshot: no filename or mime", id="button-1") |
| 12 | + yield Button("screenshot: screenshot.svg / open in browser", id="button-2") |
| 13 | + yield Button("screenshot: screenshot.svg / download", id="button-3") |
| 14 | + yield Button( |
| 15 | + "screenshot: screenshot.svg / open in browser / plaintext mime", |
| 16 | + id="button-4", |
| 17 | + ) |
| 18 | + yield Label("Deliver custom file:") |
| 19 | + yield Input(id="custom-path-input", placeholder="Path to file...") |
| 20 | + |
| 21 | + @on(Button.Pressed, selector="#button-1") |
| 22 | + def on_button_pressed(self) -> None: |
| 23 | + screenshot_string = self.export_screenshot() |
| 24 | + string_io = io.StringIO(screenshot_string) |
| 25 | + self.deliver_text(string_io) |
| 26 | + |
| 27 | + @on(Button.Pressed, selector="#button-2") |
| 28 | + def on_button_pressed_2(self) -> None: |
| 29 | + screenshot_string = self.export_screenshot() |
| 30 | + string_io = io.StringIO(screenshot_string) |
| 31 | + self.deliver_text( |
| 32 | + string_io, save_filename="screenshot.svg", open_method="browser" |
| 33 | + ) |
| 34 | + |
| 35 | + @on(Button.Pressed, selector="#button-3") |
| 36 | + def on_button_pressed_3(self) -> None: |
| 37 | + screenshot_string = self.export_screenshot() |
| 38 | + string_io = io.StringIO(screenshot_string) |
| 39 | + self.deliver_text( |
| 40 | + string_io, save_filename="screenshot.svg", open_method="download" |
| 41 | + ) |
| 42 | + |
| 43 | + @on(Button.Pressed, selector="#button-4") |
| 44 | + def on_button_pressed_4(self) -> None: |
| 45 | + screenshot_string = self.export_screenshot() |
| 46 | + string_io = io.StringIO(screenshot_string) |
| 47 | + self.deliver_text( |
| 48 | + string_io, |
| 49 | + save_filename="screenshot.svg", |
| 50 | + open_method="browser", |
| 51 | + mime_type="text/plain", |
| 52 | + ) |
| 53 | + |
| 54 | + @on(DeliveryComplete) |
| 55 | + def on_delivery_complete(self, event: DeliveryComplete) -> None: |
| 56 | + self.notify(title="Download complete", message=event.key) |
| 57 | + |
| 58 | + @on(Input.Submitted) |
| 59 | + def on_input_submitted(self, event: Input.Submitted) -> None: |
| 60 | + path = Path(event.value) |
| 61 | + if path.exists(): |
| 62 | + self.deliver_binary(path) |
| 63 | + else: |
| 64 | + self.notify( |
| 65 | + title="Invalid path", |
| 66 | + message="The path does not exist.", |
| 67 | + severity="error", |
| 68 | + ) |
| 69 | + |
| 70 | + |
| 71 | +app = ScreenshotApp() |
| 72 | +if __name__ == "__main__": |
| 73 | + app.run() |
0 commit comments