lgi-devs / lgi

Dynamic Lua binding to GObject libraries using GObject-Introspection
MIT License
440 stars 70 forks source link

Cairo Native Interop? #317

Open A-Cloud-Ninja opened 7 months ago

A-Cloud-Ninja commented 7 months ago

Taking this as my basic example for lack of better explanation

local lgi = require("lgi")
local Gtk = lgi.require("Gtk", "3.0")
local cairo = lgi.cairo
local window = Gtk.Window {
    title = "Drawing Area",
    default_width = 600,
    default_height = 600,
    on_destroy = Gtk.main_quit
}

function window:on_draw(cr)
    --Here's the context `cr`
    --Lets assume this is passed by a controlling C process:
    local ptr = cr._native
    --Lets try to get an LGI context from the pointer:
    local ctx = cairo.Context(ptr) -- This will fail, because it expects a surface
end

local da = Gtk.DrawingArea {
    expand = true
}

window:add(da)
window:show_all()
Gtk:main()

Is there a proper way of retrieving the actual cairo.Context object being used with lgi here, or should a workaround be found?

A-Cloud-Ninja commented 7 months ago

I should add, removing the override from lgi/overrides/cairo.lua for the create method does indeed allow cairo.Context(ptr) to work appropriately here.

function window:on_draw(__ctx)
    local ptr = __ctx._native
    local cr = cairo.Context(ptr)
    cr:set_source_rgb(0, 0, 0)
    cr:paint()
    cr:set_source_rgb(1, 1, 1)
    cr:rectangle(10, 10, 100, 100)
    cr:fill()
    return true
end
A-Cloud-Ninja commented 7 months ago

Found a workaround for at least this specific issue:

local lgi = require("lgi")
local cairo = lgi.cairo
local core = require("lgi.core")

local ctx_ptr = some_C_controlled_call()
local context = core.record.new(cairo.Context,ctx_ptr)

And it works! But it also seems like a janky workaround. Feel free to close if this is the best intended method.

psychon commented 7 months ago

I actually do not have Lua installed anymore and cannot try this myself, but AwesomeWM does the following: https://github.com/awesomeWM/awesome/blob/8b1f8958b46b3e75618bc822d512bb4d449a89aa/lib/gears/surface.lua#L66-L67 No idea where that true comes from. I don't think something like this exists in cairo's C API. And from a quick browse through doc/, I also did not find anything else.

Besides that: Dunno. Your guess is as good as mine.