Statusbar (JavaScript) Taryn Fox jewelfox@fursona.net 2012 Mostrar notificaciones en una barra de estado dedicada Daniel Mustieles daniel.mustieles@gmail.com 2011 - 2017 Nicolás Satragno nsatragno@gmail.com 2012 - 2013 Jorge González jorgegonz@svn.gnome.org 2011 Statusbar

Esta barra de estado registra cuántas veces se pulsó un botón. Las aplicaciones como gedit usan barras de estado para mostrar información a simple vista, y mostrar notificaciones sin interrumpir al usuario.

Los mensajes que se muestran en una barra de estado van a la parte superior de su pila, y pueden extraerse para mostrar el siguiente más reciente. También puede limpiar todos los mensajes de un tipo específico de una vez. Esta aplicación de ejemplo demuestra estas funciones.

Bibliotecas que importar #!/usr/bin/gjs const Gio = imports.gi.Gio; const Gtk = imports.gi.Gtk; const Lang = imports.lang;

Estas son las bibliotecas que necesita importar para que esta aplicación se ejecute. Recuerde que la línea que le dice a GNOME que está usando Gjs siempre tiene que ir al principio.

Crear la ventana de la aplicación const StatusbarExample = new Lang.Class({ Name: 'Statusbar Example', // Create the application itself _init: function() { this.application = new Gtk.Application({ application_id: 'org.example.jsstatusbar', flags: Gio.ApplicationFlags.FLAGS_NONE }); // Connect 'activate' and 'startup' signals to the callback functions this.application.connect('activate', Lang.bind(this, this._onActivate)); this.application.connect('startup', Lang.bind(this, this._onStartup)); }, // Callback function for 'activate' signal presents window when active _onActivate: function() { this._window.present(); }, // Callback function for 'startup' signal builds the UI _onStartup: function() { this._buildUI (); },

Todo el código de este ejemplo va en la clase «StatusBarExample». El código anterior crea una Gtk.Application para que vayan los widgets y la ventana.

// Build the application's UI _buildUI: function() { // Create the application window this._window = new Gtk.ApplicationWindow({ application: this.application, window_position: Gtk.WindowPosition.CENTER, default_height: 120, default_width: 300, title: "Button Clicker"}); // Create a paned interface this._panes = new Gtk.Paned ({ orientation: Gtk.Orientation.VERTICAL });

La función «_buildUI» es donde se pone todo el código para crear la interfaz de usuario de la aplicación. El primer paso es crear una Gtk.ApplicationWindow nueva para poner dentro todos los widgets. El siguiente paso es crear una interfaz «Gtk.Paned» orientada verticalmente, para dividir la ventana en dos secciones. De esta manera la barra de estado se parece a aquellas usadas en otras aplicaciones, y permanece en la parte inferior de la ventana, incluso si el usuario la redimensiona.

Crear los botones // Create the main button this._clickMe = new Gtk.Button ({ label: "Click Me!" }); this._clickMe.connect ("clicked", Lang.bind (this, this._clicked)); // Create the back button this._backButton = new Gtk.Button ({ label: "gtk-go-back", use_stock: true }); this._backButton.connect ("clicked", Lang.bind (this, this._back)); // Create the clear button this._clearButton = new Gtk.Button ({ label: "gtk-clear", use_stock: true }); this._clearButton.connect ("clicked", Lang.bind (this, this._clear));

Este código crea los tres Gtk.Buttons que se usarán para empujar un mensaje nuevo a la barra de tareas, extraer el último, y limpiar todos los mensajes existentes. Los botones «back» y «clear» son botones del almacén, que se traducen automáticamente a cualquier idioma que GNOME soporte.

// Put the buttons in a grid this._grid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER }); this._grid.attach (this._backButton, 0, 0, 1, 1); this._grid.attach_next_to (this._clickMe, this._backButton, Gtk.PositionType.RIGHT, 1, 1); this._grid.attach_next_to (this._clearButton, this._clickMe, Gtk.PositionType.RIGHT, 1, 1); // Put the grid in a large frame that fills most of the window this._topFrame = new Gtk.Frame ({ border_width: 20, height_request: 90, width_request: 300}); this._topFrame.add (this._grid);

Este código crea la Gtk.Grid que se usará para organizar los botones, y le adjunta los botones en orden. Después crea un Gtk.Frame que ocupará la mayor parte de la ventana y que tiene bastante relleno alrededor de los botones, y añade la rejilla al cuadro. Tenga en cuenta que todavía se necesita poner el cuadro en la interfaz con paneles, y después añadirlo a la «ApplicationWindow».

Crear la barra de estado // Create the statusbar this._statusbar = new Gtk.Statusbar(); // Keep track of the number of times the button has been clicked this.Clicks = 0; this.ContextID = this._statusbar.get_context_id ("Number of Clicks"); // Give the statusbar an initial message this._statusbar.push (this.ContextID, "Number of clicks: " + this.Clicks); // Put the statusbar in its own frame at the bottom this._barFrame = new Gtk.Frame ({ height_request: 30 }); this._barFrame.add (this._statusbar);

Aquí se crea la «Gtk.Statusbar», y se le empuja un mensaje para comenzar. Después se le da su propio cuadro estrecho en la parte inferior de la ventana.

Cada mensaje necesita tener un ID de contexto, que es un valor entero que puede obtener de la barra de estado con la función «get_context_id()». Su único parámetro es el valor de la cadena que usa para describir ese ID de contexto particular. Normalmente, obtendría un ID de contexto nuevo para distintos tipos de mensajes, para que pueda usar la función «remove()» para eliminar un mensaje específico y no sólo el más reciente de la pila. Sin embargo, este es un ejemplo simple con sólo un tipo de mensaje, por lo que sólo se usa uno para todo.

Se usa la función «push()» para empujar un mensaje nuevo a la pila. Su primer parámetro es el ID de contexto, y el segundo es el mensaje.

// Assemble the frames into the paned interface this._panes.pack1 (this._topFrame, true, false); this._panes.pack2 (this._barFrame, false, false); // Put the panes into the window this._window.add (this._panes); // Show the window and all child widgets this._window.show_all(); },

Este código termina de crear la ventana, empaquetando los marcos en el panel, añadiéndolo a la ventana, y diciéndole a la ventana que muestre todos los widgets hijos.

Funciones para interactuar con la barra de estado _clicked: function() { // Increment the number of clicks by 1 this.Clicks++; // Update the statusbar with the new number of clicks this._statusbar.push (this.ContextID, "Number of clicks: " + this.Clicks); }, _back: function () { // If there have been any clicks, decrement by 1 and remove last statusbar update if (this.Clicks > 0 ) { this.Clicks--; this._statusbar.pop (this.ContextID); }; }, _clear: function () { // Reset the number of clicks this.Clicks = 0; // Wipe out all the messages pushed to the statusbar this._statusbar.remove_all (this.ContextID); // Reset the statusbar's message this._statusbar.push (this.ContextID, "Number of clicks: " + this.Clicks); } });

Aquí están funciones que muestran cómo empujar un mensaje a la pila, extraer el que está arriba de todo, y limpiar todos los mensajes de un ID de contexto particular. La función «pop()» sólo toma un parámetro, que es el ID de contexto para el tipo de mensaje del que quiere extraer el más reciente. La función «remove_all()» funciona de la misma manera, excepto que elimina todos los mensajes de ese tipo de la pila.

// Run the application let app = new StatusbarExample (); app.application.run (ARGV);

Finalmente, se crea una instancia nueva de la clase «StatusbarExample» terminada, y se ejecuta la aplicación.

Código de ejemplo completo #!/usr/bin/gjs imports.gi.versions.Gtk = '3.0'; const Gio = imports.gi.Gio; const Gtk = imports.gi.Gtk; class StatusbarExample { // Create the application itself constructor() { this.application = new Gtk.Application({ application_id: 'org.example.jsstatusbar', flags: Gio.ApplicationFlags.FLAGS_NONE }); // Connect 'activate' and 'startup' signals to the callback functions this.application.connect('activate', this._onActivate.bind(this)); this.application.connect('startup', this._onStartup.bind(this)); } // Callback function for 'activate' signal presents window when active _onActivate() { this._window.present(); } // Callback function for 'startup' signal builds the UI _onStartup() { this._buildUI(); } // Build the application's UI _buildUI() { // Create the application window this._window = new Gtk.ApplicationWindow({ application: this.application, window_position: Gtk.WindowPosition.CENTER, default_height: 120, default_width: 300, title: "Button Clicker"}); // Create a paned interface this._panes = new Gtk.Paned ({ orientation: Gtk.Orientation.VERTICAL }); // Create the main button this._clickMe = new Gtk.Button ({ label: "Click Me!" }); this._clickMe.connect ("clicked", this._clicked.bind(this)); // Create the back button this._backButton = new Gtk.Button ({ label: "gtk-go-back", use_stock: true }); this._backButton.connect ("clicked", this._back.bind(this)); // Create the clear button this._clearButton = new Gtk.Button ({ label: "gtk-clear", use_stock: true }); this._clearButton.connect ("clicked", this._clear.bind(this)); // Put the buttons in a grid this._grid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER }); this._grid.attach (this._backButton, 0, 0, 1, 1); this._grid.attach_next_to (this._clickMe, this._backButton, Gtk.PositionType.RIGHT, 1, 1); this._grid.attach_next_to (this._clearButton, this._clickMe, Gtk.PositionType.RIGHT, 1, 1); // Put the grid in a large frame that fills most of the window this._topFrame = new Gtk.Frame ({ border_width: 20, height_request: 90, width_request: 300}); this._topFrame.add (this._grid); // Create the statusbar this._statusbar = new Gtk.Statusbar(); // Keep track of the number of times the button has been clicked this.Clicks = 0; this.ContextID = this._statusbar.get_context_id ("Number of Clicks"); // Give the statusbar an initial message this._statusbar.push (this.ContextID, "Number of clicks: " + this.Clicks); // Put the statusbar in its own frame at the bottom this._barFrame = new Gtk.Frame ({ height_request: 30 }); this._barFrame.add (this._statusbar); // Assemble the frames into the paned interface this._panes.pack1 (this._topFrame, true, false); this._panes.pack2 (this._barFrame, false, false); // Put the panes into the window this._window.add (this._panes); // Show the window and all child widgets this._window.show_all(); } _clicked() { // Increment the number of clicks by 1 this.Clicks++; // Update the statusbar with the new number of clicks this._statusbar.push (this.ContextID, "Number of clicks: " + this.Clicks); } _back() { // If there have been any clicks, decrement by 1 and remove last statusbar update if (this.Clicks > 0 ) { this.Clicks--; this._statusbar.pop (this.ContextID); }; } _clear() { // Reset the number of clicks this.Clicks = 0; // Wipe out all the messages pushed to the statusbar this._statusbar.remove_all (this.ContextID); // Reset the statusbar's message this._statusbar.push (this.ContextID, "Number of clicks: " + this.Clicks); } }; // Run the application let app = new StatusbarExample (); app.application.run (ARGV);
Documentación en profundidad

Gtk.Application

Gtk.ApplicationWindow

Gtk.Button

Gtk.Frame

Gtk.Paned

Gtk.Statusbar