| 1 |
import asyncio |
| 2 |
import time |
| 3 |
import gi |
| 4 |
|
| 5 |
gi.require_version("Gtk", "4.0") |
| 6 |
from gi.repository import Gio, GLib, Gtk |
| 7 |
from gi.events import GLibEventLoopPolicy |
| 8 |
|
| 9 |
|
| 10 |
class DownloadWindow(Gtk.ApplicationWindow): |
| 11 |
def __init__(self, *args, **kwargs): |
| 12 |
super().__init__( |
| 13 |
*args, |
| 14 |
**kwargs, |
| 15 |
default_width=500, |
| 16 |
default_height=400, |
| 17 |
title="Async I/O Example", |
| 18 |
) |
| 19 |
|
| 20 |
self.background_task = None |
| 21 |
|
| 22 |
self.cancel_button = Gtk.Button(label="Cancel") |
| 23 |
self.cancel_button.connect("clicked", self.on_cancel_clicked) |
| 24 |
self.cancel_button.set_sensitive(False) |
| 25 |
|
| 26 |
self.start_button = Gtk.Button(label="Load") |
| 27 |
self.start_button.connect("clicked", self.on_start_clicked) |
| 28 |
|
| 29 |
textview = Gtk.TextView(vexpand=True) |
| 30 |
self.textbuffer = textview.get_buffer() |
| 31 |
scrolled = Gtk.ScrolledWindow() |
| 32 |
scrolled.set_child(textview) |
| 33 |
|
| 34 |
box = Gtk.Box( |
| 35 |
orientation=Gtk.Orientation.VERTICAL, |
| 36 |
spacing=6, |
| 37 |
margin_start=12, |
| 38 |
margin_end=12, |
| 39 |
margin_top=12, |
| 40 |
margin_bottom=12, |
| 41 |
) |
| 42 |
box.append(self.start_button) |
| 43 |
box.append(self.cancel_button) |
| 44 |
box.append(scrolled) |
| 45 |
|
| 46 |
self.set_child(box) |
| 47 |
|
| 48 |
def append_text(self, text): |
| 49 |
iter_ = self.textbuffer.get_end_iter() |
| 50 |
self.textbuffer.insert(iter_, f"[{time.time()}] {text}\n") |
| 51 |
|
| 52 |
def on_start_clicked(self, button): |
| 53 |
button.set_sensitive(False) |
| 54 |
self.cancel_button.set_sensitive(True) |
| 55 |
self.append_text("Start clicked...") |
| 56 |
|
| 57 |
self.background_task = asyncio.create_task(self.download()) |
| 58 |
|
| 59 |
def on_cancel_clicked(self, button): |
| 60 |
self.append_text("Cancel clicked...") |
| 61 |
self.background_task.cancel() |
| 62 |
|
| 63 |
async def download(self): |
| 64 |
file_ = Gio.File.new_for_uri("https://pygobject.gnome.org/") |
| 65 |
|
| 66 |
try: |
| 67 |
_success, content, _etag = await file_.load_contents_async() |
| 68 |
except GLib.GError as e: |
| 69 |
self.append_text(f"Error: {e.message}") |
| 70 |
else: |
| 71 |
content_text = content[:100].decode("utf-8") |
| 72 |
self.append_text(f"Got content: {content_text}...") |
| 73 |
finally: |
| 74 |
self.cancel_button.set_sensitive(False) |
| 75 |
self.start_button.set_sensitive(True) |
| 76 |
|
| 77 |
|
| 78 |
class Application(Gtk.Application): |
| 79 |
def do_activate(self): |
| 80 |
window = DownloadWindow(application=self) |
| 81 |
window.present() |
| 82 |
|
| 83 |
|
| 84 |
def main(): |
| 85 |
asyncio.set_event_loop_policy(GLibEventLoopPolicy()) |
| 86 |
app = Application() |
| 87 |
app.run() |
| 88 |
|
| 89 |
|
| 90 |
if __name__ == "__main__": |
| 91 |
main() |