Bindings

Bindings

termbox-glib generates GObject Introspection metadata and a Vala package from the C API. The lifecycle and drawing model are the same as in getting started. The examples below show the binding syntax without repeating the C API discussion.

Vala

Vala uses the generated termbox-glib-0.1.vapi package. The example below is written as a Vala script; the shebang passes the package dependency to vala. Constructors and methods that can fail throw GLib.Error.

#!/usr/bin/env -S vala --pkg termbox-glib-0.1

using GLib;
using Termbox;

private const unichar QUIT_KEY = 'q';

private void draw_message(Terminal terminal) throws GLib.Error {
    var fg = Attr.color(Color.GREEN, AttrFlags.BOLD);
    var bg = Attr.default();
    var message = "Hello from Vala. Press %s to quit.".printf(QUIT_KEY.to_string());

    terminal.print(0, 0, fg, bg, message);
    terminal.present();
}

public static int main() {
    try {
        var loop = new MainLoop(null, false);
        var terminal = new Terminal();
        var source = terminal.create_event_source();

        terminal.key.connect((event) => {
            if (event.get_char() == QUIT_KEY)
                loop.quit();
        });

        source.attach(null);
        draw_message(terminal);

        try {
            loop.run();
        } finally {
            source.destroy();
        }

        return 0;
    } catch (GLib.Error error) {
        warning("Failed to run: %s", error.message);
        return 1;
    }
}

GJS

GJS loads the typelib at runtime. In an installed setup, the typelib search path is usually provided by the installation prefix. From an uninstalled build tree, set GI_TYPELIB_PATH and LD_LIBRARY_PATH as the examples do.

#!/usr/bin/env gjs -m

import GLib from 'gi://GLib';
import Termbox from 'gi://Termbox';
import System from 'system';

const QUIT_KEY = 'q';

function drawMessage(terminal) {
  const fg = Termbox.attr_color(Termbox.Color.GREEN, Termbox.AttrFlags.BOLD);
  const bg = Termbox.attr_default();

  terminal.print(0, 0, fg, bg, `Hello from GJS. Press ${QUIT_KEY} to quit.`);
  terminal.present();
}

function main() {
  const mainLoop = new GLib.MainLoop(null, false);
  const terminal = Termbox.Terminal.new();
  const source = terminal.create_event_source();

  terminal.connect('key', (_terminal, event) => {
    if (event.get_char() === QUIT_KEY)
      mainLoop.quit();
  });

  source.attach(null);
  drawMessage(terminal);

  try {
    mainLoop.run();
  } finally {
    source.destroy();
  }

  return 0;
}

try {
  System.exit(main());
} catch (error) {
  logError(error, 'Failed to run');
  System.exit(1);
}

See examples/basic.vala and examples/basic.js for complete examples that also redraw on resize and hide the cursor.