# Bildvisare (Javascript)

Lite mer än ett enkelt ”Hej världen”-program - skriv en bildvisare i GTK+. Inkluderar en introduktion till språket Javascript.
Jonh Wendell
jwendell@gnome.org
Johannes Schmid
jhs@gnome.org
Marta Maria Casetti
mmcasettii@gmail.com 2013
Sebastian Rasmussen
sebras@gmail.com 2019
Anders Jonsson
anders.jonsson@norsjovallen.se 2021

# Bildvisare

      I denna handledning kommer vi skriva ett väldigt enkelt GTK-program som läser in och visar en bildfil. Du kommer lära dig hur du:

        Skriver ett enkelt GTK-användargränssnitt i Javascript
        Hanterar händelser genom att ansluta signaler till signalhanterare
        Gör layouter för GTK-användargränssnitt genom att använda behållare
        Läser in och visar bildfiler

      Du behöver följande för att kunna följa denna handledning:

        En installerad kopia av den integrerade utvecklingsmiljön Anjuta
        En installerad kopia av gjs-tolken
        Grundläggande kunskap i något objektorienterat programmeringsspråk

# Skapa ett projekt i Anjuta

Innan du börjar koda kommer du behöva konfigurera ett nytt projekt i Anjuta. Detta kommer skapa alla filer som du behöver för att bygga och köra koden senare. Det är också användbart för att hålla allting samlat.

Starta Anjuta och klicka på Arkiv Ny Projekt för att öppna projektguiden.

Välj Allmän Javascript från fliken JS, klicka på Framåt, och fyll i dina detaljer på de nästkommande sidorna. Använd image-viewer som projektnamn och katalog.

Klicka på Verkställ så kommer projektet skapas åt dig. Öppna src/main.js från flikarna Projekt eller Filer. Den innehåller väldigt enkel exempelkod.

# Javascript-grunder: Hej världen

Låt oss innan vi börjar skriva bildvisaren ta reda på mer om hur Javascript används i GNOME. Din första kontakt med alla programmeringsspråk bör förstås vara Hej världen-programmet vilket redan kan hittas i main.js:

print ("Hej världen!");

Detta bör se naturligt ut för dig om du är bekant med nästan vilket annat programmeringsspråk som helst. Funktionen `print` anropas med argumentet `"Hej världen!"`, vilket kommer att skrivas ut på skärmen. Observera att varje rad kod avslutas med ett semikolon.

# Klasser i Javascript

Detta är standardsättet att definiera en klass i Javascript:

function MyClass () { this._init (); }

MyClass.prototype = {

_init: function () { this.propertyA = "Det här är ett objekts fält"; this.propertyB = 10; },

aMethod: function (arg1, arg2) { print ("inuti aMethod: " + arg1 + " " + arg2); },

dumpProperties: function () { print (this.propertyA); print (this.propertyB); }

}

Detta definierar en klass med namnet `MyClass`. Låt oss gå igenom varje del av klassdefinitionen:

`function MyClass` är klassens konstruktor — dess namn måste matcha klassens namn. Du kan komma åt alla medlemmar i klassen genom att använda objektet `this`; här anropar konstruktorn klassens `_init`-metod.

The `MyClass.prototype` block is where you define the structure of the class. Each class is made up of methods (functions) and fields (variables); there are three methods and two fields in this example.

Den första metoden som definieras här kallas `_init`, och vi anger att det är en funktion utan några argument:

_init: function ()

We write the function inside some curly braces. Two fields are defined here, `propertyA` and `propertyB`. The first is set to a string and the second is set to an integer (10). The function doesn't return any value.

The next method is called `aMethod` and has two arguments, which it prints out when you call it. The final method is `dumpProperties`, and prints the fields `propertyA` and `propertyB`.

Note how the class definition (prototype) is arranged; each function definition is separated by a comma.

Nu då MyClass har definierats så kan vi leka med den:

var o = new MyClass (); o.aMethod ("Hej", "världen"); o.propertyA = "Ändrade just dess värde!"; o.dumpProperties ();

This code creates a new instance of the class called `o`, runs `aMethod`, changes `propertyA` to a different string, and then calls `dumpProperties` (which outputs the fields).

Save the code in the main.js and then run it by using Run Execute from the menu or using the toolbar.

# Ett första Gtk-program

Låt oss se hur ett väldigt enkelt Gtk-program ser ut i Javascript:

const Gtk = imports.gi.Gtk;

Gtk.init (null, null);

var w = new Gtk.Window ({title: "Bildvisardemonstration"}); w.show ();

Gtk.main ();

Låt oss ta en titt på vad som händer:

Den första raden importerar Gtk-namnrymden (d.v.s. inkluderar Gtk-biblioteket). Biblioteken tillhandahålls av GObject Introspection (gi), vilket tillhandahåller språkbindningar för många GNOME-bibliotek.

`Gtk.init` initierar Gtk-biblioteket; denna sats är obligatorisk för alla Gtk-program.

Nästa rad skapar huvudfönstret genom att skapa ett nytt `Gtk.Window`-objekt. Du kan skicka flera egenskaper till fönstrets konstruktor genom att använda syntaxen `{egenskap: värde, egenskap: värde, …}`. I detta fall ställer vi in fönstrets titel.

Nästa rad visar explicit fönstret. I Gtk är varje komponent dold som standard.

Finally, `Gtk.main` runs the main loop — in other words, it executes the program. The main loop listens for events (signals) from the user interface and then calls a signal handler which will do something useful. We'll learn more about signals shortly.

Save the code in main.js and run it. You will notice that the application does not quit when you close the window. This is because we haven't set up a signal handler to deal with the window's `destroy` (close) signal yet. We'll do this shortly, but for now you can just hit Ctrl C in the terminal window to quit the program.

# Lägga till klasser

Det korrekta sättet att programmera med Gtk är att använda klasser. Låt oss skriva om den enkla koden du just skrev med klasser:

const Gtk = imports.gi.Gtk;

function ImageViewer () { this._init (); }

ImageViewer.prototype = { _init: function () { this.window = new Gtk.Window ({title: "Bildvisardemonstration"}); this.window.show (); } }

Gtk.init (null, null); var iv = new ImageViewer (); Gtk.main ();

Notice that the program is the same; we just moved the window creation code to our own `ImageViewer` class. The class's constructor calls the `_init` method, which creates and shows the window. We then create an instance of the class before running the main loop (`Gtk.main`).

This code is modular and can be split into multiple files easily. This makes it cleaner and easier to read.

# Signaler

Signals are one of the key concepts in Gtk programming. Whenever something happens to an object, it emits a signal; for example, when a button is clicked it gives off the `clicked` signal. If you want your program to do something when that event occurs, you must connect a function (a "signal handler") to that signal. Here's an example:

function button_clicked () { print ("du klickade på mig!"); } var b = new Gtk.Button ({label:"Klicka på mig"}); b.connect ("clicked", button_clicked);

The last two lines create a `Gtk.Button` called `b` and connect its `clicked` signal to the `button_clicked` function, which is defined above. Every time the button is clicked, the code in the `button_clicked` function will be executed. It just prints a message here.

Syntax för att ansluta en godtycklig signal till en funktion är:

object.connect (<signalnamn>, <funktion_att_anropa>);

Du kan hitta signaldefinitioner för alla objekt i GTK-klassreferensen.

You can simplify the code by making use of an inline function definition:

`b.connect ("clicked", function () { print ("du klickade på mig!"); });`

# Stänga fönstret

When you close a Gtk window it's not really closed, it's hidden. This allows you to keep the window around (which is useful if you want to ask the user if they really want to close the window, for example).

In our case, we really do just want to close the window. The simplest way of doing this is by connecting the `hide` signal of the GtkWindow object to a function that closes the application. Go back to the image-viewer.js file and add the following code to the `_init` method, on the line above `this.window.show`:

this.window.connect ("hide", Gtk.main_quit);

This connects the `hide` signal of the window to Gtk's `main_quit` function, which ends the execution of the Gtk main loop. Once the main loop finishes, the function `Gtk.main` returns. Our program would continue to run any code written after the `Gtk.main ();` line, but since we don't have any code after that point, the program just ends.

# Behållare: göra en layout för användargränssnittet

Widgets (controls, such as buttons and labels) can be arranged in the window by making use of containers. You can organize the layout by mixing different types of containers, like boxes and grids.

A `Gtk.Window` is itself a type of container, but you can only put one widget directly into it. We would like to have two widgets, an image and a button, so we must put a "higher-capacity" container inside the window to hold the other widgets. A number of container types are available, but we will use a `Gtk.Box` here. A `Gtk.Box` can hold several widgets, organized horizontally or vertically. You can do more complicated layouts by putting several boxes inside another box and so on.

There is a graphical user interface designer called Glade integrated in Anjuta which makes UI design really easy. For this simple example, however, we will code everything manually.

Let's add the box and widgets to the window. Insert the following code into the `_init` method, immediately above the `this.window.show` line:

var main_box = new Gtk.Box ({orientation: Gtk.Orientation.VERTICAL, spacing: 0}); this.window.add (main_box);

The first line creates a `Gtk.Box` called `main_box` and sets two of its properties: the `orientation` is set to vertical (so widgets are arranged in a column), and the `spacing` between the widgets is set to 0 pixels. The next line then adds the newly-created `Gtk.Box` to the window.

So far the window only contains an empty `Gtk.Box`, and if you run the program now you will see no changes at all (the `Gtk.Box` is a transparent container, so you can't see that it's there).

# Packning: Lägga till komponenter till behållaren

To add some widgets to the `Gtk.Box`, insert the following code directly below the `this.window.add (main_box)` line:

this.image = new Gtk.Image (); main_box.pack_start (this.image, true, true, 0);

The first line creates a new `Gtk.Image` called `image`, which will be used to display an image file. Then, the image widget is added (packed) into the `main_box` container using `Gtk.Box`'s `pack_start` method.

`pack_start` takes 4 arguments: the widget that is to be added to the `Gtk.Box` (`child`); whether the `Gtk.Box` should grow larger when the new widget is added (`expand`); whether the new widget should take up all of the extra space created if the `Gtk.Box` gets bigger (`fill`); and how much space there should be, in pixels, between the widget and its neighbors inside the `Gtk.Box` (`padding`).

Gtk containers (and widgets) dynamically expand to fill the available space, if you let them. You don't position widgets by giving them a precise x,y-coordinate location in the window; rather, they are positioned relative to one another. This makes handling window resizing much easier, and widgets should automatically take a sensible size in most situations.

Also note how the widgets are organized in a hierarchy. Once packed in the `Gtk.Box`, the `Gtk.Image` is considered a child of the `Gtk.Box`. This allows you to treat all of the children of a widget as a group; for example, you could hide the `Gtk.Box`, which would also hide all of its children at the same time.

Infoga nu dessa två rader under de två du just lade till:

var open_button = new Gtk.Button ({label: "Öppna en bild…"}); main_box.pack_start (open_button, false, false, 0);

These lines are similar to the first two, but this time they create a `Gtk.Button` and add it to `main_box`. Notice that we are setting the `expand` argument (the second one) to `false` here, whereas it was set to `true` for the `Gtk.Image`. This will cause the image to take up all available space and the button to take only the space it needs. When you maximize the window, the button size will remain the same, but the image size will increase, taking up all of the rest of the window.

Slutligen måste vi ändra raden `this.window.show ();` så att den säger:

this.window.show_all ();

This will show the child of the Gtk window, and all of its children, and its children's children, and so on. (Remember that Gtk widgets are all hidden by default.)

# Läsa in bilden: ansluta till knappens `clicked`-signal

When the user clicks on the Open button, a dialog should appear so that the user can choose a picture. Once chosen, the picture should be loaded and shown in the image widget.

The first step is to connect the `clicked` signal of the button to a signal handler function, which we call `_openClicked`. Put this code immediately after the `var open_button = new Gtk.Button` line where the button was created:

open_button.connect ("clicked", Lang.bind (this, this._openClicked));

We are using the Lang JavaScript helper here. It allows us to connect a class method to the signal, rather than a plain function (without a class) which we had used before for the window's `hide` signal. Don't worry about this for now, it's just a technical detail. For it to work, you also need to put the following line at the top of the file:

const Lang = imports.lang;

# Läsa in bilden: skriva signalens återanrop

Now we can create the `_openClicked()` method. Insert the following into the `ImageViewer.prototype` code block, after the `_init` method (and not forgetting the comma):

_openClicked: function () { var chooser = new Gtk.FileChooserDialog ({title: "Välj en bild", action: Gtk.FileChooserAction.OPEN, transient_for: this.window, modal: true}); chooser.add_button (Gtk.STOCK_CANCEL, 0); chooser.add_button (Gtk.STOCK_OPEN, 1); chooser.set_default_response (1);

var filter = new Gtk.FileFilter (); filter.add_pixbuf_formats (); chooser.filter = filter;

if (chooser.run () == 1) this.image.file = chooser.get_filename ();

chooser.destroy (); }

Det här är lite mer komplicerat än något som vi försökt så här långt, så låt oss dela upp det:

The line beginning with `var chooser` creates an Open dialog, which the user can use to choose files. We set four properties: the title of the dialog; the action (type) of the dialog (it's an "open" dialog, but we could have used `SAVE` if the intention was to save a file; `transient_for`, which sets the parent window of the dialog; and `modal` which, if set to `true`, prevents the user from clicking on another area of the application until the dialog is closed.

The next two lines add Cancel and Open buttons to the dialog. The second argument of the `add_button` method is the (integer) value that is returned when the button is pressed: 0 for Cancel and 1 for Open.

Observera att vi använder standardknappnamn från Gtk, istället för att manuellt skriva in ”Avbryt” eller ”Öppna”. Fördelen med att använda standardnamn är att knappetiketterna redan kommer vara översatta till användarens språk.

`set_default_response` determines the button that will be activated if the user double-clicks a file or presses Enter. In our case, we are using the Open button as default (which has the value 1).

The next three lines restrict the Open dialog to only display files which can be opened by `Gtk.Image`. A filter object is created first; we then add all kinds of files supported by `Gdk.Pixbuf` (which includes most image formats like PNG and JPEG) to the filter. Finally, we set this filter to be the Open dialog's filter.

`chooser.run` displays the Open dialog. The dialog will wait for the user to choose an image; when they do, `chooser.run` will return the value 1 (it would return 0 if the user clicked Cancel). The `if` statement tests for this.

Assuming that the user did click Open, the next line sets the `file` property of the `Gtk.Image` to the filename of the image selected by the user. The `Gtk.Image` will then load and display the chosen image.

In the final line of this method, we destroy the Open dialog because we don't need it any more.

# Kör programmet

All kod som du behöver bör nu vara på plats, så testa att köra koden. Det var det, en fullt fungerande bildvisare (och en snabb rundtur av Javascript och Gtk) på inte mycket tid alls!

# Referensimplementation

Om du stöter på problem med handledningen kan du jämföra din kod med denna referenskod.

# Nästa steg

Här är några idéer på hur du kan utöka denna enkla demonstration:

Låt användaren välja en katalog snarare än en fil, och tillhandahåll kontroller för att gå igenom alla bilderna i en katalog.

Tillämpa slumpmässiga filter och effekter till bilden då den läses in och låt användaren spara den ändrade bilden.

GEGL har kraftfulla bildmanipuleringsförmågor.

Allow the user to load images from network shares, scanners, and other more complicated sources.

You can use GIO to handle network file transfers and the like, and GNOME Scan to handle scanning.