# TextView (Javascript)

Taryn Fox
jewelfox@fursona.net 2012
En textredigerare med flera rader
Sebastian Rasmussen
sebras@gmail.com 2019
Anders Jonsson
anders.jonsson@norsjovallen.se 2021

# TextView

A TextView is really (or at least usually) a nested set of three objects.

Längst ner är en TextBuffer. Den innehåller själva texten.

I mitten finns en TextView, som är en komponent som låter dig se och redigera texten i bufferten. Den ändrar automatiskt storlek på sig själv beroende på hur mycket text det är.

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.

If you want to change what text is displayed in the TextView, you act on the TextBuffer, since it's what actually holds the text. The same goes for if you want to see what text someone typed in. This sample application lets you talk to a (make-believe) penguin, and checks the TextBuffer to see if you typed the word "fish" anywhere in it.

Pingvinpopulationer i verkligheten minskar snabbt, eftersom klimatförändring smälter isen som de lever på och dödar fisken som de äter. Om du vill spela ett (aningen fånigt) GNOME-spel som är baserat på de premisserna kan du ta en titt på Pingus.

# Bibliotek att importera

#!/usr/bin/gjs

const Gtk = imports.gi.Gtk; const Lang = imports.lang;

Detta är biblioteken som vi behöver importera för att detta program ska köras. Kom ihåg att raden som säger till GNOME att vi använder Gjs alltid behöver vara först.

# Skapa programfönstret

const TextViewExample = new Lang.Class ({ Name: 'TextView-exempel',

// Skapa programmet i sig _init: function () { this.application = new Gtk.Application ({ application_id: 'org.example.jstextview' });

// Anslut ”activate”- och ”startup”-signaler till återanropsfunktionerna this.application.connect('activate', Lang.bind(this, this._onActivate)); this.application.connect('startup', Lang.bind(this, this._onStartup)); },

// Återanropsfunktion för ”activate”-signal visar fönster när den aktiveras _onActivate: function () { this._window.present (); },

// Återanropsfunktion för ”startup”-signal bygger användargränssnittet _onStartup: function () { this._buildUI (); },

All kod för detta exempel hamnar i klassen TextViewExample. Koden ovan skapar en Gtk.Application att ha våra komponenter och fönstret i.

// Bygg programmets användargränssnitt _buildUI: function () {

// Skapa programfönstret this._window = new Gtk.ApplicationWindow ({ application: this.application, window_position: Gtk.WindowPosition.CENTER, title: "Prata med en pingvin", default_height: 400, default_width: 440, border_width: 20 });

_buildUI-funktionen är var vi stoppar all kod för att skapa programmets användargränssnitt. Det första steget är att skapa ett nytt Gtk.ApplicationWindow att stoppa alla våra komponenter i.

# Skapa vår TextView

// 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 });

Our first step in this example is to create the Label that the penguin will use to talk to you. We set the text in it to wrap by setting its wrap property to true, but we'll use a different method on the TextView itself that allows for more fine-grained control.

// Skapa en textvy så att du kan prata med pingvinen this.buffer = new Gtk.TextBuffer(); this._textView = new Gtk.TextView ({ buffer: this.buffer, editable: true, wrap_mode: Gtk.WrapMode.WORD });

Our first step is to create a TextBuffer to put the words into. After that we create the TextView, and tell it to use the TextBuffer we created as its buffer. We also set it to be editable, since we want to be able to type new things in.

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.

// 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);

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.

# Skapa resten av användargränssnittet

// Skapa ett rutnät att organisera dem i this._grid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER });

// Stoppa etiketten och textvyn i rutnätet, den ena ovanpå den andra this._grid.attach (this._penguin, 0, 0, 1, 1); this._grid.attach (this._scrolled, 0, 1, 1, 1);

Den första Grid vi skapar har bara vår Label och vårt ScrolledWindow i sig.

// Skapa en knapp för att skicka ditt meddelande till pingvinen this._send = new Gtk.Button ({ halign: Gtk.Align.END, margin_top: 20, label: "Skicka" }); this._send.connect ('clicked', Lang.bind (this, this._chat));

// Skapa ett rutnät som kommer ha det andra rutnätet överst och knappen nederst this._mainGrid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER });

// Lägg till det andra rutnätet och knappen till huvudrutnätet this._mainGrid.attach (this._grid, 0, 0, 1, 1); this._mainGrid.attach (this._send, 0, 1, 1, 1);

Vi skapar en Button för att skicka ditt meddelande till pingvinen, och en ny Grid som har den andra överst och vår Button nederst. Denna Button har en marginal uppåt så att den inte trycks upp mot vårt ScrolledWindow.

// Fäst huvudrutnätet vid fönstret this._window.add (this._mainGrid);

// Visa fönstret och alla barnkomponenter this._window.show_all(); },

Slutligen fäster vi vår huvud-Grid till fönstret, och säger sedan till fönstret och allting i det att bli synliga då programmet körs.

# Funktion som hanterar pingvinens svar

_chat: function () {

// 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;

}

});

Here we use some basic JavaScript functions to have the penguins say something random. Penguins like fish, though, so if you mention fish we want the penguin to respond to that. To do that, we use the JavaScript String object's match method on this.buffer.text, which returns the contents of our TextBuffer.

Since we want to clear out the TextBuffer after each time you click Send, we set this.buffer.text to contain an empty string afterwards. Then we return focus to our TextView, so that you can keep typing without having to click on it beforehand.

// Kör programmet let app = new TextViewExample (); app.application.run (ARGV);

Slutligen skapar vi en ny instans av den slutförda TextViewExample-klassen, och startar programmet.

# Fullständigt kodexempel

#!/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);

# Djupgående dokumentation

Gtk.Application

Gtk.ApplicationWindow

Gtk.Button

Gtk.Grid

Gtk.Label

Gtk.RadioButton

Gtk.ScrolledWindow

Gtk.TextBuffer

Gtk.TextView