Code Monkey home page Code Monkey logo

lgi's Introduction

LGI

LGI is gobject-introspection based dynamic Lua binding to GObject based libraries. It allows using GObject-based libraries directly from Lua.

Licensed under MIT-style license, see LICENSE file for full text.

Home of the project is on GitHub.

LGI is tested and compatible with standard Lua 5.1, Lua 5.2, Lua 5.3 and LuaJIT2. Compatibility with other Lua implementations is not tested yet. Lua 5.4 is only supported experimentally.

If you need to support pre-gobject-introspection GTK (ancient GTK+ 2.x releases), use Lua-Gnome.

Installation:

In order to be able to compile native part of lgi, gobject-introspection >= 0.10.8 development package must be installed, although preferred version is >= 1.30. The development package is called libgirepository1.0-dev on debian-based systems (like Ubuntu) and gobject-introspection-devel on RedHat-based systems (like Fedora).

Using LuaRocks:

luarocks install lgi

Alternatively, use make-based installation:

make
[sudo] make install [PREFIX=<prefix>] [DESTDIR=<destdir>]

Please note that on BSD-systems you may need to use 'gmake'.

Building via Meson is also supported, with the same requirements, plus a Meson installation along with the Ninja build tool, in an empty build directory:

cd $(builddir)
meson $(lgi_srcroot) [--prefix=<prefix>] [--buildtype=<buildtype>] [--pkg-config-path=<pkgconfigpath>] [-Dlua-pc=...] [-Dlua-bin=...]
ninja
ninja test
[sudo] ninja install

Building lgi with Visual Studio 2013 and later is also supported via Meson. It is recommended in this case that CMake is also installed to make finding Lua or LuaJIT easier, since Lua and LuaJIT support Visual Studio builds via batch files or manual compilation of sources. Ensure that %INCLUDE% includes the path to the Lua or LuaJIT headers, and %LIB% includes the path where the lua5x.lib from Lua or LuaJIT can be found, and ensure that lua5x.dll and lua.exe or luajit.exe can be found in %PATH% and run correctly. For building with LuaJIT, please do not pass in -Dlua-pc=luajit, but do pass in -Dlua-bin=luajit in the Meson command line so that the LuaJIT interpreter can be found correctly.

Usage

See examples in samples/ directory. Documentation is available in doc/ directory in markdown format. Process it with your favorite Markdown processor if you want to read it in HTML. You can also check the moonsteal/lua-gtk-examples repository, where you can find a variety of Lua Gtk examples.

Credits

List of contributors, in no particular order:

  • Uli Schlachter
  • Jasper Lievisse Adriaanse
  • Ildar Mulyukov
  • Nils Nordman
  • Ignas Anikevicius
  • Craig Barnes
  • Nicola Fontana
  • Andreas Stührk
  • Aaron Faanes
  • Jiří Klimeš
  • Garrett Regier
  • Kenneth Zhou
  • Travis Hoppe
  • Tobias Jakobs
  • Heiko Becker
  • Vincent Bermel
  • Szunti

Many other people contributed to what lgi is today, in many forms - writing patches, reporting bugs, packaging for distributions, providing ideas, spreading a word... Many thanks to all of you!

History

0.9.2 (9-Oct-2017)

  • fix assorted crashes in closure callback invocation code
  • fix double-free bug caused by incorrect annotation of Gio.DBusProxy.get_interface_info
  • fix marshaling of arrays of pointers
  • make objects unusable in __gc metamethod
  • work around API break in GLib 2.54
  • use structured GLib logging when available
  • add Gio.Async support also for static methods and global functions
  • better error message when Gtk.init fails
  • add support for Travis
  • don't hardcode pkg-config executable
  • fix URI in GStreamer sample
  • fix flags for DBus samples

0.9.1 (27-May-2016)

  • marshal NULL strings as nil instead of empty strings. This allows use of e.g. DataInputStream:read_line() APIs.
  • fix and improve build for OSX and Win-based configurations
  • add support for arrays with lengths as struct fields
  • allow GLib.Variant construction for lightuserdata
  • fix gtop binding (certain structs could not be imported)
  • adapt to new set of annotations in newer glib
  • assorted Lua5.3 fixes, lgi is now fully Lua5.3 compatible
  • fix binding of Gdk.Rectangle from newer GDK

0.9.0 (23-Mar-2015)

  • new feature: allow defining new properties on custom GObject subclasses implemented using lgi
  • fix: improve compatibility with locales (turkish)
  • fix: GPtrArray handling
  • fix: improve behavior when running in assorted multiple-embedded and concurrent scenarios

0.8.0 (02-Jul-2014)

  • new feature: add automatically-generated wrappers for do_async()/do_finish() pairs. Documented as Gio.Async namespace functionality.
  • new feature: automatically initialize objects implementing Gio.Initable and Gio.AsyncInitable interfaces.
  • new feature: GLib.Error is now handled properly, functions returning errors return GLib.Error instances instead of error numbers and strings. This also allows overriding virtual methods from Lua which report errors by returning GLib.Error
  • new feature: GLib.Bytes support, adding # operator and 'data' property allowing easy use of GLib.Bytes object. This leads to deprecation of seldomly used modifiable buffers extensions.
  • optimization: type attribute caching brings significant speedup of method and property lookups.
  • fix: Gtk: override for Gtk.Menu.popup() compatible with new GTK annotation.
  • fix: cairo: assorted small fixes of bad signatures, added some convenience properties.
  • fix: GLib: add overrides for GLib.MarkupParser
  • fix: Gio: add overrides for Gio.DBus*Info structures
  • fix: Pango: add override for Pango.GlyphString.glyphs array
  • fix: Gdk: Add override inheriting specific Gdk.EventXxx from Gdk.Event
  • fix: Compile cleanly against Lua5.2 with compatibility mode turned on
  • fix: avoid leak when adding already cached owned record and for retrieving Variant from Value.

0.7.2 (12-Sep-2013)

  • fix: improper marshalling of certain APIs passing pointers to records.
  • fix: cairo.PsSurface.create() had incorrect signature, missing filename.
  • fix: If GTK initialization fails, raise Lua exception instead of hard-crash of calling process.
  • fix: when running test in devel tree, prefer lgi from devel tree instead of the installed one.
  • add: cairo.Status.to_string() API
  • fix: avoid referencing GdkRGBA in GDk override when targetting Gdk2.0, which does not have GdkRGBA.
  • fix: replace GStaticRecMutex with GRecMutex to avoid compilation warnings.
  • fix: Gtk.Container.'child' pseudoproperty works even in Gtk2, where it was shadowed by internal field.
  • fix: add workaround for improperly parsed g_bytes_get_data() annotation.
  • fix: add workarounf for incorrect annotation on Pango.Layour.set_attributes(), which caused memory leak.
  • fix: adapt to Gio.InputStream.[read|read_all|read_async] API change, which does not accept buffer length argument any more (due to the newly added annotations).

0.7.1 (4-Mar-2013)

  • Add support for GStreamer 1.0, while still retaining GStreamer 0.10 compatibility.
  • fix: crash when trying to to access '_class' attribute of class which does not have public classstruct exposed in typelib
  • fix: crash when passing 'nil' to transfer=full struct (caused crash of Awesome WM during startup).

0.7.0 (23-Feb-2013)

  • New feature - subclassing. Allows creating GObject subclasses and implementing their virtual methods in Lua.
  • cairo: add support for most 1.12-specific cairo features
  • cairo: create hierarchy for Pattern subclasses
  • cairo: assorted small cairo bugfixes
  • samples: add GDBus client example
  • samples: add GnomeKeyring example
  • samples: GTK: offscreen window demos
  • samples: libsoup simple http server example
  • platforms: added support for darwin/macosx platform
  • platforms: additional fixes for OpenBSD
  • build: Makefiles now respect CFLAGS and LDFLAGS env vars values
  • build: Add Lua version option into Makefile
  • fix: custom ffi enum/flags handling
  • fix: more exotic callback-to-Lua marshalling scenarios
  • fix: do not allow GTK+ and gstreamer to call setlocale() - this might break Lua in some locales
  • fix: small adjustments, fixes and additions in Gtk override
  • fix: tons of other small fixes

0.6.2 (25-Jun-2012)

  • Avoid unexpected dependency on cairo-devel, cairo-runtime is now enough
  • Make set_resident() more robust and fix stack leak for Lua 5.2 case, avoid useless warning when set_resident() fails (to accommodate for static linking case).
  • Fix small memory leak (mutex) which occured once per opened lua_State using lgi.

0.6.1 (19-Jun-2012)

  • objects and structs: actually implement _type property as documented
  • tests: Fix regression tests for less common platforms
  • Pango: Add a few missing overrides
  • cairo: Fix Context:user_to_device() family of methods.
  • GStreamer: Add support for transfer!=none for input objects. This is needed to avoid leaks caused by strange usage of transfer annotations of gstreamer-0.10
  • GStreamer: Add more missing overrides
  • GStreamer: Fix and improve samples
  • Various fixes for usecase when Lua context with loaded lgi is closed and opened again
  • Gtk: Add missing Gtk.Builder:connect_signals() override

0.6 (22-May-2012)

  • Add cairo bindings, cairo sample and finish some gtk-demo parts which were requiring cairo

0.5.1 (not officially released)

  • Fix a few problems on more exotic architectures (s390x, mips, ia64).
  • Allow passing byte.buffer when UTF8 string is requested.

0.5 (15-Apr-2012)

  • Port gtk3-demo to Lua code. Try running 'lua samples/gtk-demo/main.lua'
  • Finish override set for Gtk
  • Extend and document features for interfacing LGI with external libraries (exporting and importing objects and structures via lightuserdata pointers).
  • Fix: a few bugs with resolving bitflags values
  • Fix: a few bugs in coroutines-as-callbacks feature
  • Fix: workaround for crashing bug in gobject-introspection 1.32.0
  • Fix: don't try to squeeze GType into lua_Number any more; this could cause crashes on some 64bit arches.

0.4 (4-Jan-2012)

  • Changed handling of enums and bitflags, switched from marshaling them as numbers to prefering strings for enums and tables (sets or lists) for bitflags. Numeric values still work for Lua->C marshalling, but backward compatibility is broken in C->Lua enum and bitflags marshalling.
  • Compatible with Lua 5.2 and LuaJIT
  • Added standardized way for overrides to handle constructor argument table array part.
  • Existing Gtk overrides reworked and improved, there is now a way to describe and create widget hierarchies in Lua-friendly way. See docs/gtk.lua, chapter about Gtk.Container for overview and samples.
  • Various bugfixes and portability fixes.

0.3 (28-Nov-2011)

  • Project hosting moved to GitHub.
  • Build system switched from waf to simple Makefile-based one
  • Added automatic locking of thread-sensitive libraries (Gdk and Clutter). There is no need to add Gdk.threads_enter(), Gdk.threads_leave() and Clutter.threads_enter(), Clutter.threads_leave() pairs into application, lgi handles this automatically.
  • Added new sample samples/console.lua, which implements already quite usable Lua console using Gtk widgets.
  • Fixes for compatibility with older gobject-introspection 0.10.8 package
  • Testsuite is not built automatically, because building it can be apparently problematic on some systems, causing installation failure even when testsuite is not needed at all.
  • Remove setlocale() initialization, which could break Lua when used with some regional locales. The downside of this change is that marshaling file names containing non-ASCII characters on systems which define G_BROKEN_FILENAMES environment variable (probably only Fedora 15) does not work now.

0.2 (7-Nov-2011)

First public release

lgi's People

Contributors

aignas avatar craigbarnes avatar diazvictor avatar doronbehar avatar edwardbetts avatar fanc999-1 avatar fstirlitz avatar gregier avatar heirecka avatar jasperla avatar jonringer avatar leafo avatar miqueas avatar myaaaaaaaaa avatar nilnor avatar ntd avatar nuko8 avatar orthographic-pedant avatar ousia avatar palob avatar pavouk avatar phicross5 avatar psychon avatar reinerh avatar rolandlo avatar supertobi avatar szunti avatar terminar avatar tingping avatar v1993 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lgi's Issues

app:on_command_line() is broken

Attempting to use the app:on_command_line signal leads to a crash:

#!/usr/bin/env lua5.1
lgi = require('lgi')
local gtk = lgi.require('Gtk', '3.0')
local gio = lgi.require('Gio', '2.0')

local app = gtk.Application {
    flags = gio.ApplicationFlags.HANDLES_COMMAND_LINE,
}

function app:on_command_line(command) end

app:run { arg[0], ... } --method shown in the examples
--app:run(arg) --another method I thought might work

This script fails with:

lua5.1: /usr/share/lua/5.1/lgi/override/GObject-Value.lua:78: bad argument #3 to 'get' (number expected, got nil)
stack traceback:
    [C]: in function 'get'
    /usr/share/lua/5.1/lgi/override/GObject-Value.lua:78: in function 'marshaller'
    /usr/share/lua/5.1/lgi/override/GObject-Closure.lua:126: in function 'marshal_cell'
    /usr/share/lua/5.1/lgi/override/GObject-Closure.lua:162: in function </usr/share/lua/5.1/lgi/override/GObject-Closure.lua:144>
    [C]: in function 'run'
    ./gtk-test.lua:12: in main chunk
    [C]: ?

Segfault with "_access"

I don't know for sure in which situations the bug happens but, when I tried to enumerate properties on some objects I got a segfault (with lgi 0.7.0) with the following code

lgi = require "lgi"
Gtk = lgi.require "Gtk"
Gtk.Window().screen._class:list_properties()

Actually, after some investigations, I found out that the follwing code also causes a segfault Gtk.Window().screen._access.

embedded lua: subsequently calls after reinitialization issue warnings or segfaults

Here are the minimal example to illustrate a problem (tested on Debian Wheezy with lua-lgi 0.6 from Sid)

test_embed_lua.c

// gcc -Wall -g -o test_embed_lua test_embed_lua.c `pkg-config --cflags --libs lua5.1`

#include <stdio.h>

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

/* the Lua interpreter */
lua_State* L;

void call_lua()
{
        printf("opening lua...\n");
        L = lua_open();
        printf("...done\n");

        printf("opening libs...\n");
        luaL_openlibs(L);
        printf("...done\n");

        printf("opening file...\n");
        luaL_loadfile(L, "test.lua");
        printf("...done\n");

        printf("calling...\n");
        lua_pcall(L, 0, LUA_MULTRET, 0);
        printf("...done\n");

        printf("closing lua...\n");
        lua_close(L);
        printf("...done\n");
}

int main ( int argc, char *argv[] )
{
        printf("1\n");
        call_lua();
        printf("\n2\n");
        call_lua();
        printf("\n3\n");
        call_lua();
        return 0;
}

test.lua:

local lgi = require 'lgi' -- OK
--local core = require 'lgi.core' -- OK
--local GLib = core.repo.GLib -- OK
--local GLib = lgi.GLib -- OK
--local GObject = lgi.GObject -- OK

--local Gtk = lgi.require('Gtk', '3.0') -- fails at subsequent call
--local Gtk = lgi.Gtk -- fails at subsequent call
--local Gdk = lgi.Gdk -- fails at subsequent call
--local cairo = lgi.cairo -- fails at subsequent call
--local Pango = lgi.Pango -- fails at subsequent call
--local Clutter = lgi.Clutter -- fails at subsequent call
local Gio = lgi.Gio -- fails at subsequent call

print '---------- script end ----------'

This would issue warnings and must be terminated with ctrl-c:

$ ./test_embed_lua 
1
opening lua...
...done
opening libs...
...done
opening file...
...done
calling...
---------- script end ----------
...done
closing lua...
...done

2
opening lua...
...done
opening libs...
...done
opening file...
...done
calling...

(process:28806): GLib-GObject-WARNING **: cannot register existing type `GIRepository'

(process:28806): GLib-CRITICAL **: g_once_init_leave: assertion `result != 0' failed

(process:28806): GLib-GObject-CRITICAL **: g_object_new: assertion `G_TYPE_IS_OBJECT (object_type)' failed
^C
$

And it seems there are problems with debugger. It stucks on the 1st call:

$ gdb ./test_embed_lua 
GNU gdb (GDB) 7.4.1-debian
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from <cut>/test_embed_lua...done.
(gdb) r
Starting program: <cut>/test_embed_lua 
1
opening lua...
...done
opening libs...
...done
opening file...
...done
calling...
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Cannot find new threads: generic error
(gdb) bt
Target is executing.
(gdb) c
Continuing.
Cannot execute this command while the selected thread is running.
(gdb) 

Moreover, the subsequent call of minimal lua Gtk script ends with segfault.

window.child can't access menu items

Accessing a window's children by ID works fine, unless they're menu items:

#!/usr/bin/env lua5.1
lgi = require('lgi')
gtk = lgi.require('Gtk', '3.0')

local window = gtk.Window {
    title = "Test",
    type = gtk.WindowType.TOPLEVEL,
    on_destroy = function() os.exit(0) end,
    default_width = 200,
    default_height = 200,

    gtk.Box {
        orientation = 'VERTICAL',
        gtk.MenuBar {
            gtk.MenuItem {
                label = "Tests",
                submenu = gtk.Menu {
                    gtk.MenuItem {
                        label = "Test 1",
                        on_activate = function() print("test 1") end,
                    },
                    gtk.MenuItem {
                        label = "Test 2",
                        id = 'test_item',
                    },
                },
            },
        },
    },
}

assert(window.child.test_item == nil) --but it shouldn't be
window:show_all()
gtk.main()

Segmentation fault in c code during call gtk_main()

After calling lua code which used lgi:

local lgi = require 'lgi'
local Gtk = lgi.require('Gtk', '2.0')

function main(window)
    print "Call from lua"
    -- main = Gtk.Window(window)
end

via c++ we get Segmentation fault during calling gtk_main().

Example of C++ code:

GtkWidget *window;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
lua_getglobal(L, "main");
lua_pushlightuserdata (L, window);
lua_call(L, 1, 0);
gtk_widget_show (window);
gtk_main ();

Creating GLib.Bytes() from native pointer fails

For GObject based types I can just pass the native pointer to the constructor to wrap native pointer.

But that doesn't work for record based types like GBytes():

GLib = require("lgi").GLib
b = GLib.Bytes("foo")
b2 = GLib.Bytes(b._native)
.../lgi/record.lua:156: bad argument #2 to 'ctor' (table expected, got userdata)
stack traceback:
        [C]: in function 'ctor'
        .../lgi/record.lua:156: in function <.../lgi/record.lua:156>
        (tail call): ?
        stdin:3: in main chunk
        [C]: ?

Undefined conversion from double to enum

Hi,

While building your package using our research compiler infrastructure we noticed the following undefined conversion: in lgi/marshal.c, line 1409:

transfer = lua_tonumber (L, lua_upvalueindex (2));

"transfer" is an enum, but lua_tonumber returns a double. Although conversion to an enum even from an integer is a bit dubious, at least the use of lua_tointeger would be relatively well defined.

Best,
Michael

Segfault when inserting into a GTree

The following code causes a segfault in LGI 0.7.1 on Fedora 18:

local lgi = require "lgi"
local tree = lgi.GLib.Tree()
tree:insert("key", "val")

I'm not sure if this is a sane thing to do, since I was just playing around with the API with no particular purpose. Causing a segfault didn't seem right though, so I just thought I'd report it here.

Unpredictable behaviour when lgi is used on separate threads with separate Lua states

I've been using lgi in an application where I run Lua scripts with separate Lua state structs in separate threads and finding it works fine except when two or more scripts both use lgi. Here's a minimal example:

#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <stdbool.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

void* lua_init(void* script) {
    lua_State *L;
    L = luaL_newstate();
    luaL_openlibs(L);
    //register functions
    //run script
    printf("Loaded script %s\n", (char*)script);
    bool error = luaL_dofile(L, (char*)script);
    if (error) {
        fprintf(stderr, "SCRIPT ERROR: %s\n", lua_tostring(L, -1));
    }
    lua_close(L);
    return NULL;
}

int main(int argc, char *argv[]) {
    pthread_t lua_threads[argc-1];
    int i;
    for (i=1; i<argc; i++) {
        printf("%s\n", argv[i]);
        pthread_create(&(lua_threads[i-1]), NULL, &lua_init, (void*)argv[i]);
    }

    while (1);  return 0;
}

compiled it with gcc -o main main.c -llua5.1 -lpthread

and ran it with two randomly selected example lgi scripts

./main ../lgi/samples/gtkhello.lua ../lgi/samples/gtkhello.lua

which caused all sorts of errors which made it look like threading weirdness:

$ ./main ../lgi/samples/gtkhello.lua ../lgi/samples/gtkhello.lua 
../lgi/samples/gtkhello.lua
../lgi/samples/gtkhello.lua
Loaded script ../lgi/samples/gtkhello.lua
Loaded script ../lgi/samples/gtkhello.lua

(main:4287): Gtk-WARNING **: gtk_disable_setlocale() must be called before gtk_init()
Xlib: sequence lost (0x10091 > 0xc6) in reply type 0x1c!
[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
main: ../../src/xcb_io.c:273: poll_for_event: Assertion `!xcb_xlib_threads_sequence_lost' failed.
Aborted

and

$ ./main ../lgi/samples/gtkhello.lua ../lgi/samples/gtkhello.lua 
../lgi/samples/gtkhello.lua
../lgi/samples/gtkhello.lua
Loaded script ../lgi/samples/gtkhello.lua
Loaded script ../lgi/samples/gtkhello.lua
[xcb] Unknown request in queue while dequeuing
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
main: ../../src/xcb_io.c:178: dequeue_pending_request: Assertion `!xcb_xlib_unknown_req_in_deq' failed.
Aborted

but it changes pretty much every run.

glib timers give nonsensical results, segfaults

Trying to use glib.Timer() in lgi doesn't seem to work:

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> lgi = require('lgi')
> glib = lgi.GLib
> t = glib.Timer()
> return t:elapsed()
stdin:1: bad argument #2 to 'elapsed' (number expected, got nil)
stack traceback:
    [C]: in function 'elapsed'
    stdin:1: in main chunk
    [C]: ?
> return t:elapsed(0)
-644044850139.76

g_timer_elapsed() takes a gulong* to return microseconds in, though this is useless in practice (the documentation even notes this); that explains the need to pass in a number. Aside from the result being nonsense, the program segfaults shortly after calling this function.

GLib.io_add_watch() throws "bad argument to pairs" exception

Function lgi.GLib.io_add_watch() throws an error when used:

Lua 5.2.1  Copyright (C) 1994-2012 Lua.org, PUC-Rio
> lgi = require('lgi')
> chan = lgi.GLib.IOChannel.unix_new(0)
> lgi.GLib.io_add_watch(chan, lgi.GLib.IOCondition.IN, print)
/usr/local/share/lua/5.2/lgi/enum.lua:96: bad argument #1 to 'pairs' (table expected, got function)
stack traceback:
    [C]: in function 'pairs'
    /usr/local/share/lua/5.2/lgi/enum.lua:96: in function </usr/local/share/lua/5.2/lgi/enum.lua:89>
    (...tail calls...)
    [C]: in function 'io_add_watch'
    stdin:1: in main chunk
    [C]: in ?
> =lgi._VERSION
0.7.2

Instantiating foreign objects not working

While trying to convert my code to instantiate foreign classes passing a string class to GObject.Object.new rather than consuming pointers using core.object.new, I noticed that it doesn't work. From diving into the code, it seems that it will only work for classes with introspection info available (I end at lgi_type_get_repotype requiring g_irepository_find_by_gtype to return something, which it naturally won't).

Further information: I worked around that by using core.object.new passing the GType, but that ended just now with a SEGV in lgi_object_2c (0.7.2 release):

#0  0x00000000004c3266 in lgi_object_2c (L=L@entry=0x40089378, narg=narg@entry=2, gtype=29113248, optional=optional@entry=0, nothrow=nothrow@entry=0, 
    transfer=transfer@entry=0) at object.c:301
#1  0x00000000004c6f58 in callable_call (L=0x40089378) at callable.c:793
#2  0x0000000000447d4e in lj_BC_FUNCC ()
#3  0x000000000044a02b in gc_call_finalizer ()
#4  0x000000000044aa7c in lj_gc_finalize_cdata ()
#5  0x0000000000434919 in cpfinalize ()
#6  0x000000000044808f in lj_vm_cpcall ()
#7  0x0000000000434cbb in lua_close ()

Don't error() upon access of non-existent fields

One thing I've that annoyed me in the past, that bit me today as well, is that lgi raises errors upon reads for non-existent fields instead of returning nil. I find this annoying since it's (to me) very different from the standard Lua way of just returning nil. Is there a rationale for doing it this way?

My use case btw is a method that accepts either lgi objects or other objects that can be converted to lgi objects for a special conversion method. Whereas this would be a standard Lua conditional one-liner it now requires pcall.

[regression] Gtk-2

With Gtk-3.0.typelib everything is fine. But with Gtk-2.0.typelib I see this:

$ lua gtkhello.lua

(lua:19124): Gtk-WARNING **: gtk_disable_setlocale() must be called before gtk_init()
lua: /usr/share/lua5/lgi/override/Gtk.lua:576: attempt to call field 'get_major_version' (a nil value)
stack traceback:
/usr/share/lua5/lgi/override/Gtk.lua:576: in main chunk
[C]: in function 'require'
/usr/share/lua5/lgi/namespace.lua:174: in function </usr/share/lua5/lgi/namespace.lua:146>
(tail call): ?
gtkhello.lua:10: in main chunk
[C]: ?

Version info:
$ rpm -q gobject-introspection libgtk+2-gir
gobject-introspection-1.32.1-alt1
libgtk+2-gir-2.24.11-alt1

get_current_folder broken with recently used?

Hi,

I'm facing and issue with this situation:

---- FILE ---
local lgi = require 'lgi'
local Gtk = lgi.Gtk

local windowMain = Gtk.Window {
can_focus='true',
window_position='CENTER',
on_destroy=Gtk.main_quit,
}
content = Gtk.Box {
orientation = 'VERTICAL',
spacing = 5,
Gtk.Label {
label ="Get a file with recently used",
},
Gtk.FileChooserButton {
id='fileChooser',
title = "Chooser",
action = 'OPEN',
},
Gtk.Button{
id="newObject",
label="Print"
},
Gtk.Button{
id="quit",
label="Quit"
}
}

local filePath='/tmp'
local fileChooser=content.child.fileChooser
fileChooser:set_current_folder(filePath)

function content.child.quit:on_clicked()
windowMain:destroy()
end

function content.child.newObject:on_clicked()
print("Directory: "..fileChooser:get_current_folder())
end

windowMain:add(content)
windowMain:show_all()
Gtk.main()

---- FILE ---

Is it a bug or a feature? :)

Cheers and thanks for your job.

Ownership transfer issues with gstreamer

Running the included gstreamer sample ends up with errors similar to the following on my current Arch Linux system with gstreamer 0.10.36

(lua:5279): GStreamer-CRITICAL **: 
Trying to dispose object "file-source", but it still has a parent "audio-player".
You need to let the parent manage the object instead of unreffing the object directly.

I just started looking, but I think there is difficulty with that fact that gstreamer instance creation functions all claim they transfer full ownership. This is against the transfer none that would should be expected. This prevents the ref_sink special handling implementation in lgi from ever working.

Although I have not tested it from gstreamer source, I notice they have changed the annotations in git master to (transfer floating).

Wonder if there is a simple interim workaround from 0.10 gstreamer though.

Example code using buffer is incorrect

The examples using a buffer provide the array length as a paramter to the introspected function. This causes an error since the array size parameter is not exposed to the lua code.

Example from samples/giostream.lua:

stream:read_all(buffer, #buffer)

should be

stream:read_all(buffer)

Gtk.Builder lacks connecting signals support

Would be great if Gtk.Builder connects the signals to functions as specified in XML (.glade) file.
Take in mind that tag also accepts "object", "swapped", and "after" attributes.

result of tonumber depends on the locale

The Lua functions tonumber and tostring use a dot as decimal separator. With lgi, it depends on the locale.

My locale is pt_br, the decimal separator is comma, so I get some unespected results. For example, running

print(tonumber("3.2"))  --> 3.2
print(tonumber("3,2"))  --> nil

local lgi = require 'lgi'
print(tonumber("3.2"))  --> 3.2
print(tonumber("3,2"))  --> nil

local Gtk = lgi.Gtk
print(tonumber("3.2"))  --> nil
print(tonumber("3,2"))  --> 3,2

results in
3.2
nil
3.2
nil
nil
3,2

Note that the result changes only after "local Gtk = lgi.Gtk".

Performance issues when looking up members of Lgi objects

I'm using Lgi for creating animated graphs using cairo, and I've run into some performance issues. My app calls cairo's move_to() and line_to() functions quite a lot of times, which takes much longer then I expected.

Some investigation showed a lot of time is spent by Lgi looking up methods from objects. For example, one thousand calls of

cr:line_to(x, y)

takes about 20 msec on my PC. The time is not consumed by the function call into cairo, because one thousand times looking up the function without calling it:

local l =cr.line_to

takes only slightly longer.

My current workaround is to cache the functions in local variables and call those:

local l = cr.line_to
for thousands of times do
l(cr, x, y)
end

resulting in a speedup of over 20 times.

Would it be feasible to add some form of caching or memoization to the Lgi objects themselves, so that the user does not need to do this caching at application level? I've looked into the Lgi code, but since I am not at all familiar with the gobject introspection stuff, grokking the code will probably take me some time.

If adding memozation is not an option it might be a good idea to make a note of this performance penalty in the documentation to inform future Lgi users?

Thanks,

Ico

Arrays in structs are incorrecly GCed

Lua: v5.2.2
Lgi: commit a01a702

I restarted to play with DBus interfaces and I found out that arrays inside structs seems to be freed while they shouldn't:

local lgi = require "lgi"
local Gio = lgi.require "Gio"

local method = Gio.DBusMethodInfo()
local iface = Gio.DBusInterfaceInfo()
iface.methods = { method }

collectgarbage()

print(iface.methods)

This will most likely run fine but with Valgrind, we see the following

valgrind lua crash.lua
==12234== Memcheck, a memory error detector
==12234== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==12234== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info
==12234== Command: lua crash.lua
==12234== 
==12234== Invalid read of size 8
==12234==    at 0x5F9FA3A: marshal_2lua_array (marshal.c:432)
==12234==    by 0x5FA14E3: lgi_marshal_2lua (marshal.c:1251)
==12234==    by 0x5FA1AB2: lgi_marshal_field (marshal.c:1407)
==12234==    by 0x5FA523A: record_field (record.c:591)
==12234==    by 0x4086D4: ??? (in /usr/bin/lua)
==12234==    by 0x4124DE: ??? (in /usr/bin/lua)
==12234==    by 0x4089A8: ??? (in /usr/bin/lua)
==12234==    by 0x406657: lua_callk (in /usr/bin/lua)
==12234==    by 0x5FA1BAA: lgi_marshal_access (marshal.c:1432)
==12234==    by 0x5FA4E66: record_access (record.c:458)
==12234==    by 0x4086D4: ??? (in /usr/bin/lua)
==12234==    by 0x408973: ??? (in /usr/bin/lua)
==12234==  Address 0x5d840d0 is 0 bytes inside a block of size 16 free'd
==12234==    at 0x4C289DC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12234==    by 0x684F8C0: array_free (garray.c:370)
==12234==    by 0x5F9ABF4: guard_gc (core.c:236)
==12234==    by 0x4086D4: ??? (in /usr/bin/lua)
==12234==    by 0x40899C: ??? (in /usr/bin/lua)
==12234==    by 0x407FFB: ??? (in /usr/bin/lua)
==12234==    by 0x408BE0: ??? (in /usr/bin/lua)
==12234==    by 0x409CE8: ??? (in /usr/bin/lua)
==12234==    by 0x409D6E: ??? (in /usr/bin/lua)
==12234==    by 0x40693E: lua_gc (in /usr/bin/lua)
==12234==    by 0x419115: ??? (in /usr/bin/lua)
==12234==    by 0x4086D4: ??? (in /usr/bin/lua)
==12234== 
==12234== Invalid read of size 8
==12234==    at 0x5FA134B: lgi_marshal_2lua (marshal.c:1205)
==12234==    by 0x5F9FA91: marshal_2lua_array (marshal.c:436)
==12234==    by 0x5FA14E3: lgi_marshal_2lua (marshal.c:1251)
==12234==    by 0x5FA1AB2: lgi_marshal_field (marshal.c:1407)
==12234==    by 0x5FA523A: record_field (record.c:591)
==12234==    by 0x4086D4: ??? (in /usr/bin/lua)
==12234==    by 0x4124DE: ??? (in /usr/bin/lua)
==12234==    by 0x4089A8: ??? (in /usr/bin/lua)
==12234==    by 0x406657: lua_callk (in /usr/bin/lua)
==12234==    by 0x5FA1BAA: lgi_marshal_access (marshal.c:1432)
==12234==    by 0x5FA4E66: record_access (record.c:458)
==12234==    by 0x4086D4: ??? (in /usr/bin/lua)
==12234==  Address 0x5d840d0 is 0 bytes inside a block of size 16 free'd
==12234==    at 0x4C289DC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12234==    by 0x684F8C0: array_free (garray.c:370)
==12234==    by 0x5F9ABF4: guard_gc (core.c:236)
==12234==    by 0x4086D4: ??? (in /usr/bin/lua)
==12234==    by 0x40899C: ??? (in /usr/bin/lua)
==12234==    by 0x407FFB: ??? (in /usr/bin/lua)
==12234==    by 0x408BE0: ??? (in /usr/bin/lua)
==12234==    by 0x409CE8: ??? (in /usr/bin/lua)
==12234==    by 0x409D6E: ??? (in /usr/bin/lua)
==12234==    by 0x40693E: lua_gc (in /usr/bin/lua)
==12234==    by 0x419115: ??? (in /usr/bin/lua)
==12234==    by 0x4086D4: ??? (in /usr/bin/lua)
==12234== 
table: 0x5d85160
==12234== 
==12234== HEAP SUMMARY:
==12234==     in use at exit: 66,275 bytes in 403 blocks
==12234==   total heap usage: 9,793 allocs, 9,390 frees, 1,398,932 bytes allocated
==12234== 
==12234== LEAK SUMMARY:
==12234==    definitely lost: 0 bytes in 0 blocks
==12234==    indirectly lost: 0 bytes in 0 blocks
==12234==      possibly lost: 4,860 bytes in 85 blocks
==12234==    still reachable: 61,327 bytes in 317 blocks
==12234==         suppressed: 0 bytes in 0 blocks
==12234== Rerun with --leak-check=full to see details of leaked memory
==12234== 
==12234== For counts of detected and suppressed errors, rerun with: -v
==12234== ERROR SUMMARY: 3 errors from 2 contexts (suppressed: 2 from 2)

Which seems to indicate that array object (and not DBusMethodInfo itself) has been freed.

So far I didn't found a workaround to anchor a guard to the Lua state (like with callbacks). Is it possible ?

Cairo support

Cairo support seems to be present only in name in lgi. For example if I create a Gtk.DrawingArea, in its on_draw method, I have a Cairo context, but it seems to have no methods. e.g. cr:set_source_surface() fails, saying "cairo.Context: no `set_source_surface'", which suggests that lgi knows what a Cairo context is, but nothing about how to use it.

Since GDK drawing operations are now deprecated in favour of Cairo, this seems like a potential problem for any app that needs to draw things.

[]-read-access against GBytes.get_data() reads invalid data

local lgi = assert(require("lgi"))
GLib = lgi.GLib
print(lgi._VERSION)

for _, b in ipairs(GLib.Bytes("foobar"):get_data()) do 
  print(string.char(b))
end

prints out:

0.7.1
f
P

A

�

valgrind complains about:

==26199== Invalid read of size 1
==26199==    at 0x5F7E952: marshal_2lua_int (marshal.c:121)
==26199==    by 0x5F811AE: lgi_marshal_2lua (marshal.c:1255)
==26199==    by 0x5F7F74A: marshal_2lua_array (marshal.c:432)
==26199==    by 0x5F81132: lgi_marshal_2lua (marshal.c:1236)
==26199==    by 0x5F785C3: callable_param_2lua (callable.c:724)
==26199==    by 0x5F78DB8: callable_call (callable.c:892)
==26199==    by 0x408163: ??? (in /usr/bin/lua5.1)
==26199==    by 0x411557: ??? (in /usr/bin/lua5.1)
==26199==    by 0x4085BC: ??? (in /usr/bin/lua5.1)
==26199==    by 0x407809: ??? (in /usr/bin/lua5.1)
==26199==    by 0x40874E: ??? (in /usr/bin/lua5.1)
==26199==    by 0x405E0E: lua_pcall (in /usr/bin/lua5.1)
==26199==  Address 0x5c6f3b8 is 2 bytes after a block of size 6 alloc'd
==26199==    at 0x4C2CD7B: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==26199==    by 0x685DCF0: g_malloc (gmem.c:159)
==26199==    by 0x6874785: g_memdup (gstrfuncs.c:392)
==26199==    by 0x68343E8: g_bytes_new (gbytes.c:96)
==26199==    by 0x6B10C17: ffi_call_unix64 (in /usr/lib/x86_64-linux-gnu/libffi.so.6.0.1)
==26199==    by 0x6B1057F: ffi_call (in /usr/lib/x86_64-linux-gnu/libffi.so.6.0.1)
==26199==    by 0x5F78D17: callable_call (callable.c:876)
==26199==    by 0x408163: ??? (in /usr/bin/lua5.1)
==26199==    by 0x411452: ??? (in /usr/bin/lua5.1)
==26199==    by 0x4085BC: ??? (in /usr/bin/lua5.1)
==26199==    by 0x407809: ??? (in /usr/bin/lua5.1)
==26199==    by 0x40874E: ??? (in /usr/bin/lua5.1)
==26199== 

Useless warning with static linking

When lgi is linked statically, with LuaJIT, this warning in set_resident will always fire:

g_warning ("failed to self-resident corelgilua5, not found in registry");

Which is rather annoying, since it's not indicative of any real problem given the static linking. It would be nice if this could either be removed, or less preferably ifdef'ed with something that allows ignoring it or logged at the debug level.

GLib.unichar_to_utf8 unicode_char not handled correctly

It seems that GLib.unichar_to_utf8 unicode_char isn't wrapped correctly for some reason.

The C definition is as follows:

gint  g_unichar_to_utf8  (gunichar c, gchar *outbuf);

Where the outbuf must be allocated by the caller (see http://developer.gnome.org/glib/unstable/glib-Unicode-Manipulation.html#g-unichar-to-utf8 for full info). Lgi doesn't detect this, and requires the outbuf argument to be a string where it seems a bytes buffer would be appropriate.

I don't know whether this is an issue with the Gir or typelib info. I checked the Gir file which contains the following:

        <parameter name="outbuf" transfer-ownership="none">
          <doc xml:whitespace="preserve">output buffer, must have at least 6 bytes of space. If %NULL, the length
 will be computed and returned and nothing will be written to @outbuf.</doc>
          <type name="utf8" c:type="gchar*"/>
        </parameter>

Which doesn't mention anything regarding it being an out parameter etc, but perhaps the typelib information says differently.

cairo cant call text_extents method

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

local cr = cairo.Context.create()

cr:text_extents("test")

Lua execute the code, it says "segmentation fault (core dumped)"

GEGL Support

GEGL support would be nice. Is GEGL support something you plan on adding? Once I wrap my head around gobject-introspection I'll try to tackle it myself.

issue about signals

I use Lua as extensions for my program. I noticed a problem: the signal is outside the built-in main loop. This causes my program freezes if a signal is received. I wanted to give an interface for extensions to connect signal inside the program, but LUA can't do that because I can't get the pointer of a function in Lua. Is there any workaround?

Error when getting child widgets

I was having an error when writing a GUI using GTK+ with lgi. Here is a program that demonstrates it:

local lgi = require 'lgi'

local win = lgi.Gtk.Window {
    title = 'lgi paned test',
    lgi.Gtk.Paned {
        id = 'paned',
        orientation = 'VERTICAL',
        lgi.Gtk.Button {
            id = 'btn1',
            label = 'One',
        },
        lgi.Gtk.Button {
            id = 'btn2',
            label = 'Two',
        },
    },
}

local btn1 = win.child.btn1 -- works fine
btn1:set_label('Test')

---------------------------------------

local win2 = lgi.Gtk.Window {
    title = 'lgi paned test',
    lgi.Gtk.Box {
        orientation = 'VERTICAL',
        lgi.Gtk.Paned {
            id = 'paned',
            orientation = 'VERTICAL',
            lgi.Gtk.Button {
                id = 'btn1',
                label = 'One',
            },
            lgi.Gtk.Button {
                id = 'btn2',
                label = 'Two',
            },
        },
    },
}

local btn1 = win.child.paned.btn1 -- error "Gtk.Paned: no `btn1'"
btn1:set_label('Test')

---------------------------------------

win:show_all()
win2:show_all()

lgi.Gtk.main()

For some reason getting the paned widget's child fails if it's in a Box. Is this a bug in lgi?

GdkScreen::get_rgb[a]_colormap segfault

Seems like calling gdk_screen_get_rgb_colormap or gdk_screen_get_rgba_colormap causes a segfault.

#!/usr/bin/env lua5.1
lgi = require('lgi')
gtk = lgi.require('Gtk', '3.0')
gdk = lgi.require('Gdk', '3.0')
cairo = lgi.cairo
webkit = lgi.require('WebKit', '3.0')


local webview = webkit.WebView.new()
local window = gtk.Window {
    title = "Webkit Transparency Test",
    type = gtk.WindowType.TOPLEVEL,
    type_hint = gdk.WindowTypeHint.NORMAL,
    width = 400, height = 400,
    decorated = true, resizable = true,
    gtk.Box {
        orientation = 'VERTICAL',
        webview,
        gtk.Label { label="This label IS transparent" },
    },
    on_destroy = function() os.exit(0) end,
}


local screen_supports_alpha = false
window:set_app_paintable(true)
window.on_draw = function(widget, cr, event)
    if screen_supports_alpha then cr:set_source_rgba(0, 0, 0, 0.5)
    else cr:set_source_rgb(0, 0, 0)
    end
    cr.operator = cairo.Operator.SOURCE
    cr:paint()
    return false
end

local function check_screen_supports_alpha()
    local screen = window:get_screen()
    local visual = screen:get_rgba_visual()
    print("get colormap", screen)
    local colormap = screen:get_rgba_colormap()  -- segfault here
    print("colormap is", colormap)
    if visual then
        screen_supports_alpha = true
        print("Alpha supported on this screen")
        webview:set_transparent(true)
    else
        screen_supports_alpha = false
        print("Alpha not supported on this screen")
        visual = screen:get_default_visual()
        colormap = screen:get_rgb_colormap()
    end
    window:set_visual(visual)
    window:set_colormap(colormap)
end

window.on_screen_changed = function(widget, old_screen)
    check_screen_supports_alpha()
end
check_screen_supports_alpha()


webview:load_string([[
    <html>
        <head>
            <title>Transparency Test</title>
            <style type="text/css">
                body, html {
                    background: rgba(0, 0, 0, 0);
                    color: #FFF;
                    text-shadow: 1px 1px 1px #000;
                    min-height: 200px;
                }
            </style>
            <script>alert(navigator.userAgent)</script>
        </head>
        <body>
            This window should be transparent!
        </body>
    </html>
]], "text/html", "UTF-8", "file://" .. os.getenv("PWD"))


window:show_all()
gtk.main()

Memory leak if if same cairo surface is "imported" as lightuserdata more than once

Hi,

The following code has a memory leak if run() is called with anything but 1 as argument. I know that re-loading lgi after lua_close() can cause problems, but the leak also occurs if the first run is removed.

Is this by design and I am doing something wrong or is this a genuine memory leak?

Thanks for looking at this,
Uli

#include <cairo.h>
#include <stdio.h>
#include <lauxlib.h>
#include <lualib.h>

static const cairo_user_data_key_t key;
static cairo_surface_t *surface;
static const char lua_code[] =
"require('lgi').cairo.Surface(surface(), true);"
;

static int surface_callback(lua_State *L)
{
    lua_pushlightuserdata(L, cairo_surface_reference(surface));
    return 1;
}

static void run(unsigned int i)
{
    lua_State *L;

    /* Create a cairo surface that prints a message when it gets destroyed */
    surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 10, 10);
    cairo_surface_set_user_data(surface, &key, "Cairo surface destroyed", (cairo_destroy_func_t) puts);

    /* Prepare the lua state, surface() should call surface_callback() */
    L = luaL_newstate();
    luaL_openlibs(L);

    lua_pushcfunction(L, surface_callback);
    lua_setglobal(L, "surface");

    /* Run the code */
    while (i--)
        if (luaL_dostring(L, lua_code) != 0)
            puts("Error while running code");

    /* Clean up */
    lua_close(L);
    printf("After lua_close, surface still has %d references\n",
            cairo_surface_get_reference_count(surface));
    cairo_surface_destroy(surface);
}

int main()
{
    puts("Running with one iteration:");
    run(1);

    puts("\nRunning with two iterations:");
    run(2);

    return 0;
}

Error in gtkbuilder sample: AtkAction not implemented

$ lua gtkbuilder.lua
lgi-Message: gobject-introspection binding for Lua, 0.4

(lua:865): Gtk-WARNING **: accessibility action on a widget that does not implement AtkAction
lua: gtkbuilder.lua:35: attempt to index a boolean value
stack traceback:
gtkbuilder.lua:35: in main chunk
[C]: ?

OS: Archlinux
gobject-introspection 1.30.0-1
lua 5.1.4,
gtk 3.2.3
lgi: master@github

Signal callbacks prevents GC

I bumped into the problem that setting callbacks for an lgi object appears to prevent any references from within the callback to be garbage collected.

My use case is this:

I have an object o containing a lgi object. For the lgi object I provide a signal handler; a closure that references said object o. This unfortunately seems to prevent any garbage collection of o. This is a problem since o and its siblings are dynamically created objects that could be created in any number during the applications lifetime, and that also have other resource cleanup tasks associated with GC. Any thoughts regarding this?

Below you'll find a self contained stripped down example of the problem:

local lgi = require('lgi')

local function gen()
  -- local a = { ref = {} } -- this works fine
  local a = { ref = lgi.Gtk.Entry() } -- but lgi objects does not
  a.callback = function() return a end
  a.ref.on_focus_in_event = a.callback
  return a
end

local cache = setmetatable({}, {__mode = 'v'})
cache[1] = gen()
collectgarbage()
assert(cache[1] == nil, "reference was not collected")

Segfault with 0.7.0

Hello,

Trying to push the new version of lgi into archlinux, I got segfault running awesome with the last version 0.7.0.

su -l bobby -c /usr/bin/startx

This is a pre-release version of the X server from The X.Org Foundation.
It is not supported in any way.
Bugs may be filed in the bugzilla at http://bugs.freedesktop.org/.
Select the "xorg" product for bugs you find in this release.
Before reporting bugs in pre-release versions please check the
latest version in the X.Org Foundation git repository.
See http://wiki.x.org/wiki/GitPage for git access instructions.

X.Org X Server 1.13.2.901 (1.13.3 RC 1)
Release Date: 2013-02-15
X Protocol Version 11, Revision 0
Build Operating System: Linux 3.7.5-1-ARCH x86_64
Current Operating System: Linux sheldon 3.8.1-1-ARCH #1 SMP PREEMPT Thu Feb 28 18:23:03 CET 2013 x86_64
Kernel command line: root=UUID=066ba3bf-1e99-47ff-ab0c-befcc0d5c27b rootfstype=btrfs ro initrd=\initramfs-linux.img
Build Date: 18 February 2013 03:52:56PM

Current version of pixman: 0.28.2
Before reporting problems, check http://wiki.x.org
to make sure that you have the latest version.
Markers: (--) probed, (**) from config file, (==) default setting,
(++) from command line, (!!) notice, (II) informational,
(WW) warning, (EE) error, (NI) not implemented, (??) unknown.
(==) Log file: "/var/log/Xorg.0.log", Time: Sun Mar 3 03:07:55 2013
(==) Using config directory: "/etc/X11/xorg.conf.d"
Initializing built-in extension Generic Event Extension
Initializing built-in extension SHAPE
Initializing built-in extension MIT-SHM
Initializing built-in extension XInputExtension
Initializing built-in extension XTEST
Initializing built-in extension BIG-REQUESTS
Initializing built-in extension SYNC
Initializing built-in extension XKEYBOARD
Initializing built-in extension XC-MISC
Initializing built-in extension SECURITY
Initializing built-in extension XINERAMA
Initializing built-in extension XFIXES
Initializing built-in extension RENDER
Initializing built-in extension RANDR
Initializing built-in extension COMPOSITE
Initializing built-in extension DAMAGE
Initializing built-in extension MIT-SCREEN-SAVER
Initializing built-in extension DOUBLE-BUFFER
Initializing built-in extension RECORD
Initializing built-in extension DPMS
Initializing built-in extension X-Resource
Initializing built-in extension XVideo
Initializing built-in extension XVideo-MotionCompensation
Initializing built-in extension XFree86-VidModeExtension
Initializing built-in extension XFree86-DGA
Initializing built-in extension XFree86-DRI
Initializing built-in extension DRI2
Loading extension GLX
Loading: 01-functions-vars.lua
Loading: 05-theme.lua
Loading: 10-layout.lua
Loading: 12-timers.lua
Loading: 15-widgets.lua
E: awesome: signal_fatal:231: signal 11, dumping backtrace
awesome(backtrace_get+0x41) [0x422551]
awesome() [0x40d1d2]
/usr/lib/libc.so.6(+0x35340) [0x7f9bbb6e5340]
/usr/lib/lua/5.2/lgi/corelgilua51.so(lgi_record_2c+0xfc) [0x7f9bb5861b3c]
/usr/lib/lua/5.2/lgi/corelgilua51.so(lgi_marshal_2c+0x56e) [0x7f9bb585d90e]
/usr/lib/lua/5.2/lgi/corelgilua51.so(+0x9db1) [0x7f9bb5858db1]
/usr/lib/liblua.so.5.2(+0xd11a) [0x7f9bbbcb011a]
/usr/lib/liblua.so.5.2(+0x18677) [0x7f9bbbcbb677]
/usr/lib/liblua.so.5.2(+0xd369) [0x7f9bbbcb0369]
/usr/lib/liblua.so.5.2(lua_callk+0x31) [0x7f9bbbcac511]
/usr/lib/lua/5.2/lgi/corelgilua51.so(lgi_marshal_access+0x82) [0x7f9bb585f9d2]
/usr/lib/liblua.so.5.2(+0xd11a) [0x7f9bbbcb011a]
/usr/lib/liblua.so.5.2(+0xd308) [0x7f9bbbcb0308]
/usr/lib/liblua.so.5.2(+0x17356) [0x7f9bbbcba356]
/usr/lib/liblua.so.5.2(+0x17840) [0x7f9bbbcba840]
/usr/lib/liblua.so.5.2(+0x18ecf) [0x7f9bbbcbbecf]
/usr/lib/liblua.so.5.2(+0xd369) [0x7f9bbbcb0369]
/usr/lib/liblua.so.5.2(lua_callk+0x31) [0x7f9bbbcac511]
/usr/lib/liblua.so.5.2(+0x1c688) [0x7f9bbbcbf688]
/usr/lib/liblua.so.5.2(+0xd11a) [0x7f9bbbcb011a]
/usr/lib/liblua.so.5.2(+0x18624) [0x7f9bbbcbb624]
/usr/lib/liblua.so.5.2(+0xd369) [0x7f9bbbcb0369]
/usr/lib/liblua.so.5.2(+0xc9ab) [0x7f9bbbcaf9ab]
/usr/lib/liblua.so.5.2(+0xd595) [0x7f9bbbcb0595]
/usr/lib/liblua.so.5.2(lua_pcallk+0x7f) [0x7f9bbbcac5df]
awesome() [0x4192be]
awesome(luaA_parserc+0x60) [0x41a9df]
awesome(main+0x80f) [0x40dac9]
/usr/lib/libc.so.6(__libc_start_main+0xf5) [0x7f9bbb6d1a15]
awesome() [0x40cde9]
xinit: connection to X server lost

waiting for X server to shut down Server terminated successfully (0). Closing log file.

LuaRocks Build Fail

I've pastebin'd the console output. Maybe you could shed some light on the situation. I'm following instructions from the GNOME website, and I've hit a snag on the very first step!
luarocks install lgi comes back with 'build failed"

Please help if you can, I'd really appreciate it.

Access to individual glyphs in Pango.GlyphString

I'm using the following code to shape a string:

local pango = lgi.Pango
local pal = pango.AttrList.new();
pal:insert(pango.Attribute.language_new(pango.Language.from_string("he")))
pal:insert(pango.Attribute.family_new("Adobe Hebrew"))
pal:insert(pango.Attribute.size_new(12))

local fm = lgi.PangoCairo.FontMap.get_default()
local pango_context = lgi.Pango.FontMap.create_context(fm)
pango_context:set_language(pango.Language.from_string("he"))
local s = "ltr שָׁוְא ltr"

items = pango.itemize(pango_context, s, 0, string.len(s), pal, nil)

for i in pairs(items) do
    local offset = items[i].offset
    local length = items[i].length
    local analysis = items[i].analysis
    local pgs = pango.GlyphString()
    pango.shape(string.sub(s,1+offset), length, analysis, pgs)
    -- Pull out individual glyphs with pgs.glyphs
end

Unfortunately whereas I'd expect pgs.glyphs to return an array, it's returning a single Pango.GlyphInfo. I think this is because PangoGlyphInfo is defined as

struct PangoGlyphString {
  gint num_glyphs;
  PangoGlyphInfo *glyphs;
  gint *log_clusters;
};

And the PangoGlyphInfo * is being interpreted as a pointer instead of as an array.

I am quite new to lua so my expectations could be out of whack, but how do I access glyphs other than the first?

[FR] update UIManager sample

samples/gtk-demo/demo-uimanager.lua currently needs improvements.

  1. It doesn't use demo.ui file which is misleading.
  2. the demo should demonstrate a code + ui-file which is usual in Gtk world.

I know that you prefer Lua-style UI description. So I'll work on this, but no hurry.

Inconsistent naming in GUserDirectory

The GUserDirectory enum has inconsistent naming values:

lgi = require 'lgi'; GLib = lgi.require 'GLib'
for k in pairs(GLib.UserDirectory) do print(k) end
_name
DIRECTORY_TEMPLATES
DIRECTORY_PICTURES
DIRECTORY_DOWNLOAD
N_DIRECTORIES
DIRECTORY_MUSIC
DIRECTORY_DESKTOP
DIRECTORY_DOCUMENTS
DIRECTORY_VIDEOS
DIRECTORY_PUBLIC_SHARE

This is because of the last value defined by GLib (G_USER_N_DIRECTORIES). Not a big deal but... a patch that strips DIRECTORY_ would be be accepted?

Crash when accessing 'window.child' with gtk2

lgi seems to fail if you try to access window.child when using Gtk 2.0.

Here's the simplest program:

local lgi = require 'lgi'
local Gtk = lgi.require('Gtk', '2.0')
local window = Gtk.Window {
    title = 'Application',
    default_width = 128,
    default_height = 64,
    on_destroy = Gtk.main_quit,
    Gtk.Toolbar {
        Gtk.ToolButton { id = 'quit', stock_id = Gtk.STOCK_QUIT }
    }
}

-- just using 'local q = window.child' instead of the below
-- is enough to see the problem

function window.child.quit:on_clicked()
    window:destroy()
end

window:show_all()
Gtk.main()

Running it under FreeBSD/amd64 with the latest lgi (commit dcf318b), gtk 2.24 and lua 5.1 gives me this:

$ lus-5.1 example.lua
Bus error

Running the same program, but with 3.0 instead of 2.0 works fine (with gtk 3.6).

(I see the same behavior under a Linux-based system, so the problem is not FreeBSD-specific).

Not sure if it'll help you to diagnose the problem (it doesn't help me), but here's the backtrace I get after the crash (lgi is build with debug symbols, lua without):

(gdb) run example.lua
Starting program: /usr/local/bin/lua-5.1 example.lua
(no debugging symbols found)...(no debugging symbols found)...(no debugging symbols found)...(no debugging symbols found)...(no debugging symbols found)...[New LWP 100177]
[New Thread 8014ff400 (LWP 100177/lua)]

Program received signal SIGBUS, Bus error.
[Switching to Thread 8014ff400 (LWP 100177/lua)]
0x0000000801813eaa in lgi_object_2lua (L=0x801407300, obj=0x8078dba40, own=0, no_sink=0) at object.c:344
(gdb) bt
#0  0x0000000801813eaa in lgi_object_2lua (L=0x801407300, obj=0x8078dba40, own=0, no_sink=0) at object.c:344
#1  0x00000008018120c8 in lgi_marshal_2lua (L=0x801407300, ti=0x8078fd770, ai=0x0, dir=GI_DIRECTION_OUT, transfer=GI_TRANSFER_NOTHING, source=0x801519370, parent=1, ci=0x0, args=0x0) at marshal.c:1200
#2  0x000000080181275d in lgi_marshal_field (L=0x801407300, object=0x801519370, getmode=1, parent_arg=1, field_arg=2, val_arg=3) at marshal.c:1390
#3  0x0000000801814069 in object_field (L=0x801407300) at object.c:424
#4  0x0000000000408012 in lua_resume ()
#5  0x0000000000410cf4 in lua_newstate ()
#6  0x000000000040849e in lua_resume ()
#7  0x00000000004056fd in lua_call ()
#8  0x000000080181283d in lgi_marshal_access (L=0x801407300, getmode=1, compound_arg=1, element_arg=2, val_arg=3) at marshal.c:1415
#9  0x0000000801813f8e in object_access (L=0x801407300) at object.c:376
#10 0x0000000000408012 in lua_resume ()
#11 0x000000000040844d in lua_resume ()
#12 0x000000000040f35b in lua_newstate ()
#13 0x00000000004107c0 in lua_newstate ()
#14 0x000000000040849e in lua_resume ()
#15 0x0000000000407bb7 in lua_yield ()
#16 0x0000000000407c35 in lua_yield ()
#17 0x0000000000405555 in lua_pcall ()
#18 0x0000000000403e1a in main ()

Test suite: hard-coded libdir

tests/Makefile has these library paths hardcoded

--library-path=/usr/lib
--library-path=/usr/X11R6/lib
--library-path=/usr/local/lib 

for the Regress-1.0.gir target. On a 64bit Fedora system though the correct path would be /usr/lib64. It would be nice to be able to pass the correct libdir to the Makefile.

Memory leak with Pango's parse_markup and PangoLayout

Hi,

This is a forward of a bug which was forwarded to me:

System used is debian testing.

The following lua code has growing memory usage. According to massif, there is memory allocated in pango_parse_markup() which never gets freed.

Test case:

local lgi = require("lgi")
local cairo = lgi.cairo
local Pango = lgi.Pango
local PangoCairo = lgi.PangoCairo

local ctx = PangoCairo.font_map_get_default():create_context()
local layout = Pango.Layout.new(ctx)

local width, height = 200, 200
local surf = cairo.ImageSurface('ARGB32', width, height)
local cr = cairo.Context(surf)

while true do
    local attr, parsed = Pango.parse_markup("Test<u>ing<b>some</b>thing</u>", -1, 0)
    layout.text = parsed
    layout.attributes = attr

    cr:update_layout(layout)
    layout.width = Pango.units_from_double(width)
    layout.height = Pango.units_from_double(height)

    local ink, logical = layout:get_pixel_extents()
    local offset = (height - logical.height) / 2
    cr:move_to(0, offset)
    cr:show_layout(layout)

    -- Give the garbage collector a kick
    collectgarbage("collect")
end

Cheers,
Uli

No get_xid() in GdkWindow?

I am trying to port a simple video player to lgi, but don't know how to get XID of the X11 Window. I understand from GTK docs that Gtk.DrawingArea():get_window():get_xid() should return that, but it's not there. So how do I get window's XID?

Overriding metamethods for classes

Hi.

I'm monkey-patching LGI a bit (especially gio.File). It was easy to add new method (jus function gio.File:new_method() ... end), but I still can't figure out how to add metamethod like __string or __add, etc...?

Any clues?

Thanks.

Support outer CFLAGS and LDFLAGS

Trying to package lgi for Fedora, and packaging guidelines require that CFLAGS and LDFLAGS are set, to ensure some compile and link flags are set.

As far as I can see, the current makefiles do not allow passing these in in a clean way.

GtkTreeSelection::get_iter() segfault

Using get_iter() method of GtkTreeSelection() causes segfaults:

#!/usr/bin/env lua5.1
lgi = require('lgi')
gtk = lgi.require('Gtk', '3.0')
gdk = lgi.require('Gdk', '3.0')
cairo = lgi.cairo
gobject = lgi.GObject


local list_model = gtk.ListStore.new { --why .new here? >.>
    gobject.Type.STRING, --name
    gobject.Type.STRING, --path
}

local list = gtk.TreeView { id='list', model=list_model }
local treecol = gtk.TreeViewColumn { title = "List", {
    gtk.CellRendererText {}, { text = 1 },
}}
list:append_column(treecol)


local selection = list:get_selection()
function selection:on_changed()
    print("on_changed")
    local rows = selection:get_selected_rows()

    print("index rows")
    local treepath = rows[1]

    print("get_iter")
    local iter = list_model:get_iter(treepath)

    print("get_value")
    local item = list_model:get_value(iter, 2)

    print("selected:", item)
end


list_model:clear()
for i = 1, 50 do
    list_model:append {"Item " .. i, "Item path " .. i}
end


local window = gtk.Window {
    title = "ListView Test",
    type = gtk.WindowType.TOPLEVEL,
    type_hint = gdk.WindowTypeHint.NORMAL,
    width = 400, height = 400,
    decorated = true, resizable = true,
    gtk.ScrolledWindow { list },
    on_destroy = function() os.exit(0) end,
}


window:show_all()
gtk.main()

The output is:

on_changed
index rows
get_iter
Segmentation fault (core dumped)

The same happens if you connect the signal after the window is shown (e.g. when clicking a button) and then selecting an item in the list.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.