1<?xml version='1.0' encoding='UTF-8'?>
2<page xmlns="http://projectmallard.org/1.0/"
3      xmlns:its="http://www.w3.org/2005/11/its"
4      xmlns:xi="http://www.w3.org/2001/XInclude"
5      type="guide" style="task"
6      id="switch.js">
7  <info>
8  <title type="text">Switch (JavaScript)</title>
9    <link type="guide" xref="beginner.js#buttons"/>
10    <revision version="0.1" date="2012-06-18" status="draft"/>
11
12    <credit type="author copyright">
13      <name>Taryn Fox</name>
14      <email its:translate="no">jewelfox@fursona.net</email>
15      <years>2012</years>
16    </credit>
17
18    <desc>A sliding switch that can be flipped on and off</desc>
19  </info>
20
21  <title>Switch</title>
22  <media type="image" mime="image/png" src="media/switchanimals.png"/>
23  <p>A Switch has two positions, on and off. This example shows how you can use multiple switches together to control which <link xref="image.js">Image</link> is shown in the window. The pictures used in this example <link href="https://live.gnome.org/TarynFox?action=AttachFile&amp;do=get&amp;target=Animal+Photos.zip">can be downloaded here</link>.</p>
24  <note><p>The window will contain a "broken image" icon instead of a picture if picture files named <file>redfox.png</file>, <file>muteswan.png</file>, <file>fruitbat.png</file>, and <file>gentoopenguin.png</file> aren't in the same directory. You can change the code and the pictures around as you like, but the Creative Commons-licensed photos used in this example were taken from the following sources and cropped to 640x425:</p>
25    <list>
26        <item><p><link href="http://en.wikipedia.org/wiki/File:Fuzzy_Freddy.jpg">Red fox photo</link> by Rob Lee, licensed <link href="http://creativecommons.org/licenses/by/2.0/deed.en">CC-By</link></p></item>
27        <item><p><link href="http://en.wikipedia.org/wiki/File:Pygoscelis_papua_-Nagasaki_Penguin_Aquarium_-swimming_underwater-8a.jpg">Gentoo penguin photo</link> by Ken Funakoshi, licensed <link href="http://creativecommons.org/licenses/by-sa/2.0/deed.en">CC-By-SA</link></p></item>
28        <item><p><link href="http://www.flickr.com/photos/shekgraham/127431519/in/photostream/">Fruit bat photo</link> by Shek Graham, licensed <link href="http://creativecommons.org/licenses/by/2.0/deed.en">CC-By</link></p></item>
29        <item><p><link href="http://commons.wikimedia.org/wiki/File:Mute_Swan-Mindaugas_Urbonas.jpg">Mute swan photo</link> by Mindaugas Urbonas, licensed <link href="http://creativecommons.org/licenses/by-sa/2.5/deed.en">CC-By-SA</link></p></item>
30    </list>
31    <p>Photo credits and licensing information are shown in the application's <link xref="aboutdialog.js">AboutDialog</link>. Always remember to credit the original artist when using <link href="http://creativecommons.org">Creative Commons-licensed works!</link></p></note>
32    <links type="section" />
33
34  <section id="imports">
35    <title>Libraries to import</title>
36    <code mime="application/javascript"><![CDATA[
37#!/usr/bin/gjs
38
39const Gio = imports.gi.Gio;
40const Gtk = imports.gi.Gtk;
41const Lang = imports.lang;
42]]></code>
43    <p>These are the libraries we need to import for this application to run. Remember that the line which tells GNOME that we're using Gjs always needs to go at the start.</p>
44    </section>
45
46  <section id="applicationwindow">
47    <title>Creating the application window</title>
48    <code mime="application/javascript"><![CDATA[
49const SwitchExample = new Lang.Class({
50    Name: 'Switch Example',
51
52    // Create the application itself
53    _init: function() {
54        this.application = new Gtk.Application({
55            application_id: 'org.example.jsswitch',
56            flags: Gio.ApplicationFlags.FLAGS_NONE
57        });
58
59    // Connect 'activate' and 'startup' signals to the callback functions
60    this.application.connect('activate', Lang.bind(this, this._onActivate));
61    this.application.connect('startup', Lang.bind(this, this._onStartup));
62    },
63
64    // Callback function for 'activate' signal presents window when active
65    _onActivate: function() {
66        this._window.present();
67    },
68
69    // Callback function for 'startup' signal creates the menu and builds the UI
70    _onStartup: function() {
71        this._initMenus();
72        this._buildUI ();
73    },
74]]></code>
75    <p>All the code for this sample goes in the SwitchExample class. The above code creates a <link href="http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gtk.Application.html">Gtk.Application</link> for our widgets and window to go in.</p>
76    <note><p>Before we call _buildUI to create the window and the widgets inside it, we need to call _initMenus, which tells GNOME to create the menu. We can put the actual code for _initMenus after the code for _buildUI, since it doesn't matter what order we put them in so long as _initMenus is called first in _onStartup.</p></note>
77    <code mime="application/javascript"><![CDATA[
78    // Build the application's UI
79    _buildUI: function() {
80
81        // Create the application window
82        this._window = new Gtk.ApplicationWindow({
83            application: this.application,
84            window_position: Gtk.WindowPosition.CENTER,
85            border_width: 20,
86            title: "Animal Creator"});
87]]></code>
88    <p>The _buildUI function is where we put all the code to create the application's user interface. The first step is creating a new <link xref="GtkApplicationWindow.js">Gtk.ApplicationWindow</link> to put all our widgets into.</p>
89  </section>
90
91  <section id="button">
92    <title>Creating the switches</title>
93    <code mime="application/javascript"><![CDATA[
94        // Create the image widget and set its default picture
95        this._image = new Gtk.Image ({file: "redfox.png"});
96]]></code>
97
98    <p>We first create the <link xref="image.js">Image</link> that the switches will control. Remember that a file named <file>redfox.png</file> needs to be in the same directory as this application.</p>
99
100    <code mime="application/javascript"><![CDATA[
101        // Create a label for the first switch
102        this._flyLabel = new Gtk.Label ({
103            label: "Make it fly",
104            margin_right: 30});
105
106        // Create the first switch and set its default position
107        this._flySwitch = new Gtk.Switch ({active: false});
108        this._flySwitch.connect ('notify::active', Lang.bind (this, this._switchFlip));
109
110        // Create a label for the second switch
111        this._birdLabel = new Gtk.Label ({
112            label: "Make it a bird",
113            margin_right: 30});
114
115        // Create the second switch
116        this._birdSwitch = new Gtk.Switch ({active: false});
117        this._birdSwitch.connect ('notify::active', Lang.bind (this, this._switchFlip));
118]]></code>
119
120    <p>We use a <link xref="label.js">Label</link> to mark each Switch, and give them a bit of a margin on the right so that they aren't crammed right next to the Switches. After that we create the Switches, and set them to be switched off by default.</p>
121    <p>The signal a switch sends out when it's flipped on or off is called notify::active. After we create each switch, we connect its notify::active signal to a function called _switchFlip. If you have multiple switches that each do something different, you might want to connect them to different functions, but here they're both used for the same thing: To control what picture's displayed by _image.</p>
122
123    <code mime="application/javascript"><![CDATA[
124        // Create a grid for the labels and switches beneath the picture
125        this._UIGrid = new Gtk.Grid ({
126            halign: Gtk.Align.CENTER,
127            valign: Gtk.Align.CENTER,
128            margin_top: 20});
129
130        // Attach the labels and switches to that grid
131        this._UIGrid.attach (this._flyLabel, 0, 0, 1, 1);
132        this._UIGrid.attach (this._flySwitch, 1, 0, 1, 1);
133        this._UIGrid.attach (this._birdLabel, 0, 1, 1, 1);
134        this._UIGrid.attach (this._birdSwitch, 1, 1, 1, 1);
135
136        // Create a master grid to put both the UI and the picture into
137        this._mainGrid = new Gtk.Grid ({
138            halign: Gtk.Align.CENTER,
139            valign: Gtk.Align.CENTER });
140
141        // Attach the picture and the UI grid to the master grid
142        this._mainGrid.attach (this._image, 0, 0, 1, 1);
143        this._mainGrid.attach (this._UIGrid, 0, 1, 1, 1);
144]]></code>
145    <p>We create a <link xref="grid.js">Grid</link> for the Labels and Switches first, so that we can organize them in a 2x2 layout with a margin between it and the Image. Then we put that Grid into a larger 2x1 Grid that has the Image on top, and the Grid with the Labels and Switches on the bottom.</p>
146    <code mime="application/javascript"><![CDATA[
147        // Add the master grid to the window
148        this._window.add (this._mainGrid);
149
150        // Show the window and all child widgets
151        this._window.show_all();
152    },
153]]></code>
154    <p>Finally, we add the larger Grid to the window, then tell the window to show itself and all the widgets inside of it.</p>
155    </section>
156
157    <section id="switch-handler">
158    <title>Function which handles the switches being flipped</title>
159
160    <code mime="application/javascript"><![CDATA[
161    _switchFlip: function() {
162
163        // Change the picture depending on which switches are flipped
164        if (this._flySwitch.get_active()) {
165
166            if (this._birdSwitch.get_active()) this._image.set_from_file ("muteswan.png");
167
168            else this._image.set_from_file ("fruitbat.png");
169        }
170
171        else {
172
173            if (this._birdSwitch.get_active()) this._image.set_from_file ("gentoopenguin.png");
174
175            else this._image.set_from_file ("redfox.png");
176
177        }
178
179    },
180]]></code>
181    <p>Each time a Switch is flipped, this function checks to see which of the two Switches are active afterwards, using the Switches' built-in get_active() function. It then changes the Image accordingly. You can change the filenames around as you like, so long as you have pictures to go with them.</p>
182</section>
183
184<section id="about">
185    <title>Creating the AboutDialog</title>
186    <code mime="application/javascript"><![CDATA[
187    _initMenus: function() {
188
189        // Build the application's menu so we can have an "About" button
190        let menu = new Gio.Menu();
191        menu.append("About", 'app.about');
192        menu.append("Quit",'app.quit');
193        this.application.set_app_menu(menu);
194
195        // Bind the "About" button to the _showAbout() function
196        let aboutAction = new Gio.SimpleAction ({ name: 'about' });
197        aboutAction.connect('activate', Lang.bind(this,
198            function() {
199                this._showAbout();
200            }));
201        this.application.add_action(aboutAction);
202
203        // Bind the "Quit" button to the function that closes the window
204        let quitAction = new Gio.SimpleAction ({ name: 'quit' });
205        quitAction.connect('activate', Lang.bind(this,
206            function() {
207                this._window.destroy();
208            }));
209        this.application.add_action(quitAction);
210    },
211]]></code>
212    <p>The first step is building the <link xref="gmenu.js">GMenu</link> that the "About" button goes into. This is the menu that appears when you click the application's name in the upper-left corner of the screen, next to the Activities menu. Our menu only has two options in it: About, and Quit.</p>
213
214    <code mime="application/javascript"><![CDATA[
215    _showAbout: function () {
216
217        // String arrays of the names of the people involved in the project
218        var artists = ['Rob Lee http://en.wikipedia.org/wiki/File:Fuzzy_Freddy.jpg', 'Ken Funakoshi http://en.wikipedia.org/wiki/File:Pygoscelis_papua_-Nagasaki_Penguin_Aquarium_-swimming_underwater-8a.jpg', 'Shek Graham http://www.flickr.com/photos/shekgraham/127431519/in/photostream/', 'Mindaugas Urbonas http://commons.wikimedia.org/wiki/File:Mute_Swan-Mindaugas_Urbonas.jpg'];
219        var authors = ["GNOME Documentation Team"];
220        var documenters = ["GNOME Documentation Team"];
221
222        // Create the About dialog
223        let aboutDialog = new Gtk.AboutDialog({
224            title: "AboutDialog Example",
225            program_name: "Animal Creator",
226            copyright: "Copyright \xa9 2012 GNOME Documentation Team\n\nRed fox photo licensed CC-By by Rob Lee\nGentoo penguin photo licensed CC-By-SA by Ken Funakoshi\nFruit bat photo licensed CC-By by Shek Graham\nMute swan photo licensed CC-By-SA by Mindaugas Urbonas\nLinks to the originals are available under Credits.\n\nHave you hugged a penguin today?",
227            artists: artists,
228            authors: authors,
229            documenters: documenters,
230            website: "http://developer.gnome.org",
231            website_label: "GNOME Developer Website" });
232
233        // Attach the About dialog to the window
234        aboutDialog.modal = true;
235        aboutDialog.transient_for = this._window;
236
237        // Show the About dialog
238        aboutDialog.show();
239
240        // Connect the Close button to the destroy signal for the dialog
241        aboutDialog.connect('response', function() {
242            aboutDialog.destroy();
243        });
244    }
245
246});
247]]></code>
248    <p>An <link xref="aboutdialog.js">AboutDialog</link> has a lot of different things you can set, to credit everyone who worked on the application and leave a note to whomever reads it. In this case, the copyright section contains our note and credits the original photographers, while the artists section shows you a list of the photographers with links to the original photos when you click the Credits button. The web URLs put after their names in the array turn their names into clickable links in the Credits section.</p>
249
250    <code mime="application/javascript"><![CDATA[
251// Run the application
252let app = new SwitchExample ();
253app.application.run (ARGV);
254]]></code>
255    <p>Finally, we create a new instance of the finished SwitchExample class, and set the application running.</p>
256  </section>
257
258  <section id="complete">
259    <title>Complete code sample</title>
260<code mime="application/javascript" style="numbered"><xi:include href="samples/switch.js" parse="text"><xi:fallback/></xi:include></code>
261  </section>
262
263  <section id="in-depth">
264    <title>In-depth documentation</title>
265<list>
266  <item><p><link href="http://developer.gnome.org/gio/unstable/GMenu.html">GMenu</link></p></item>
267  <item><p><link href="http://developer.gnome.org/gio/stable/GSimpleAction.html">GSimpleAction</link></p></item>
268  <item><p><link href="http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gtk.Application.html">Gtk.Application</link></p></item>
269  <item><p><link href="http://developer.gnome.org/gtk3/stable/GtkApplicationWindow.html">Gtk.ApplicationWindow</link></p></item>
270  <item><p><link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.Grid.html">Gtk.Grid</link></p></item>
271  <item><p><link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.Image.html">Gtk.Image</link></p></item>
272  <item><p><link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.Label.html">Gtk.Label</link></p></item>
273  <item><p><link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.Switch.html">Gtk.Switch</link></p></item>
274</list>
275  </section>
276</page>
277