Un élément graphique TextView est en réalité (le plus souvent) une combinaison de trois objets.
En bas se trouve un tampon TextBuffer qui contient le texte lui-même.
Au milieu, nous trouvons l'élément graphique TextView, qui nous permet d'afficher et de modifier le texte du tampon. Il se redimensionne automatiquement en fonction de la quantité de texte qu'il contient.
Since the automatic resizing can make a TextView unwieldy, you normally place it inside of a ScrolledWindow. Despite the name, it's not an actual window in terms of having a title bar and an X button; it's a widget you put on the application you're making, which acts like a window onto a more manageable chunk of a TextView. If the text in the buffer is too big to fit, scrollbars will appear.
Si vous modifiez le texte affiché dans le TextView, vous agissez sur le TextBuffer puisque c'est lui qui contient effectivement le texte. Procédez de la même manière si vous souhaitez connaître le texte saisi par quelqu'un. Cet exemple d'application vous permet de parler à un pingouin (imaginaire) et parcourt le TextBuffer pour voir si vous avez saisi le mot « poisson » quelque part.
Dans la vraie vie, les populations de pingouins déclinent rapidement, à cause du changement climatique qui fait fondre les glaces sur lesquels ils vivent et raréfie les stocks de poissons dont ils se nourrissent. Allez jeter un coup d'œil à Pingus. si vous voulez jouer à un jeu GNOME (un peu stupide) basé sur ce constat.
#!/usr/bin/gjs
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;
Ce sont les bibliothèques que nous devons importer pour faire fonctionner cette application. N'oubliez pas que la ligne qui informe GNOME que nous allons utiliser Gjs doit toujours se trouver au début.
Tout le code de cet exemple tient dans la classe TextViewExample. Le code ci-dessus crée une Gtk.Application pour nos éléments graphiques et la fenêtre qui les contient.
La fonction _buildUI est l'endroit où nous mettons tout le code nécessaire à la création de l'interface utilisateur de l'application. La première étape consiste à créer une Gtk.ApplicationWindow pour y mettre tous nos éléments graphiques.
Pour commencer, créons le Label (étiquette) que le pingouin va utiliser pour dialoguer avec vous. Définissons la propriété de césure du texte de l'étiquette sur wrap (césure) en lui attribuant la valeur « true », mais nous utiliserons une méthode différente sur l'élément graphique TextView lui-même pour avoir un contrôle plus fin.
La première étape consiste à créer un élément graphique TextBuffer pour y placer les mots. Ensuite, nous créons l'élément TextView et nous lui indiquons d'utiliser le TextBuffer comme tampon. Nous le paramétrons aussi pour qu'il soit modifiable (editable), car nous voulons pouvoir y saisir d'autres choses.
The wrap_mode property lets you select from four different WrapModes. Gtk.WrapMode.CHAR, for instance, starts wrapping around in the middle of a word if you keep typing when it gets to the edge. Most people are probably used to Gtk.WrapMode.WORD, which will automatically put the word you're typing on the next line if it gets to be too long.
Here we create a ScrolledWindow, and set it to automatically scroll if it gets to be too big horizontally or vertically. We also give it a nice-looking ETCHED_IN border. After that, we put our TextView inside, and tell the ScrolledWindow to give us a viewport onto it.
Le premier Grid (grille) que nous avons créé ne contient que l'étiquette et la ScrolledWindow.
Nous créons un Button (bouton) pour envoyer votre message au pingouin et un nouveau Grid (grille) qui contient l'autre grille en haut et le bouton en bas. Le bouton comporte une marge (margin) dans sa partie supérieure, de telle sorte qu'il n'est pas collé contre la ScrolledWindow.
Enfin, nous relions la grille principale à la fenêtre, puis indiquons à la fenêtre de s'afficher avec son contenu quand l'application est lancée.
Nous utilisons ici quelques fonctions JavaScript de base pour que le pingouin dise quelque chose au hasard. Les pingouins apprécient le poisson et nous allons donc le faire répondre quand on prononce le mot « fish » (poisson). Pour cela, nous appliquons la méthode JavaScript de correspondance d'objets chaîne de caractères sur le texte
Comme nous voulons effacer le TextBuffer après chaque clic sur « Sent » (Envoyer), nous paramétrons le
Enfin, nous créons une nouvelle instance de la classe TextViewExample que nous venons de terminer et démarrons l'application.
#!/usr/bin/gjs
imports.gi.versions.Gtk = '3.0';
const Gtk = imports.gi.Gtk;
class TextViewExample {
// Create the application itself
constructor() {
this.application = new Gtk.Application({
application_id: 'org.example.jstextview'
});
// 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 windows 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,
title: "Talk to a Penguin",
default_height: 400,
default_width: 440,
border_width: 20 });
// Create a label for the penguin to talk to you
this._penguin = new Gtk.Label ({
height_request: 180,
width_request: 400,
label: "Squaaaak?",
wrap: true });
// Create a textview for you to talk to the penguin
this.buffer = new Gtk.TextBuffer();
this._textView = new Gtk.TextView ({
buffer: this.buffer,
editable: true,
wrap_mode: Gtk.WrapMode.WORD });
// Create a "scrolled window" to put your textview in so it will scroll
this._scrolled = new Gtk.ScrolledWindow ({
hscrollbar_policy: Gtk.PolicyType.AUTOMATIC,
vscrollbar_policy: Gtk.PolicyType.AUTOMATIC,
shadow_type: Gtk.ShadowType.ETCHED_IN,
height_request: 180,
width_request: 400, });
// Put the textview into the scrolled window
this._scrolled.add_with_viewport (this._textView);
// Create a grid to organize them in
this._grid = new Gtk.Grid ({
halign: Gtk.Align.CENTER,
valign: Gtk.Align.CENTER });
// Put the label and textview in the grid one on top of the other
this._grid.attach (this._penguin, 0, 0, 1, 1);
this._grid.attach (this._scrolled, 0, 1, 1, 1);
// Create a button to send your message to the penguin
this._send = new Gtk.Button ({
halign: Gtk.Align.END,
margin_top: 20,
label: "Send" });
this._send.connect ('clicked', this._chat.bind(this));
// Create a grid that will have the other grid on top and the button on bottom
this._mainGrid = new Gtk.Grid ({
halign: Gtk.Align.CENTER,
valign: Gtk.Align.CENTER });
// Add the other grid and the button to the main grid
this._mainGrid.attach (this._grid, 0, 0, 1, 1);
this._mainGrid.attach (this._send, 0, 1, 1, 1);
// Attach the main grid to the window
this._window.add (this._mainGrid);
// Show the window and all child widgets
this._window.show_all();
}
_chat() {
// Create a random number to determine what the penguin says
this.number = Math.floor ((Math.random() * 3) + 1);
// Did you actually say anything?
if (this.buffer.text) {
// Did you mention fish?
if (this.buffer.text.match (/fish/gi)) {
// Have the penguin squaak about fish
if (this.number == 1)
this._penguin.set_label ("FISH!");
else if (this.number == 2)
this._penguin.set_label ("Fish fish fish fish. Fish!");
else
this._penguin.set_label ("Fish? Fish fish fish. Fish fish. FISH!");
}
// I guess you didn't mention fish
else {
// Have the penguin talk about penguinny stuff
if (this.number == 1)
this._penguin.set_label ("SQUAAK!");
else if (this.number == 2)
this._penguin.set_label ("Ork ork ork ork squaak. Squaak squaak! *waves flippers*");
else
this._penguin.set_label ("Ork ork ork ork ork?");
}
}
// Clear the buffer
this.buffer.text = "";
// Give focus back to the textview so you don't have to click it again
this._textView.has_focus = true;
}
};
// Run the application
let app = new TextViewExample ();
app.application.run (ARGV);
Gtk.Application
Gtk.ApplicationWindow
Gtk.Button
Gtk.Grid
Gtk.Label
Gtk.RadioButton
Gtk.ScrolledWindow
Gtk.TextBuffer
Gtk.TextView