# Bildvisare (Vala)

Lite mer än ett enkelt ”Hej världen”-program i GTK+.
Dokumentationsprojekt för GNOME
gnome-doc-list@gnome.org
Johannes Schmid
jhs@gnome.org
Philip Chimento
philip.chimento@gmail.com
Tiffany Antopolski
tiffany.antopolski@gmail.com
Marta Maria Casetti
mmcasetti@gmail.com 2013
Sebastian Rasmussen
sebras@gmail.com 2019
Anders Jonsson
anders.jonsson@norsjovallen.se 2021

# Bildvisare

      I denna handledning kommer du skapa ett program som öppnar och visar en bildfil. Du kommer att lära dig:

        Hur du konfigurerar ett grundläggande projekt med den integrerade utvecklingsmiljön Anjuta.
        Hur du skriver ett Gtk-program i Vala
        Några grundläggande koncept i GObject-programmering

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

        Grundläggande kunskap i programmeringsspråket Vala.
        En installerad kopia av Anjuta.
        Du kan finna API-referensen för gtk+-3.0 användbar, även om det inte är nödvändigt att följa handledningen.

# 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å Skapa ett nytt projekt eller Arkiv Ny Projekt för att öppna projektguiden.

Välj GTK+ (enkel) från fliken Vala, klicka på Fortsätt, och fyll i dina detaljer på de nästkommande sidorna. Använd image-viewer som projektnamn och katalog.

Säkerställ att Använd GtkBuilder för användargränssnitt inte är ikryssad då vi kommer skapa användargränssnittet manuellt i denna handledning.

Du kommer lära dig hur du använder gränssnittsbyggaren i handledningen Gitarrstämmare.

Klicka på Fortsätt sedan Verkställ så kommer projektet skapas åt dig. Öppna src/image_viewer.vala från flikarna Projekt eller Filer. Du kommer se denna kod:

using GLib; using Gtk;

public class Main : Object {

public Main () { Window window = new Window(); window.set_title ("Hej världen"); window.show_all(); window.destroy.connect(on_destroy); }

public void on_destroy (Widget window) { Gtk.main_quit(); }

static int main (string[] args) { Gtk.init (ref args); var app = new Main ();

Gtk.main ();

return 0; } }

# Bygg koden för första gången

The code loads an (empty) window from the user interface description file and shows it. More details are given below; skip this list if you understand the basics:

The two `using` lines at the top import namespaces so we don't have to name them explicitly.

The constructor of the `Main` class creates a new (empty) window and connects a signal to exit the application when that window is closed.

Connecting signals is how you define what happens when you push a button, or when some other event happens. Here, the `destroy` function is called (and quits the app) when you close the window.

The `static main` function is run by default when you start a Vala application. It calls a few functions which create the `Main` class, set up and then run the application. The `Gtk.main` function starts the GTK main loop, which runs the user interface and starts listening for events (like clicks and key presses).

Denna kod är klar att användas, så du kan kompilera den genom att klicka på Bygg Bygg projekt (eller trycka Skift F7).

Change the Configuration to Default and then press Execute to configure the build directory. You only need to do this once, for the first build.

# Skapa användargränssnittet

Now we will bring life into the empty window. GTK organizes the user interface with `Gtk.Container`s that can contain other widgets and even other containers. Here we will use the simplest available container, a `Gtk.Box`.

Add the following lines to the top of the `Main` class:

private Window window; private Image image;

Ersätt nu den aktuella konstruktorn med den nedan:

public Main () {

window = new Window (); window.set_title ("Bildvisare i Vala");

// Konfigurera användargränssnittet var box = new Box (Orientation.VERTICAL, 5); var button = new Button.with_label ("Öppna bild"); image = new Image ();

box.pack_start (image, true, true, 0); box.pack_start (button, false, false, 0); window.add (box);

// Visa öppna-dialog när en fil öppnas button.clicked.connect (on_open_image);

window.show_all (); window.destroy.connect (main_quit); }

The first two lines are the parts of the GUI that we will need to access from more than one method. We declare them up here so that they are accessible throughout the class instead of only in the method where they are created.

The first lines of the constructor create the empty window. The next lines create the widgets we want to use: a button for opening up an image, the image view widget itself and the box we will use as a container.

The calls to `pack_start` add the two widgets to the box and define their behaviour. The image will expand into any available space whereas the button will just be as big as needed. You will notice that we don't set explicit sizes on the widgets. In GTK this is usually not needed as it makes it much easier to have a layout that looks good in different window sizes. Next, the box is added to the window.

We need to define what happens when the user clicks on the button. GTK uses the concept of signals.

When the button is clicked, it fires the `clicked` signal, which we can connect to some action (defined in a callback method).

This is done using the `connect` method of the button's `clicked` signal, which in this case tells GTK to call the (yet undefined) `on_image_open` callback method when the button is clicked. We will define the callback in the next section.

In the callback, we need to access the `window` and `image` widgets, which is why we defined them as private members at the top of our class.

The last `connect` call makes sure that the application exits when the window is closed. The code generated by Anjuta called an `on_destroy` callback method which called `Gtk.main_quit`, but just connecting our signal to `main_quit` directly is easier. You can delete the `on_destroy` method.

# Visa bilden

We will now define the signal handler for the `clicked` signal for the button we mentioned before. Add this code after the constructor:

public void on_open_image (Button self) { var filter = new FileFilter (); var dialog = new FileChooserDialog ("Open image", window, FileChooserAction.OPEN, Stock.OK, ResponseType.ACCEPT, Stock.CANCEL, ResponseType.CANCEL); filter.add_pixbuf_formats (); dialog.add_filter (filter);

switch (dialog.run ()) { case ResponseType.ACCEPT: var filename = dialog.get_filename (); image.set_from_file (filename); break; default: break; } dialog.destroy (); }

This is a bit complicated, so let's break it down:

A signal handler is a type of callback method that is called when a signal is emitted. Here the terms are used interchangeably.

The first argument of the callback method is always the widget that sent the signal. Sometimes other arguments related to the signal come after that, but clicked doesn't have any.

In this case the `button` sent the `clicked` signal, which is connected to the `on_open_image` callback method:

button.clicked.connect (on_open_image);

The `on_open_image` method takes the button that emitted the signal as an argument:

public void on_open_image (Button self)

The next interesting line is where the dialog for choosing the file is created. `FileChooserDialog`'s constructor takes the title of the dialog, the parent window of the dialog and several options like the number of buttons and their corresponding values.

Notice that we are using stock button names from Gtk, instead of manually typing "Cancel" or "Open". The advantage of using stock names is that the button labels will already be translated into the user's language.

The next two lines restrict the Open dialog to only display files which can be opened by GtkImage. GtkImage is a widget which displays an 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.

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

Assuming that the user did click Open, the next lines get the filename of the image selected by the user, and tell the `GtkImage` widget to load and display the selected image.

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

Destroying automatically hides the dialog.

# Bygg och kör programmet

All of the code should now be ready to go. Click Build Build Project to build everything again, and then Run Execute to start the application.

If you haven't already done so, choose the src/image-viewer application in the dialog that appears. Finally, hit Run and enjoy!

# 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:

Set it up so that when the window opens it is of a specific size to start off with. For example, 200 X 200 pixels.

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.