Blob Blame History Raw
<?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="messagedialog.js" xml:lang="fr">
  <info>
  <title type="text">MessageDialog (JavaScript)</title>
    <link type="guide" xref="beginner.js#windows"/>
    <link type="seealso" xref="GtkApplicationWindow.js"/>
    <link type="seealso" xref="gmenu.js"/>
    <link type="seealso" xref="label.js"/>
    <revision version="0.2" date="2012-06-25" status="draft"/>

    <credit type="author copyright">
      <name>Taryn Fox</name>
      <email its:translate="no">jewelfox@fursona.net</email>
      <years>2012</years>
    </credit>

    <desc>Un message surgissant lié à une fenêtre</desc>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Luc Rebert,</mal:name>
      <mal:email>traduc@rebert.name</mal:email>
      <mal:years>2011</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Alain Lojewski,</mal:name>
      <mal:email>allomervan@gmail.com</mal:email>
      <mal:years>2011-2012</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Luc Pionchon</mal:name>
      <mal:email>pionchon.luc@gmail.com</mal:email>
      <mal:years>2011</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Bruno Brouard</mal:name>
      <mal:email>annoa.b@gmail.com</mal:email>
      <mal:years>2011-12</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Luis Menina</mal:name>
      <mal:email>liberforce@freeside.fr</mal:email>
      <mal:years>2014</mal:years>
    </mal:credit>
  </info>

  <title>Boîte de dialogue de message</title>
  <media type="image" mime="image/png" src="media/messagedialog.png"/>
  <p>Une BoiteDeDialogueDemessage contient un message modale surgissant auquel vous devez d'abord répondre avant de pouvoir retourner travailler dans la fenêtre à laquelle elle est liée. Elle peut faire exploser le monde (ou au moins elle le prétend). Pour faire apparaître le message surgissant quand vous exécutez cet exemple, cliquez sur « Message » dans le menu de son application : c'est le menu qui s'affiche quand vous cliquez sur le nom de l'application dans le coin supérieur gauche de l'écran, à côté de « Activités ».</p>
  <note><p>La différence entre une BoiteDeDialogueDemessage et une <link xref="dialog.js">Boîte de dialogue</link> est que la boîte de dialogue peut contenir n'importe quel élément graphique ou contenu que vous souhaitez y mettre, alors que la BoiteDeDialogueDemessage est juste un moyen pratique de faire s'afficher un message basique surgissant avec des boutons.</p></note>
    <links type="section"/>

  <section id="imports">
    <title>Bibliothèques à importer</title>
    <code mime="application/javascript"><![CDATA[
#!/usr/bin/gjs

const Gio = imports.gi.Gio;
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;
]]></code>
    <p>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.</p>
  </section>

  <section id="applicationwindow">
    <title>Création de la fenêtre de l'application</title>
    <code mime="application/javascript"><![CDATA[
const MessageDialogExample = new Lang.Class ({
    Name: 'MessageDialog Example',

    // Create the application itself
    _init: function () {
        this.application = new Gtk.Application ({
            application_id: 'org.example.jsmessagedialog',
            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 windows when active
    _onActivate: function () {
        this._window.present ();
    },

    // Callback function for 'startup' signal initializes menus and builds the UI
    _onStartup: function () {
        this._initMenus();
        this._buildUI ();
    },
]]></code>
    <p>Tout le code de cet exemple va dans la classe MessageDialogExample. Le code ci-dessus crée une <link href="http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gtk.Application.html">Gtk.Application</link> pour nos composants graphiques et la fenêtre qui les contient.</p>
    <note><p>Avant d'appeler _buildUI pour créer la fenêtre et les éléments graphiques qu'elle contient, il nous faut appeler _initMenus, qui indique à GNOME de générer le menu. Nous pouvons mettre le code actuel pour _initMenus après le code pour _buildUI, car l'ordre n'a pas d'importance du moment que _initMenus est appelé en premier dans _onStartup.</p></note>
    <code mime="application/javascript"><![CDATA[
    // Build the application's UI
    _buildUI: function () {

        // Create the application window
        this._window = new Gtk.ApplicationWindow  ({
            application: this.application,
            window_position: Gtk.WindowPosition.CENTER,
            title: "Gtk.MessageDialog Example",
            default_height: 200,
            default_width: 400 });
]]></code>
    <p>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 <link xref="GtkApplicationWindow.js">Gtk.ApplicationWindow</link> pour y mettre tous nos éléments graphiques.</p>

    <code mime="application/javascript"><![CDATA[
        // Create a silly warning message and add it to the window
        this.warningLabel = new Gtk.Label ({
            label: "This application goes boom! (Not really.)"});
        this._window.add (this.warningLabel);
]]></code>
    <p>For this example, all that we have in the window the popup comes out of is a silly warning <link xref="label.js">Label</link>.</p>
  </section>

  <section id="menu">
    <title>Création du menu de l'application</title>
    <code mime="application/javascript"><![CDATA[
    // Build the application menu, including the button that calls the dialog
    _initMenus: function() {
        let menu = new Gio.Menu();
        menu.append("Message",'app.message');
        menu.append("Quit",'app.quit');
        this.application.set_app_menu(menu);

        // This pops up a MessageDialog when "Message" is clicked in the menu
        let messageAction = new Gio.SimpleAction ({ name: 'message' });
        messageAction.connect('activate', Lang.bind(this,
            function() {
                this._showMessageDialog();
            }));
        this.application.add_action(messageAction);

        // This closes the window when "Quit" is clicked in the menu
        let quitAction = new Gio.SimpleAction ({ name: 'quit' });
        quitAction.connect('activate', Lang.bind(this,
            function() {
                this._window.destroy();
            }));
        this.application.add_action(quitAction);
    },
]]></code>
    <p>Ici, nous construisons le <link xref="gmenu.js">GMenu</link> où nous mettons le bouton « Message » qui active la BoiteDeDialogueDemessage. le GMenu est le menu qui s'affiche quand vous cliquez sur le nom de l'application dans le coin supérieur gauche de l'écran, à côté de « Activités ». Notre menu ne contient que deux options : Message et Quit.</p>
  </section>

  <section id="messagedialog">
    <title>Création de la BoiteDeDialogueDemessage</title>
    <code mime="application/javascript"><![CDATA[
    _showMessageDialog: function () {

        // Create a modal MessageDialog whose parent is the window
        this._messageDialog = new Gtk.MessageDialog ({
            transient_for: this._window,
            modal: true,
            buttons: Gtk.ButtonsType.OK_CANCEL,
            message_type: Gtk.MessageType.WARNING,
            text: "This action will cause the universe to stop existing." });

        this._messageDialog.connect ('response', Lang.bind(this, this._response_cb));
        this._messageDialog.show();
    },
]]></code>
    <p>Pour que notre BoiteDeDialogueDemessage soit liée à la fenêtre principale, nous définissons sa propriété modale à vrai et la configurons comme une "transient_for" _window. Ensuite, nous définissons quel type de bouton et quel genre de message nous voulons y mettre (celui-ci va déterminer le type d'icône qui accompagnera le message). Enfin nous y saisissons le texte du message et connectons son signal « response » à la fonction de rappel qui le prend en charge.</p>
    <note><p>Voici quelques ressources pour bâtir vos propres BoiteDeDialogueDemessage</p>
      <list>
        <item><p><link href="http://developer.gnome.org/gtk3/stable/GtkMessageDialog.html#GtkButtonsType">List of button types</link></p></item>
        <item><p><link href="http://developer.gnome.org/gtk3/stable/GtkMessageDialog.html#GtkMessageType">List of message types</link></p></item>
      </list>
    </note>

    <code mime="application/javascript"><![CDATA[
    // Callback function (aka signal handler) for the response signal
    _response_cb: function (messagedialog, response_id) {

        // A simple switch that changes the main window's label
        switch (response_id) {
            case Gtk.ResponseType.OK:
                this.warningLabel.set_label ("*BOOM*\n");
                break;
            case Gtk.ResponseType.CANCEL:
                this.warningLabel.set_label ("Good choice!\n");
                break;
            case Gtk.ResponseType.DELETE_EVENT:
                this.warningLabel.set_label ("Dialog closed or cancelled.\n");
                break;
        }

        this._messageDialog.destroy();

    }

});
]]></code>
    <p>Cette fonction prend deux paramètres : la BoiteDeDialogueDemessage et son identifiant response_id. Les deux sont fournis automatiquement (il n'y a pas besoins d'intervention manuelle pour que cela fonctionne). Ici, nous utilisons un interrupteur simple pour modifier le texte « warning label » en fonction de l'option sélectionnée. Le DELETE_EVENT se produit en appuyant sur la touche Échap pour annuler la BoiteDeDialogueDemessage au lieu de cliquer sur OK ou Cancel. Quel que soit votre choix, le message surgissant est détruit ensuite.</p>

    <code mime="application/javascript"><![CDATA[
// Run the application
let app = new MessageDialogExample ();
app.application.run (ARGV);
]]></code>
    <p>Pour finir, nous créons un nouvel exemple de la classe MessageDialogExample terminée et nous démarrons l'application.</p>
  </section>

  <section id="complete">
    <title>Exemple complet de code</title>
<code mime="application/javascript" style="numbered">#!/usr/bin/gjs

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

const Gio = imports.gi.Gio;
const Gtk = imports.gi.Gtk;

class MessageDialogExample {

    // Create the application itself
    constructor() {
        this.application = new Gtk.Application({
            application_id: 'org.example.jsmessagedialog',
            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 windows when active
    _onActivate() {
        this._window.present();
    }

    // Callback function for 'startup' signal initializes menus and builds the UI
    _onStartup() {
        this._initMenus();
        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: "Gtk.MessageDialog Example",
            default_height: 200,
            default_width: 400
        });

        // Create a silly warning message and add it to the window
        this.warningLabel = new Gtk.Label({
            label: "This application goes boom! (Not really.)"
        });
        this._window.add (this.warningLabel);

        // Show the window and all child widgets
        this._window.show_all();
    }

    // Build the application menu, including the button that calls the dialog
    _initMenus() {
        let menu = new Gio.Menu();
        menu.append("Message",'app.message');
        menu.append("Quit",'app.quit');
        this.application.set_app_menu(menu);

        // This pops up a MessageDialog when "Message" is clicked in the menu
        let messageAction = new Gio.SimpleAction ({ name: 'message' });
        messageAction.connect('activate', () =&gt; { this._showMessageDialog(); });
        this.application.add_action(messageAction);

        // This closes the window when "Quit" is clicked in the menu
        let quitAction = new Gio.SimpleAction ({ name: 'quit' });
        quitAction.connect('activate', () =&gt; { this._window.destroy(); });
        this.application.add_action(quitAction);
    }

    _showMessageDialog() {

        // Create a modal MessageDialog whose parent is the window
        this._messageDialog = new Gtk.MessageDialog ({
            transient_for: this._window,
            modal: true,
            buttons: Gtk.ButtonsType.OK_CANCEL,
            message_type: Gtk.MessageType.WARNING,
            text: "This action will cause the universe to stop existing." });

        this._messageDialog.connect ('response', this._response_cb.bind(this));
        this._messageDialog.show();
    }

    // Callback function (aka signal handler) for the response signal
    _response_cb(messagedialog, response_id) {

        // A simple switch that changes the main window's label
        switch (response_id) {
            case Gtk.ResponseType.OK:
                this.warningLabel.set_label ("*BOOM*\n");
                break;
            case Gtk.ResponseType.CANCEL:
                this.warningLabel.set_label ("Good choice!\n");
                break;
            case Gtk.ResponseType.DELETE_EVENT:
                this.warningLabel.set_label ("Dialog closed or cancelled.\n");
                break;
        }

        this._messageDialog.destroy();

    }
};

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

  <section id="in-depth">
    <title>Documentation approfondie</title>
<p>Dans cet exemple, les éléments suivants sont utilisés :</p>
<list>
  <item><p><link href="http://developer.gnome.org/gio/unstable/GMenu.html">GMenu</link></p></item>
  <item><p><link href="http://developer.gnome.org/gio/stable/GSimpleAction.html">GSimpleAction</link></p></item>
  <item><p><link href="http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gtk.Application.html">Gtk.Application</link></p></item>
  <item><p><link href="http://developer.gnome.org/gtk3/stable/GtkApplicationWindow.html">Gtk.ApplicationWindow</link></p></item>
  <item><p><link href="http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gtk.MessageDialog.html">Gtk.MessageDialog</link></p></item>
</list>
  </section>
</page>