Skip to content

Commit a48f488

Browse files
committed
docs(linux): GObjects as objects, their methods, properties and signals
GObjects from C are objects of their class (one per GObject) with the class's C functions as methods and its GObject properties in camelCase; signal handlers are released on disconnect; the memory section describes the references their JavaScript objects hold.
1 parent f60d83c commit a48f488

3 files changed

Lines changed: 89 additions & 40 deletions

File tree

‎content/guide/extending-classes-and-implementing-interfaces-linux.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,8 @@ class CountingButton extends GtkButton {
6666
```
6767

6868
- Vfuncs are named as in the class structs of the C headers (`GtkWidgetClass.snapshot`, `GObjectClass.constructed`), in snake_case or camelCase (`size_allocate` or `sizeAllocate`). Vfuncs receive the instance as `this`, followed by their other arguments.
69-
- `super.method(...)` calls the parent's implementation, a JavaScript one or the native one.
69+
- `super.method(...)` calls the parent's implementation, a JavaScript one or the native one. That includes vfuncs with a public function of the same name: in an override of `GtkWidgetClass.measure`, `super.measure()` calls the parent's vfunc, not `gtk_widget_measure`.
70+
- Instances have the methods and properties of their native classes (`this.queue_draw()`, `this.visible`), see [GObjects](/guide/linux-marshalling#gobjects). Calling a method you override, such as `swatch.measure(...)`, calls your override.
7071
- An instance is passed to C functions as the GObject (`gtk_box_append(box, swatch)`), and fields you set on `this` are visible when native code calls your overrides.
7172
- `instanceof` works for your class and its native parents.
7273
- Classes can be extended again, from JavaScript.
@@ -248,7 +249,7 @@ An instance of a JavaScript class is a JavaScript object together with the GObje
248249

249250
You don't need to unref instances you create with `new`. Use `dispose` (not `finalize`) to release resources, and call `super.dispose()`.
250251

251-
Signal arguments, property values and vfunc instances that are instances of a JavaScript class are passed to JavaScript as their JavaScript object. C functions that return them return an `interop.Pointer` to the GObject. To compare it with an instance, use `interop.handleof(instance).equals(pointer)`.
252+
Signal arguments, property values, vfunc instances and the results of C functions that return GObject types are passed to JavaScript as the instance's JavaScript object. Functions declared to return `gpointer` (such as `g_list_model_get_item`) return an `interop.Pointer` to the GObject; to compare it with an instance, use `interop.handleof(instance).equals(pointer)`.
252253

253254
## How it works
254255

‎content/guide/linux-marshalling.md‎

Lines changed: 81 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -31,18 +31,18 @@ Calls are checked against the C signature: passing the wrong number of arguments
3131

3232
## Primitive types
3333

34-
| C type | JavaScript to C | C to JavaScript |
35-
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------- |
36-
| `char`, `short`, `int` (signed and unsigned), enums | `number` (truncated to the C type's size) | `number` |
37-
| `long`, `long long`, `int64_t`, `size_t`, `gsize`, `GType`, ... | `number` or `bigint` | `number`, or `bigint` for values outside &plusmn;2<sup>53</sup> |
38-
| `float`, `double`, `long double` | `number` | `number` |
39-
| `bool` (`_Bool`) | any value, converted to `true` or `false` | `boolean` |
40-
| `gboolean` | `number` or `boolean` | `number` (`0` or `1`), because `gboolean` is a C `int` |
41-
| `const char *` | `string`, `interop.Pointer` or `null` | `string`, or `null` for `NULL` |
42-
| `char *` | `string`, `interop.Pointer` or `null` | `interop.Pointer`, see [Strings](#strings) |
43-
| pointers (`void *`, `GtkWidget *`, ...) | `interop.Pointer`, `interop.Reference`, struct, `ArrayBuffer`, typed array or `null` | `interop.Pointer`, or `null` for `NULL` |
44-
| function pointers | a JavaScript function, see [Callbacks](#callbacks) | a callable JavaScript function |
45-
| structs and unions (by value) | a struct instance or a plain object | a struct instance, see [Structs](#structs) |
34+
| C type | JavaScript to C | C to JavaScript |
35+
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
36+
| `char`, `short`, `int` (signed and unsigned), enums | `number` (truncated to the C type's size) | `number` |
37+
| `long`, `long long`, `int64_t`, `size_t`, `gsize`, `GType`, ... | `number` or `bigint` | `number`, or `bigint` for values outside &plusmn;2<sup>53</sup> |
38+
| `float`, `double`, `long double` | `number` | `number` |
39+
| `bool` (`_Bool`) | any value, converted to `true` or `false` | `boolean` |
40+
| `gboolean` | `number` or `boolean` | `number` (`0` or `1`), because `gboolean` is a C `int` |
41+
| `const char *` | `string`, `interop.Pointer` or `null` | `string`, or `null` for `NULL` |
42+
| `char *` | `string`, `interop.Pointer` or `null` | `interop.Pointer`, see [Strings](#strings) |
43+
| pointers (`void *`, `GtkWidget *`, ...) | `interop.Pointer`, `interop.Reference`, struct, `ArrayBuffer`, typed array or `null` | `interop.Pointer`, or `null` for `NULL`; a pointer to a GObject is its object, see [GObjects](#gobjects) |
44+
| function pointers | a JavaScript function, see [Callbacks](#callbacks) | a callable JavaScript function |
45+
| structs and unions (by value) | a struct instance or a plain object | a struct instance, see [Structs](#structs) |
4646

4747
`null` and `undefined` are passed as `NULL` (or `0` for numbers).
4848

@@ -55,17 +55,15 @@ atoll('9007199254740993') // 9007199254740993n
5555

5656
## Pointers
5757

58-
Pointers are `interop.Pointer` objects. Every call returns a new object, so compare pointers with `equals()`, not `===`:
58+
Pointers are `interop.Pointer` objects. A GObject is the same object every time it reaches JavaScript (see [GObjects](#gobjects)), but other pointers are new objects on every call, so compare them with `equals()`, not `===`:
5959

6060
```ts
61-
const box = gtk_box_new(GtkOrientation.VERTICAL, 0)
62-
const label = gtk_label_new('Hello')
63-
gtk_box_append(box, label)
64-
65-
gtk_widget_get_parent(label).equals(box) // true
61+
const text = g_strdup('hello')
62+
text.equals(text.add(0)) // true
63+
text === text.add(0) // false
6664

67-
box.toHexString() // '0x5581f3a0c2d0'
68-
box.add(8) // a pointer 8 bytes further
65+
text.toHexString() // '0x5581f3a0c2d0'
66+
text.add(8) // a pointer 8 bytes further
6967
new interop.Pointer(0x1000) // a pointer from an address
7068
```
7169

@@ -194,9 +192,9 @@ timer.it_interval = { tv_sec: 2, tv_usec: 0 }
194192
- Pointer fields are read as `interop.Pointer`. To view a struct that a pointer points to, use `new interop.Reference(StructType, pointer).value`.
195193

196194
```ts
197-
const label = g_object_ref_sink(gtk_label_new('Hello'))
195+
const label = gtk_label_new('Hello')
198196
const object = new interop.Reference(GObject, label).value
199-
console.log(object.ref_count) // 1
197+
console.log(object.ref_count) // 1, the reference the JavaScript object holds
200198
```
201199

202200
## Callbacks
@@ -235,41 +233,89 @@ const compare = interop.callback((a, b) => int(a) - int(b), {
235233

236234
Keep the following in mind:
237235

238-
- The C function generated for a JavaScript function stays valid until you call `interop.release(fn)`, so it is safe to use for callbacks that are called later (signal handlers, timeouts and idle callbacks). Release callbacks you no longer need.
236+
- The C function generated for a JavaScript function stays valid until you call `interop.release(fn)`, so it is safe to use for callbacks that are called later (timeouts and idle callbacks). Release callbacks you no longer need. Signal handlers are released for you, see [GObject signals](#gobject-signals).
239237
- A string returned from a callback is only valid until the callback returns. Return `interop.cstring()` (and keep a reference to it) or `g_strdup()` instead.
240238
- An exception thrown in a callback doesn't reach the C caller. It is reported as an uncaught error, and the C caller receives `0` (or `NULL`).
241239
- Callbacks always run on the JavaScript thread that created them, see [Threading](#threading).
242240

241+
## GObjects
242+
243+
A GObject that reaches JavaScript (the result of a C function declared to return a GObject class or interface, a struct field, a signal argument or a property value) is an object of its class. There is one JavaScript object per GObject, so `===` works:
244+
245+
```ts
246+
const box = gtk_box_new(GtkOrientation.VERTICAL, 0)
247+
const label = gtk_label_new('Hello')
248+
gtk_box_append(box, label)
249+
250+
gtk_widget_get_parent(label) === box // true
251+
label instanceof GtkLabel // true, and GtkWidget, GObject
252+
```
253+
254+
A class's C functions are methods of its objects, named without the type's prefix, and so are the functions of the interfaces it implements. Its GObject properties are JavaScript properties in camelCase:
255+
256+
```ts
257+
label.set_text('Hi') // gtk_label_set_text(label, 'Hi')
258+
box.append(gtk_label_new('More')) // gtk_box_append, from GtkBox
259+
entry.set_text('x') // gtk_editable_set_text, from the GtkEditable interface
260+
261+
label.maxWidthChars = 20 // the max-width-chars property
262+
label.visible // true, a boolean
263+
```
264+
265+
- A property has a getter if it's readable and a setter if it's writable after construction, so assigning a read-only property throws in strict mode. When the class has a matching C getter or setter (`gtk_widget_get_opacity` for `opacity`), the property calls it directly.
266+
- Calling the C functions still works the same way, and a method costs what the C call does.
267+
- Create objects with `new`, passing construct properties as with `g_object_new`. Abstract classes throw.
268+
269+
```ts
270+
const window = new GtkWindow({ title: 'Hello', defaultWidth: 400 })
271+
```
272+
273+
GObjects are still `interop.Pointer` values, so they pass to any C function and support `equals()` and `toHexString()`. Functions declared to return `gpointer` (`g_list_model_get_item`) return an `interop.Pointer` with no class; use a typed variant when there is one (`g_list_model_get_object`).
274+
243275
## GObject signals
244276

245-
`g_signal_connect` and `g_signal_connect_after` connect a JavaScript function to a GObject signal. The handler receives the instance, the signal's arguments and the user data:
277+
`connect` and `disconnect`, or `g_signal_connect`, `g_signal_connect_after` and `g_signal_handler_disconnect`, connect a JavaScript function to a GObject signal. The handler receives the instance, the signal's arguments and the user data:
246278

247279
```ts
248-
g_signal_connect(button, 'clicked', (self) => {
249-
console.log('clicked')
280+
const id = button.connect('clicked', (self) => {
281+
console.log('clicked', self === button) // true
250282
})
283+
button.disconnect(id)
251284

252285
g_signal_connect(toggle, 'notify::active', (self) => {
253-
console.log(gtk_switch_get_active(self))
286+
console.log(self.active)
254287
})
255288
```
256289

257-
The argument types are read from the signal's definition. String arguments are passed as pointers, read them with `interop.stringFromCString()`.
290+
- The argument types are read from the signal's definition: GObject arguments are their objects. String arguments are passed as pointers, read them with `interop.stringFromCString()`.
291+
- A handler is released when it's disconnected or its object is finalized, so you don't need `interop.release()` for it. Connecting the same function more than once is fine.
292+
- `emit(signal, ...args)` emits a signal, as `g_signal_emit_by_name` does.
258293

259294
## GObject memory management
260295

261-
GObjects are `interop.Pointer` values, and their reference counts are not managed by the runtime. Follow the [GObject ownership rules](https://docs.gtk.org/gobject/concepts.html#object-memory-management) as you would in C: unref objects you own when you are done with them, or adopt them so they are unreffed when the pointer is garbage collected:
296+
The JavaScript object of a GObject holds a reference on it (a toggle reference):
297+
298+
- While native code also references the GObject (a parent widget, a `GListStore`), the JavaScript object stays alive, with any fields you set on it.
299+
- When only JavaScript references it, the JavaScript object can be garbage collected, which releases the GObject.
300+
301+
The C headers don't say who owns a function's result, so the JavaScript object always takes a reference of its own. A floating reference, as new widgets have, becomes the JavaScript object's, so there is nothing to release:
262302

263303
```ts
264-
const label = interop.adopt(
265-
g_object_ref_sink(gtk_label_new('hi')),
266-
g_object_unref,
267-
)
304+
const label = gtk_label_new('hi') // floating: owned by its JavaScript object
305+
box.append(label)
306+
```
307+
308+
A function that returns a new reference (`transfer full` in the GTK docs, often `*_new`, `*_dup_*` and `*_ref`) leaves that reference to you, as in C. Unref it when you no longer need it; the JavaScript object keeps its own:
309+
310+
```ts
311+
const file = g_file_new_for_path('/tmp')
312+
g_object_unref(file) // the reference g_file_new_for_path returned
313+
file.get_path() // still valid
268314
```
269315

270-
Widgets added to a parent widget are owned by the parent and don't need to be unreffed.
316+
Objects created with `new`, and instances of [JavaScript GObject classes](/guide/extending-classes-and-implementing-interfaces-linux), don't need to be unreffed.
271317

272-
Instances of [JavaScript GObject classes](/guide/extending-classes-and-implementing-interfaces-linux) are managed for you: their JavaScript object holds a reference on the GObject.
318+
A C function that keeps the reference you pass it (`transfer full` parameters, such as `gtk_widget_set_layout_manager`) takes the JavaScript object's reference. Pass `g_object_ref(object)` to such functions.
273319

274320
## Variadic functions
275321

‎content/guide/linux/index.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,8 @@ console.log(getpid())
127127

128128
const label = gtk_label_new('Hello from JavaScript')
129129
gtk_label_set_selectable(label, true)
130+
label.set_selectable(true) // the same call, as a method
131+
label.selectable = true // or through the GObject property
130132
```
131133

132134
Every `@nativescript/core` view exposes the underlying GTK widget (a `GtkWidget *`) through `nativeView`:
@@ -139,15 +141,15 @@ const button = new Button()
139141
gtk_widget_set_tooltip_text(button.nativeView, 'Click me')
140142
```
141143

142-
GTK signals are connected with `g_signal_connect`:
144+
GTK signals are connected with `connect` (or `g_signal_connect`):
143145

144146
```ts
145-
g_signal_connect(button.nativeView, 'clicked', () => {
147+
button.nativeView.connect('clicked', () => {
146148
console.log('clicked')
147149
})
148150
```
149151

150-
Read [Linux Marshalling](/guide/linux-marshalling) to learn how JavaScript values are converted to C types, how to work with pointers, structs and callbacks, and how to manage the memory of GObjects.
152+
Read [Linux Marshalling](/guide/linux-marshalling) to learn how JavaScript values are converted to C types, how to work with pointers, structs and callbacks, and how GObjects, their methods, properties, signals and memory work.
151153

152154
GObject classes, such as GTK widgets, can be extended from JavaScript, and GObject interfaces implemented. See [Extending GObject classes and implementing interfaces](/guide/extending-classes-and-implementing-interfaces-linux).
153155

0 commit comments

Comments
 (0)