from pywayland.client import Display, EventQueue
import wl4pgi

import gi
from gi.repository import GLib, Gio

# The display is NOT converted to GObject since they have a lot of special behaviour. Also
# you still have to roundtrip, but only after creating GObject adapters.
display = Display()
display.connect()
event_queue = EventQueue(display)


def on_geometry(output, x, y, pw, ph, subpixel, make, model, transform):
    print(output, x, y, pw, ph, subpixel, make, model, transform)


def on_geometry_1(output, x, y, pw, ph, subpixel, make, model, transform):
    print("Since it uses GObject signals, multiple handlers work without problems")
    print(f"Also, custom attributes work: {output.test}. There's always zero or one GObjects "
          f"per Wayland object.")


def on_global(registry, name, interface, version):
    if interface == "wl_output":
        # GObjects adapters only represent a proxy. Thus, to get the interface class for use
        # in this signal, you must go into pywayland.
        output = registry.bind(name, wl4pgi.wayland.WlOutput.interface_type, version)
        output.test = 0
        # Multiple handlers, transparently and with a single display and a single registry.
        output.connect("geometry", on_geometry)
        output.connect("geometry", on_geometry_1)
        display.roundtrip()


# Starting from the registry, operation is within PyGObject.
registry = wl4pgi.wayland.WlRegistry(display.get_registry())
registry.connect("global", on_global)
display.roundtrip()

# The next parts would be removed for GTK integration.
def on_display_event(self, source, condition):
    if condition & GLib.IO_IN:
        self.display.dispatch(queue=self.event_queue)
    return True


fd = display.get_fd()
GLib.io_add_watch(fd, GLib.IO_IN, on_display_event)

main_loop = GLib.MainLoop()
main_loop.run()
