File: hello-world.js.page

package info (click to toggle)
gnome-devel-docs 40.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 79,188 kB
  • sloc: javascript: 2,514; xml: 2,407; ansic: 2,229; python: 1,854; makefile: 805; sh: 499; cpp: 131
file content (322 lines) | stat: -rw-r--r-- 13,912 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
<?xml version="1.0" encoding="utf-8"?>
<page xmlns="http://projectmallard.org/1.0/" xmlns:its="http://www.w3.org/2005/11/its" xmlns:xi="http://www.w3.org/2001/XInclude" type="guide" style="task" id="hello-world.js" xml:lang="es">

  <info>
  <title type="text">Hola mundo (JavaScript)</title>
    <link type="guide" xref="beginner.js#tutorials" group="#first"/>

    <revision version="0.1" date="2013-06-17" status="review"/>

    <credit type="author copyright">
      <name>Susanna Huhtanen</name>
      <email its:translate="no">ihmis.suski@gmail.com</email>
      <years>2012</years>
    </credit>
    <credit type="editor">
      <name>Tiffany Antopolski</name>
      <email its:translate="no">tiffany.antopolski@gmail.com</email>
    </credit>

    <desc>Una aplicación «Hola mundo» básica</desc>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Daniel Mustieles</mal:name>
      <mal:email>daniel.mustieles@gmail.com</mal:email>
      <mal:years>2011 - 2020</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Nicolás Satragno</mal:name>
      <mal:email>nsatragno@gmail.com</mal:email>
      <mal:years>2012 - 2013</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Jorge González</mal:name>
      <mal:email>jorgegonz@svn.gnome.org</mal:email>
      <mal:years>2011</mal:years>
    </mal:credit>
  </info>

  <title>Cómo construir, instalar y crear un <file>tar.xz</file> de un programa Hola mundo</title>
    <media type="image" mime="image/png" style="floatend" src="media/hello-world.png"/>
    <synopsis>
      <p>Este tutorial le demostrará cómo:</p>
      <list style="numbered">
        <item><p>crear una pequeña aplicación «Hola, mundo» usando JavaScript y GTK+</p></item>
        <item><p>hacer el archivo <file>.desktop</file></p></item>
        <item><p>configurar el sistema de construcción</p></item>
      </list>
    </synopsis>



  <links type="section"/>

  <section id="HelloWorld"><title>Crear el programa</title>

    <links type="section"/>

    <section id="script"><title>Script para ejecutar la aplicación</title>
      <p>Esta tiene que ser la primera línea de su script:</p>
      <code mime="application/javascript">#!/usr/bin/gjs</code>
      <p>Le dice al script que use <link href="https://live.gnome.org/Gjs/">Gjs</link>. Gjs es una vinculación de JavaScript para GNOME.</p>
    </section>


    <section id="imports"><title>Bibliotecas que importar</title>
      <code mime="application/javascript">const Lang = imports.lang;

imports.gi.versions.Gtk = '3.0'
const Gtk = imports.gi.Gtk;</code>
      <p>Para que su script funcione con GNOME, se deben importar las bibliotecas de GNOME mediante introspección de GObject. En este caso, se están importando las vinculaciones de lenguaje y GTK+, la biblioteca que contiene los widgets gráficos usados para crear aplicaciones de GNOME.</p>
    </section>

    <section id="mainwindow"><title>Crear la ventana principal de la aplicación</title>
      <code mime="application/javascript">const Application = new Lang.Class({
    //A Class requires an explicit Name parameter. This is the Class Name.
    Name: 'Application',

    //create the application
    _init: function() {
        this.application = new Gtk.Application();

       //connect to 'activate' and 'startup' signals to handlers.
       this.application.connect('activate', Lang.bind(this, this._onActivate));
       this.application.connect('startup', Lang.bind(this, this._onStartup));
    },

    //create the UI
    _buildUI: function() {
        this._window = new Gtk.ApplicationWindow({ application: this.application,
                                                   title: "Hello World!" });
    },

    //handler for 'activate' signal
    _onActivate: function() {
        //show the window and all child widgets
        this._window.show_all();
    },

    //handler for 'startup' signal
    _onStartup: function() {
        this._buildUI();
    }
});
</code>

    <p>«GtkApplication» inicializa GTK+. También conecta el botón <gui>x</gui> que se genera automáticamente junto con la ventana a la señal «destroy».</p>
    <p>Se puede empezar a construir la primera ventana. Esto se hace creando una variable llamada <var>_window</var> y asignándole una «Gtk.ApplicationWindow» nueva.</p>
    <p>Se le asignara una propiedad llamada <var>title</var>. El título puede ser la cadena que quiera pero, para estar seguro, es conveniente que tenga una codificación UTF-8.</p>
    <p>Ya tiene una ventana que contiene un título y un botón «cerrar» que funciona. Ahora, añada el texto «Hola mundo».</p>
    </section>

    <section id="label"><title>Etiqueta para la ventana</title>
      <code mime="application/javascript">// Add a label widget to your window
this.label = new Gtk.Label({ label: "Hello World" });
this._window.add(this.label);
this._window.set_default_size(200, 200);</code>

      <p>Una etiqueta de texto es uno de los widgets de GTK+ que puede usar si importó la biblioteca GTK+. Para usarlo, cree una variable nueva llamada «label» y asígnele una Gtk.Label nueva. Después dele propiedades dentro de las llaves «{}». En este caso, se está estableciendo el texto que la etiqueta contendrá. Finalmente, se crea y ejecuta la aplicación:</p>

      <code mime="application/javascript">//run the application
let app = new Application();
app.application.run(ARGV);</code>

      <p>«Gtk.ApplicationWindow» sólo puede contener un widget a la vez. Para construir programas más elaborados necesita crear un widget contenedor como «Gtk.Grid» dentro de la ventana, y después añadirle los otros.</p>
   </section>


    <section id="js"><title>hello-world.js</title>
      <p>El archivo completo:</p>
      <code mime="application/javascript" style="numbered">#!/usr/bin/gjs

const Lang = imports.lang;

imports.gi.versions.Gtk = '3.0'
const Gtk = imports.gi.Gtk;

class Application {

    //create the application
    constructor() {
        this.application = new Gtk.Application();

       //connect to 'activate' and 'startup' signals to handlers.
       this.application.connect('activate', this._onActivate.bind(this));
       this.application.connect('startup', this._onStartup.bind(this));
    }

    //create the UI
    _buildUI() {
        this._window = new Gtk.ApplicationWindow({ application: this.application,
                                                   title: "Hello World!" });
        this._window.set_default_size(200, 200);
        this.label = new Gtk.Label({ label: "Hello World" });
        this._window.add(this.label);
    }

    //handler for 'activate' signal
    _onActivate() {
        //show the window and all child widgets
        this._window.show_all();
    }

    //handler for 'startup' signal
    _onStartup() {
        this._buildUI();
    }
};

//run the application
let app = new Application();
app.application.run(ARGV);
</code>
    </section>

    <section id="terminal"><title>Ejecutar la aplicación desde la terminal</title>
      <p>Para ejecutar esta aplicación, primero guárdela como hello-world.js. Luego, abra una terminal, vaya a la carpeta donde está la aplicación y ejecute:</p>
      <screen><output style="prompt">$ </output><input>gjs hello-world.js</input></screen>
    </section>
  </section>



  <section id="desktop.in"><title>El archivo <file>.desktop.in</file></title>
      <p>Ejecutar aplicaciones desde la terminal es útil al principio del proceso de crear la aplicación. Para tener una <link href="https://developer.gnome.org/integration-guide/stable/mime.html.en">integración con la aplicación</link> completa en GNOME 3, se necesita un lanzador en el escritorio. Para esto, necesita crear un archivo <file>.desktop</file>. El archivo «.desktop» describe el nombre de la aplicación, el icono que usa y varios campos de integración. Puede encontrar una descripción de los archivos <file>.desktop</file> <link href="http://developer.gnome.org/desktop-entry-spec/">aquí</link>. El archivo <file>.desktop.in</file> creará el <file>.desktop</file>.</p>

  <note>
       <p>Antes de continuar, guarde nuevamente <file>hello-world.js</file> como <file>hello-world</file>. Después ejecute esto en la terminal:</p>
      <screen><output style="prompt">$ </output><input>chmod +x hello-world</input></screen>
  </note>

    <p>El ejemplo muestra los requerimientos mínimos de un archivo <code>.desktop.in</code>.</p>
    <code mime="text/desktop" style="numbered">[Desktop Entry]
Version=1.0
Encoding=UTF-8
Name=Hello World
Comment=Say Hello
Exec=@prefix@/bin/hello-world
Icon=application-default-icon
Terminal=false
Type=Application
StartupNotify=true
Categories=GNOME;GTK;Utility;
</code>

    <p>Guarde el archivo como <file>hello-world.desktop.in</file>. Ahora se verán algunas partes del archivo <code>.desktop.in</code>.</p>
    <terms>
      <item><title>Name</title><p>El nombre de la aplicación.</p></item>
      <item><title>Comment</title><p>Una descripción corta de la aplicación.</p></item>
      <item><title>Exec</title><p>Especifica un comando que ejecutar cuando se elige la aplicación en el menú. En este ejemplo, «exec» sólo indica dónde encontrar el archivo <code>hello-world</code> y el archivo se hace cargo del resto.</p></item>
      <item><title>Terminal</title><p>Especifica si el comando del campo «Exec» se ejecuta en una ventana de la terminal.</p></item>
    </terms>

    <p>Para incluir su aplicación en la categoría correcta, debe añadir las categorías necesarias a la línea «Categories». Puede encontrar más información sobre las distintas categorías en la <link href="http://standards.freedesktop.org/menu-spec/latest/apa.html">especificación del menú</link>.</p>
    <p>En este ejemplo se ha usado un icono existente. Para usar un icono personalizado, necesita un archivo «.svg» con su icono guardado en <file>/usr/share/icons/hicolor/scalable/apps</file>. Escriba el nombre del archivo del icono en el archivo «.desktop.in», en la línea 7. Puede obtener más información sobre los iconos en <link href="https://wiki.gnome.org/Initiatives/GnomeGoals/AppIcon">Instalar iconos para temas</link>, <link href="https://live.gnome.org/GnomeGoals/AppIcon">Instalar iconos para temas</link> y en <link href="http://freedesktop.org/wiki/Specifications/icon-theme-spec">freedesktop.org: especificaciones/icon-theme-spec</link>.</p>
  </section>

  <section id="autotools"><title>El sistema de construcción</title>
    <p>Para que su aplicación forme parte realmente del sistema GNOME 3 debe instalarla con la ayuda de autotools. La construcción autotools instalará todos los archivos necesarios en las ubicaciones correctas.</p>
    <p>Para esto deberá tener los siguientes archivos:</p>
    <links type="section"/>

      <section id="autogen"><title>autogen.sh</title>
        <code mime="application/x-shellscript" style="numbered">#!/bin/sh

set -e

test -n "$srcdir" || srcdir=`dirname "$0"`
test -n "$srcdir" || srcdir=.

olddir=`pwd`
cd "$srcdir"

# This will run autoconf, automake, etc. for us
autoreconf --force --install

cd "$olddir"

if test -z "$NOCONFIGURE"; then
  "$srcdir"/configure "$@"
fi
</code>

      <p>Una vez que el archivo <file>autogen.sh</file> esté listo y guardado, ejecute:</p>
      <screen><output style="prompt">$ </output><input>chmod +x autogen.sh</input></screen>
    </section>


    <section id="makefile"><title>Makefile.am</title>
      <code mime="application/x-shellscript" style="numbered"># The actual runnable program is set to the SCRIPTS primitive.
# # Prefix bin_ tells where to copy this
bin_SCRIPTS = hello-world
# # List of files to be distributed
EXTRA_DIST =  \
	$(bin_SCRIPTS)
#
#     # The desktop files
desktopdir = $(datadir)/applications
desktop_DATA = \
	hello-world.desktop
</code>
    </section>


    <section id="configure"><title>configure.ac</title>
      <code mime="application/x-shellscript" style="numbered"># This file is processed by autoconf to create a configure script
AC_INIT([Hello World], 1.0)
AM_INIT_AUTOMAKE([1.10 no-define foreign dist-xz no-dist-gzip])
AC_CONFIG_FILES([Makefile hello-world.desktop])
AC_OUTPUT
</code>
    </section>


    <section id="readme"><title>README</title>
       <p>Información que los usuarios deben leer primero. Este archivo puede estar vacío.</p>

       <p>Cuando tenga los archivos <file>hello-world</file>, <file>hello-world.desktop.in</file>, <file>Makefile.am</file>, <file>configure.ac</file> y <file>autogen.sh</file> con la información y los permisos correctos, cree el archivo <file>README</file> con instrucciones para la instalación. A continuación se muestra un ejemplo de a qué se deben parecer las instrucciones de un archivo README adecuado.</p>
      <code mime="text/readme" style="numbered">Para construir e instalar este programa ejecute estos comandos desde una terminal:

./autogen.sh --prefix=/home/%USER/.local
make install

-------------
Al ejecutar la primera línea se crean los siguientes archivos:

aclocal.m4
autom4te.cache
config.log
config.status
configure
hello-world.desktop
install-sh
missing
Makefile.in
Makefile

Al ejecutar «make install», se instala la aplicación en /home/usuario/.local/bin
y se instala el archivo helloWorld.desktop en /home/usuario/.local/share/applications

Ahora puede ejecutar la aplicación escribiendo «Hello World» en la vista general.

----------------
Para desinstalarla, escriba:

make uninstall

----------------
Para crear un archivador tar escriba:

make distcheck

Esto creará el archivo hello-world-1.0.tar.xz

</code>
    </section>

    <!-- TODO: How to make a custom icon with autotools -->

  </section>
</page>