# Integrar software existente con GNOME

Guía para fabricantes de software independente

Guía para fabricantes de software independente

Rosanna
Yuen

    	    zana@gnome.org

Federico
Mena-Quintero

    	    federico@gnu.org

Mike
Hearn

    	    mike@navi.cx

2005, 2006
Rosanna Yuen, Federico Mena-Quintero, Mike Hearn
2011.
Fran Dieguez (frandieguez@gnome.org)
0.6
2006/Setembro/19

Extensión das guías de iconas.

0.5
2006/September/18

Integración do contido do primeiro artigo de Rosanna Yuen sobre os estándares de freedesktop.org

0.0
Xuño 2005

Versión inicial deste documento.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License (GFDL), Version 1.1 or any later version published by the Free Software Foundation with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. You can find a copy of the GFDL at this link or in the file COPYING-DOCS distributed with this manual.

Este manual é parte dunha colección de manuais de GNOME distribuído baixo a GFDL. Se quere distribuír este manual por separado da colección. pode facelo engadindo unha copia da licenza do manual, tal como se describe na sección 6 da licenza.

Moitos dos nomes empregados polas empresas para distinguir os seus produtos e servizos considéranse marcas comerciais. Cando estes nomes aparezan na documentación de GNOME, e sempre que se teña informado aos membros do Proxecto de documentación de GNOME de ditas marcas comerciais, os nomes aparecerán en maiúsculas ou coas iniciais en maiúsculas.

DOCUMENT AND MODIFIED VERSIONS OF THE DOCUMENT ARE PROVIDED UNDER THE TERMS OF THE GNU FREE DOCUMENTATION LICENSE WITH THE FURTHER UNDERSTANDING THAT:

1. DOCUMENT IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE DOCUMENT OR MODIFIED VERSION OF THE DOCUMENT IS FREE OF DEFECTS MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY, ACCURACY, AND PERFORMANCE OF THE DOCUMENT OR MODIFIED VERSION OF THE DOCUMENT IS WITH YOU. SHOULD ANY DOCUMENT OR MODIFIED VERSION PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL WRITER, AUTHOR OR ANY CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY DOCUMENT OR MODIFIED VERSION OF THE DOCUMENT IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER; AND

2. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE AUTHOR, INITIAL WRITER, ANY CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE DOCUMENT OR MODIFIED VERSION OF THE DOCUMENT, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER DAMAGES OR LOSSES ARISING OUT OF OR RELATING TO USE OF THE DOCUMENT AND MODIFIED VERSIONS OF THE DOCUMENT, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES.

## Prefacio

GNOME is a project to build a complete desktop and development platform based entirely on free software. Many companies, governments, schools, institutions, and individuals have deployed the GNOME desktop on their systems. If you are a developer of third-party software ("Independent Software Vendor" or ISV, or "Independent Software Developer" (ISD) if you don't do it commercially), you may want to ensure that your existing software runs properly under GNOME. This guide explains how to integrate existing software with GNOME, without actually rewriting that software to explicitly use the GNOME platform libraries and development tools.

Esta guía é útil nas seguintes circunstancias:

- Se é un desenvolvedor de software ou distribuidor que ten un aplicativo que non está deseñada especificamente para traballar con GNOME, pero quere asegurarse de que se executa correctametne nun Escritorio GNOME.

- Se é un administrador de sistemas dunh institucición que teña instalados Escritorios GNOME aos seus usuarios. Tamén ten aplicativos obsoletod ou caseriso e quere que os usuarios de GNOME poidan acceder a elas correctamente.

- You are writing a GNOME application proper and you need a checklist of basic things to do to ensure that your application integrates well with the rest of the GNOME desktop.

In general, this guide is about integrating existing software into a GNOME desktop. On the other hand, if you are considering writing new software, we encourage you to develop it completely with GNOME as your target platform; please refer to the GNOME Developer's Site for more information.

One of the main concerns of GNOME is the user experience. Users should have a comfortable computing environment: this means having a complete desktop and a set of applications which operate together in a consistent way. With relatively little work, applications which are not written explicitly with GNOME in mind can be made to run comfortably within a GNOME desktop.

### Estrutura desta guía

This guide is structured as a list of tasks that you need to perform to integrate existing software with GNOME. The guide presents these tasks roughly in order of importance. For example, the task of adding your application to the GNOME desktop's menus appears before the task for adding drag-and-drop support. Also, this guide has an appendix with an integration checklist to aid you in evaluating your integration work.

### Estándares e freedesktop.org

Many of the integration tasks in this guide rely on standards which are relevant to more than GNOME. Other desktop projects like the K Desktop Environment also use these standards: if you integrate your applications with GNOME, you should have to do little or no extra work to make them run in those other environments as well.

Creating a perfect application is a wonderful feeling. Whether large or small, you want the desktop to recognize your application and for them to interact appropriately. With multiple desktops currently available, it is best for your application to be able to integrate itself in as many of them as possible. Even though no official rules have been adopted, there is a set of specifications available at freedesktop.org.

Although not a formal standards body, freedesktop.org maintains a set of informal but commonly agreed upon guidelines. When followed, these guidelines allow applications to be integrated on to compliant desktops.

## Integración básica

This chapter teaches you about the very basic steps you should take to integrate a program into the GNOME desktop. These steps concern the following:

- Letting the user launch your application by making it appear in the desktop's panel menus, or any other launching mechanism in the desktop.

- Letting the desktop know which types of user-created files require your application to be launched.

- Letting the desktop know how to display the appropriate icons for your program and the files which your program creates.

### Ficheiros de escritorio: poñer o seu aplicativo nos menús do escritorio

To run applications from GNOME, users click on icons on their desktops or they select the applications which they want to run from a menu. Therefore, the first step in integrating an existing program with GNOME is to register it with the set of applications that users can run.

Unlike in Windows or MacOS, in GNOME the users menus are automatically constructed from the list of registered applications. Each published application specifies a set of categories to which it belongs, and the systems menu configuration sorts and arranges them. This mechanism follows the freedesktop.org desktop entry and menu standards.

Though common in other desktops, creating your own application-specific submenu is not recommended. Instead, provide one menu item for each application you ship. Extra items such as help files, READMEs or links to your web site should be embedded into the application itself.

In GNOME and other freedesktop.org-compliant desktops, an application gets registered into the desktop's menus through a desktop entry, which is a text file with `.desktop` extension. This desktop file contains a listing of the configurations for your application. The desktop takes the information in this file and uses it to:

- poña o aplicativo no Menú principal.

- liste o aplicativo no diálogo Executar aplicativo....

- cree os iniciadores axeitados no menú ou no escritorio

- asocie o nome e a descrición do aplicativo.

- use a icona axeitada.

- recoǹeza o tipo MIME que admite para abir ficheiros.

To add a menu entry for your application, create a desktop file. It should have a unique filename, and there are no length limits so avoid abbreviations and feel free to include brand names. However, don't put spaces or international characters in the file name. For instance, "foocorp-painter-pro.desktop" would be a good filename to choose but "fcpp.desktop" would be a bad name, as would "FooCorp Painter Pro.desktop". The file should be UTF-8 encoded, and should resemble the following template:

    	[Desktop Entry]
    	Encoding=UTF-8
    	Name=FooCorp Painter Pro
    	Exec=foocorp-painter-pro
    	Icon=foocorp-painter-pro
    	Type=Application
    	Categories=Application;

These desktop files contain metadata about your application, and play a central role in integrating the program with the GNOME and other standards compliant desktops. The template presented here is the most basic possible. The file can be linguistically translated so your applications name can appear in the user's native language.

Place this file in the `/usr/share/applications` directory so that it is accessible by everyone, or in `~/.local/share/applications` if you only wish to make it accessible to a single user. Which is used should depend on whether your application is installed systemwide or into a user's home directory. GNOME monitors these directories for changes, so simply copying the file to the right location is enough to register it with the desktop. Note that the `~/.local/share/applications` location is not monitored by versions of GNOME prior to version 2.10 or on Fedora Core Linux, prior to version 2.8. These versions of GNOME follow the now-deprecated vfolder standard, and so desktop files must be installed to `~/.gnome2/vfolders/applications`. This location is not supported by GNOME 2.8 on Fedora Core nor on upstream GNOME 2.10 so for maximum compatibility with deployed desktops, put the file in both locations. Note that the KDE Desktop requires one to run `kbuildsycoca` to force a refresh of the menus.

Each working desktop file needs to follow the same format. A minimal example of a desktop file is shown in . The file is split into sections, each starting with the section descriptor in square brackets. In this example, only one section is shown as that is the essential section to integrating your application to the desktop. Within each section, the part of each line before the equal sign is the key while the second half is the value. An explanation of each line is shown in .

Other than the first line identifying the desktop file, the order of the lines is not important. In , the line `Type=Application` could be the second row, the fifth row, or the last row and the result would be the same.

However, the keys are case sensitive. `Type=Application` is not the same as `type=Application` or `TYPE=Application`.

#### Ficheiro de escritorio de exemplo

    [Desktop Entry]
    Type=Application
    Encoding=UTF-8
    Name=Nome de exemplo de aplicativo
    Comment=O mesmo aplicativo
    Exec=application
    Icon=application.png
    Terminal=false

#### Explicacións liña a liña

Liña | Descrición
--- | ---
`[Desktop Entry]` | A primeira liña de todo ficheiro de escritorio e a sección de cabeceira para identificar o bloque de pares de chaves asociados co escritorio. Necesario para que o escritorio recoñeza o ficheiro correctamente.
`Type=Application` | Dílle ao escritorio que este ficheiro de escritorio pertence a un aplicativo. Outros valores válidos para esta chave son `Ligazón` e `Cartafol`.
`Encoding=UTF-8` | Describe a codificación das entradas neste ficheiro de escritorio.
`Name=Nome de exemplo de aplicativo` | Dalle o nome ao seu aplicativo para o menú principal e calquera iniciador.
`Comment=Un aplicativo de exemplo` | Describe o aplicativo. Usando un consello.
`Exec=application` | A orde que inicia o aplicativo desde consola. Pode ter argumentos.
`Icon=application.png` | O nome da icona asociada con este aplicativo.
`Terminal=false` | Describe se o aplicativo se debería executar nun terminal.

#### Iniciar o seu aplicativo

Se o seu aplicativo pode levar argumentos desde a liña de ordes, pode detallalo usando os campos mostrados na

##### Variábeis de execución

Engadir… | Acepta…
--- | ---
`%f` | un só nome de ficheiro.
`%F` | múltiples nomes de ficheiro.
`%u` | un só URL.
`%U` | múltiples URL.
`%d` | un só cartafol. Usado xunto con `%f` para localizar un ficheiro.
`%D` | múltiples cartafoles. Usado xunto con `%F` para localizar ficheiros.
`%n` | un só nome de ficheiro sen ruta.
`%N` | múltiples ficheiros sen rutas.
`%k` | un URI ou nome de ficheiro local para a localización do ficheiro de escritorio.
`%v` | o nome do dispositivo de entrada.

#### Idiomas estranxeiros

Para crear nomes e comentarios localizados débese engadir liñas adicionais para cada local necesaria. Por exemplo, para engadir a versión en galego do comentario engada a seguinte liña

`Comment[gl]=Exemplo do nome do programa`

Non existen límites no número de traducións para o ficheiro.

Xa que manter unha longa lista de traducións nun ficheiro é moi ineficaz, unha mellor forma de crear estas traducións é usar o paquete intltook. Para obter máis información consulte as páxinas do manual de intltool-extract e intltool-merge.

#### Referencias

Especificación de entradas de escritorio; Especificacións para crear un ficheiro de escritorio.

### Instalar iconas

Na especificouse a icona para este ficheiro como `aplication.png`. Para que esto funcione, precisa poñer ese ficheiro de icona no cartafol correcto.

O escritorio busca iconas no cartafol de temas seleccionado `/user/share/icons`. As iconas dos aplicativos deberían estar dispoñíbeis, cando menos, nunha resolución de 48x48 píxeles. Poña a icona en `/usr/share/iconas/hicolor/48x48/apps/`. Este é o cartafol no que o escritorio busca en caso de qeu non teña unha icona para o seu aplicativo no tema seleccionado. Se ten iconas para temas, pópaos nos cartafoles axeitados.

To better visually integrate with the GNOME desktop, while keeping your application look native when run under KDE, Windows XP or Mac OS X, follow the Tango Style guidelines when creating your artwork. The document explains various aspects of icon design, including colors, lighting and sizes. Some typical workflow and video tutorials are also provided.

#### Referencias

Icon Theme Specification — Describes how to install and look up icons in a themeable way.

Icon Naming Specification — Provides a canonical naming scheme for icon files.

Tango Style Guidelines — Provides description on how to design clean and 'multiplatform' icon artwork.

### Adding MIME types

If your application can open specific MIME types, you need to let the desktop know in the desktop file. For example, if your application can accept PNG files, add the following line into your desktop file:

    MimeType=image/png

Additional Mime types can be added by separating the different types with semicolons.

The system already knows of a large number of MIME types. However, if you are creating one of your own, you need to register your MIME type into the MIME database. In the `/usr/share/mime/packages/` directory, create an XML file with the format as shown in .

#### Sample file for registering a new MIME type

    <?xml version="1.0" encoding="UTF-8"?>
    <mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
       <mime-type type="application/x-example">
         <comment>Tipo de ficheiro de exemplo </comment>
         <magic priority="50">
           <match value="search-string" type="string" offset="10:140"/>
         </magic>
         <glob pattern="*.newextension"/>
       </mime-type>
    </mime-info>

In this example, replace the example MIME type with the name of your MIME type. The magic section searches files for the search string for identification. The glob line uses the suffix of file names for identification.

Because the `magic` command forces the computer to open the files to search for the string, the `glob` command is preferable.

Once your new MIME type is adequately described in the file, run the following in a shell:

    update-mime-database /usr/share/mime

Para obter máis información sobre elixir unha boa extensión MIME e rexistrar o seu tipo MIME, vaia á páxina web da IANA.

#### Referencias

Especificación de información de tipos MIME: Describe o sistema de rexistro de tipos MIME en detalle.

## Integración máis profunda co Escritorio

This chapter contains a list of things which you can do to make your application have better integration with GNOME than the absolute minimum. For example, GNOME is able to display feedback while an application is being launched: you can see how to enable this feedback in . Also, if your software creates documents or other "printable" data, you can install a thumbnailer utility to let the GNOME file manager create thumbnail images specific to your program.

### Notificación de inicio

Ainda que os campos mostrados na fornecen suficiente información para que o escritorio recoñeza o seu aplicativo, existen outros campos que poden ser útiles para o seu caso particular. Un destes campos é startup notification.

Cando a notificación de inicio está activada, o panel e o cursor notifican ao usuario que o aplicativo iniciouse. Cando o aplicativo aparece na pantalla, o panel e o cursor volven ao seu estado normal.

Para permitir que o iniciador saiba que o seu aplicativo admite a notificación de inicio, engada a seguinte liña ao seu ficheiro de escritorio:

`StartupNotify=true`

This command in the desktop file enables the desktop to use whatever startup notification is built in to either your application or your toolkit. Most modern toolkits work transparently with the startup notification system. If you are not using a modern toolkit, the Startup Notification Spec has the details that you need to implement it yourself.

Regardless of toolkit, there is one type of application where you would have to manually handle feedback. Applications with remoting capabilities (where you tell an existing process to open a new window instead of starting a new process) cannot use the built-in mechanism. The value of the DESKTOP_LAUNCH_ID environment has to be passed by your application and have it notify the launching system of your new window. If you are using GTK+, the documentation for `gdk_notify_startup_complete()` has a bit more information.

#### Referencias

Startup Notification Protocol — Describes the low-level details of how startup notification is implemented in the X Window System.

### Instalar un programa xerador de miniaturas

The GNOME file manager, Nautilus, can display little thumbnails tailored for each file instead of generic icons in its file lists. For example, a word processor document can be made to appear as a little version of the first page in the document. This is useful because users can see a small representation of the visible data in their files, which may aid in recalling what file they are looking for. You can make your application create these thumbnails with a few simple steps.

A thumbnailer is a program with no user interface that takes a file and a pixel size as inputs, and it writes a thumbnail for that file. GNOME determines which thumbnailer program to use based on the MIME type of the file for which a thumbnail is to be generated. The mapping between MIME types and thumbnailer programs is stored as a series of GConf keys.

For each MIME type which you want to handle, you have to create a pair of GConf keys:

`/desktop/gnome/thumbnailers/application@x-foo/enable`

  Type: boolean. Determines whether this thumbnailer will be run. You can enable or disable each individual thumbnailer. When you install a new thumbnailer, you should of course make this key's value be true.

`/desktop/gnome/thumbnailers/application@x-foo/command`

  Type: string. The command which GNOME will use when it needs to generate a thumbnail for a file of type application@x-foo. For example, the value could be "`application-x-foo-thumbnailer %i %o %s`". See below for an explanation of the percent signs.

That is, each MIME type requires two GConf keys (`enable` and `command`) under the same path. The path name can be derived from the MIME type name by substituting a "`/`" with "`@`". For example, a thumbnailer for `image/x-my-format` would need two keys: `/desktop/gnome/thumbnailers/image@x-my-format/enable` and `/desktop/gnome/thumbnailers/image@x-my-format/command`.

Dentro da chave `command` GNOME buscará secuencias de porcentaes e os substituirá con valores actuais:

`%i` | Nome do ficheiro de entrada. Isto é o ficheiro que o seu xerador de miniaturas debe ler.
`%u` | URI de entrada. SE o seu xerador de miniatura pode xestionar URI no lugar de ficheiros de nomes planos, use `%u` no lugar de `%i`.
`%o` | Nome do ficheiro de saída. Isto é onde o seu xerador de miniaturas debe escribir a imaxe en miniatura en formato PNG.
`%s` | Size of the thumbnail as a single integer. For example, if this gets substituted with `128`, it means that your thumbnailer should output an image no bigger than 128×128 pixels.

TAnto `%s` como `%u` deben aparecer na súa liña de ordes e `%o` tamén é obrigatoria. A substitución `%s` é opcional, pero recoméndase que o seu xerador de miniaturas a teña en conta.

#### Información adicional

Como un parámetro adicional pode activar a chave booleana `/desktop/gnome/thumbnailers/disable_all` para deactivar a xeración tódalas miniaturas.

## Lista de comprobación da integración

Este apéndice fornece unha lista de comprobación das diversas tarefas presentes ao longo desta guía. Pode usar a lista de comprobación para verificar que o seu software está integrado en GNOME cando menos dunha forma básica, así como un recurso para planificar futuros traballos de integración.

1. Does your application appear in the menus of the GNOME Panel?

2. Does your application have an icon for the panel menus or the desktop? If so, does it have multiple pre-rendered sizes and a scalable SVG version?

3. Se o seu aplicativo pode cargar ou gardar ficheiros, rexistra os tipos MIME que poida manexar?

4. Fornece o seu aplicativo iconas MIME para o xestor de ficheiros?

5. O seu aplicativo admite notificación de inicio, de tal forma que GNOME poida mostrarlle comentarios ao usuario mentras que o seu aplicativo se está iniciando?

6. Se o seu aplicativo crea documentos «imprimíbeis», instala un creador de miniaturas para que o use o xestor de ficheiros?

## Agradecementos

Moitas grazas a JAkub Steiner por fornecer unha folla de setilo bonita para a versión HTML desta guía.