| 1 |
import gi |
| 2 |
|
| 3 |
gi.require_version("Gdk", "4.0") |
| 4 |
gi.require_version("Gtk", "4.0") |
| 5 |
from gi.repository import Gdk, Gtk |
| 6 |
|
| 7 |
|
| 8 |
class ClipboardWindow(Gtk.ApplicationWindow): |
| 9 |
def __init__(self, *args, **kargs): |
| 10 |
super().__init__(*args, **kargs, title="Clipboard Example") |
| 11 |
|
| 12 |
box = Gtk.Box(spacing=12, orientation=Gtk.Orientation.VERTICAL) |
| 13 |
self.set_child(box) |
| 14 |
|
| 15 |
self.clipboard = Gdk.Display.get_default().get_clipboard() |
| 16 |
|
| 17 |
text_box = Gtk.Box(spacing=6, homogeneous=True) |
| 18 |
box.append(text_box) |
| 19 |
|
| 20 |
self.entry = Gtk.Entry(text="Some text you can copy") |
| 21 |
button_copy_text = Gtk.Button(label="Copy Text") |
| 22 |
button_copy_text.connect("clicked", self.copy_text) |
| 23 |
button_paste_text = Gtk.Button(label="Paste Text") |
| 24 |
button_paste_text.connect("clicked", self.paste_text) |
| 25 |
|
| 26 |
text_box.append(self.entry) |
| 27 |
text_box.append(button_copy_text) |
| 28 |
text_box.append(button_paste_text) |
| 29 |
|
| 30 |
image_box = Gtk.Box(spacing=6) |
| 31 |
box.append(image_box) |
| 32 |
|
| 33 |
self.picture = Gtk.Picture.new_for_filename("../images/application.png") |
| 34 |
self.picture.props.hexpand = True |
| 35 |
button_copy_image = Gtk.Button(label="Copy Image", valign=Gtk.Align.CENTER) |
| 36 |
button_copy_image.connect("clicked", self.copy_image) |
| 37 |
button_paste_image = Gtk.Button(label="Paste Image", valign=Gtk.Align.CENTER) |
| 38 |
button_paste_image.connect("clicked", self.paste_image) |
| 39 |
|
| 40 |
image_box.append(self.picture) |
| 41 |
image_box.append(button_copy_image) |
| 42 |
image_box.append(button_paste_image) |
| 43 |
|
| 44 |
def copy_text(self, _button): |
| 45 |
self.clipboard.set(self.entry.get_text()) |
| 46 |
|
| 47 |
def paste_text(self, _button): |
| 48 |
self.clipboard.read_text_async(None, self.on_paste_text) |
| 49 |
|
| 50 |
def on_paste_text(self, _clipboard, result): |
| 51 |
text = self.clipboard.read_text_finish(result) |
| 52 |
if text is not None: |
| 53 |
self.entry.set_text(text) |
| 54 |
|
| 55 |
def copy_image(self, _button): |
| 56 |
texture = self.picture.get_paintable() |
| 57 |
gbytes = texture.save_to_png_bytes() |
| 58 |
content = Gdk.ContentProvider.new_for_bytes("image/png", gbytes) |
| 59 |
self.clipboard.set_content(content) |
| 60 |
|
| 61 |
def paste_image(self, _button): |
| 62 |
self.clipboard.read_texture_async(None, self.on_paste_image) |
| 63 |
|
| 64 |
def on_paste_image(self, _clipboard, result): |
| 65 |
texture = self.clipboard.read_texture_finish(result) |
| 66 |
if texture is not None: |
| 67 |
self.picture.set_paintable(texture) |
| 68 |
|
| 69 |
|
| 70 |
def on_activate(app): |
| 71 |
win = ClipboardWindow(application=app) |
| 72 |
win.present() |
| 73 |
|
| 74 |
|
| 75 |
app = Gtk.Application(application_id="com.example.App") |
| 76 |
app.connect("activate", on_activate) |
| 77 |
|
| 78 |
app.run(None) |