Tuesday, February 14, 2017

Gtk and CoffeeScript?

Someone reminded me recently that Gnome's official language is GJS. I love javascript, and I would be all over that except for one thing. Standards. What version is it, anyway? It's not ES6. It's not ES5. It reminds me of issues with IE. But we have tools for this - things like Babel, TypeScript, and my favorite, CoffeeScript.

So, CoffeeScript it is, and the first thing that goes is

const Lang = imports.lang;

This is what CoffeeScript replaces. Now we have a real 1st class class statement.

So here is my port of Gnome's HelloWorld example,


Gtk = imports.gi.Gtk

class Application

    #create the application
    constructor: () ->
        @application = new Gtk.Application()
        #connect to 'activate' and 'startup' signals to handlers.
        @application.connect('activate', @_onActivate)
        @application.connect('startup', @_onStartup)

    # create the UI
    _buildUI: () ->
        @_window = new Gtk.ApplicationWindow(application: @application, title: "Hello World!")
        @_window.set_default_size(200, 200)
        @label = new Gtk.Label(label: "Hello World" )
        @_window.add(@label)

    # handler for 'activate' signal
    _onActivate: () =>
        # show the window and all child widgets
        @_window.show_all()

    # handler for 'startup' signal
    _onStartup: () =>
        @_buildUI()

#run the application
app = new Application()
app.application.run(ARGV)

The important thing to note, is that we no longer use Lang.bind:


this.application.connect('activate', Lang.bind(this, this._onActivate));

Instead, the function definition is bound using the fat arrow:


    _onActivate: () =>


The other thing I ran into is shebang support. Coffeescript treats it as a coment and discards it.
So I follow up my compile with a simple fix replacing the coffescript header with shebang.


coffee -c test.coffee
sed -i "s/\/\/ Generated by CoffeeScript 1.11.1/\#\!\/usr\/bin\/env gjs/" test.js





1 comment: