<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://docbook.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY url_refdocs_base_glib_html "http://developer.gnome.org/glibmm/unstable/">
<!ENTITY url_refdocs_base_glib "&url_refdocs_base_glib_html;classGlib_1_1">
<!ENTITY url_refdocs_base_gio "&url_refdocs_base_glib_html;classGio_1_1">
<!ENTITY url_refdocs_base_gtk_html "http://developer.gnome.org/gtkmm/unstable/">
<!ENTITY url_refdocs_base_gtk "&url_refdocs_base_gtk_html;classGtk_1_1">
<!ENTITY url_refdocs_base_gtk_namespace "&url_refdocs_base_gtk_html;namespaceGtk_1_1">
<!ENTITY url_figures_base "figures/">
<!ENTITY url_examples_base "http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/">
<!ENTITY url_examples_branchsuffix "master">
<!ENTITY gtkmm "<application>gtkmm</application>">
<!ENTITY uuml "&#252;">
<!ENTITY szlig "&#223;">
<!ENTITY verbar "&#124;">
<!ENTITY copy "&#169;">
<!ENTITY nbsp "&#160;">
]>
<!--
NOTE TO TUTORIAL DOCUMENTATION AUTHORS:
When referring to the gtkmm project in this document, please use the form
&gtkmm; so that the name is consistent throughout the document. This will wrap
gtkmm with <application></application> tags which can then be styled by CSS if
desired (e.g. boldface, monospace, etc) to make it stand out as the project
name
-->
<!-- The XSL for developer.gnome.org requires this id. -->
<book id="index" lang="pt-BR">

  <bookinfo>

    <title>Programando com <application>gtkmm</application> 3</title>

    <authorgroup>
      <author lang="en">
        <firstname>Murray</firstname>
        <surname>Cumming</surname>
      </author>
      <author lang="en">
        <firstname>Bernhard</firstname>
        <surname>Rieder</surname>
        <contrib>Chapter on "Timeouts".</contrib>
      </author>
      <author lang="en">
        <firstname>Jonathon</firstname>
        <surname>Jongsma</surname>
        <contrib>Chapter on "Drawing with Cairo".</contrib>
        <contrib>Chapter on "Working with gtkmm's Source Code".</contrib>
        <contrib>Chapter on "Recent Files".</contrib>
      </author>
      <author lang="en">
        <firstname>Ole</firstname>
        <surname>Laursen</surname>
        <contrib>Parts of chapter on "Internationalization".</contrib>
      </author>
      <author lang="en">
        <firstname>Marko</firstname>
        <surname>Anastasov</surname>
        <contrib>Chapter on "Printing".</contrib>
        <contrib>Parts of chapter on "Internationalization".</contrib>
      </author>
      <author lang="en">
        <firstname>Daniel</firstname>
        <surname>Elstner</surname>
        <contrib>Section "Build Structure" of chapter
          on "Wrapping C Libraries with gmmproc".</contrib>
      </author>
      <author lang="en">
        <firstname>Chris</firstname>
        <surname>Vine</surname>
        <contrib>Chapter on "Multi-threaded programs".</contrib>
      </author>
      <author lang="en">
        <firstname>David</firstname>
        <surname>King</surname>
        <contrib>Section on Gtk::Grid.</contrib>
      </author>
      <author lang="en">
        <firstname>Pedro</firstname>
        <surname>Ferreira</surname>
        <contrib>Chapter on Keyboard Events.</contrib>
      </author>
      <author lang="en">
        <firstname>Kjell</firstname>
        <surname>Ahlstedt</surname>
        <contrib>Parts of the update from gtkmm 2 to gtkmm 3.</contrib>
      </author>
    </authorgroup>

    <abstract>

      <!-- This text is copied from the introduction. -->
      <para>Este livro explica os conceitos-chave da API C++ <application>gtkmm</application> para a criação de interfaces com o usuário. Ele também apresenta os principais elementos de interfaceamento ("widgets").</para>

    </abstract>

    <copyright lang="en">
      <year>2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010</year>
      <holder>Murray Cumming</holder>
    </copyright>

    <legalnotice>
      <para>Permissão concedida para copiar, distribuir e/ou modificar este documento sob os termos da Licença de Documentação Livre GNU (GNU Free Documentation License), Versão 1.2 ou qualquer versão mais recente publicada pela Free Software Foundation; sem Seções Invariantes, Textos de Capa Frontal, e sem Textos de Contracapa. Você pode encontrar uma cópia da licença GNU Free Documentation License da Free Software Foundation ao visitar seu web site ou escrevendo para: Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</para>
    </legalnotice>

  </bookinfo>

<chapter id="chapter-introduction">
<title>Introdução</title>

<sect1 id="sec-this-book">
<title>Este livro</title>

<para>Este livro explica os conceitos-chave da API C++ <application>gtkmm</application> para a criação de interfaces com o usuário. Ele também apresenta os principais elementos de interfaceamento ("widgets"). Embora ele mencione classes, construtores e métodos, ele não entra em maiores detalhes. Portanto, para uma informação mais completa da API, você deveria seguir os links na documentação de referência.</para>

<para>Este livro presume que tenha um bom conhecimento de C++ e de como criar programas em C++.</para>

<para>Gostaríamos muito de ouvir sobre quaisquer problemas que tenha em aprender sobre <application>gtkmm</application> com este documento, e agradeceríamos informações sobre melhorias. Por favor, veja a seção <link linkend="chapter-contributing">Contribuindo</link> para maiores informações.</para>
</sect1>

<sect1 id="sec-gtkmm">
<title>gtkmm</title>
<para><application>gtkmm</application> é um wrapper em C++ para <ulink url="http://www.gtk.org/">GTK+</ulink>, uma biblioteca usada para criar interfaces gráficas para usuário. Sua licença é a LGPL, então você pode desenvolver software aberto, software livre ou mesmo softwares comerciais não livres usando <application>gtkmm</application> sem comprar licenças.</para>
<para><application>gtkmm</application> foi originalmente denominado como gtk-- porque GTK+ já tem um sinal + no nome. Entretanto, como -- não é facilmente indexado por mecanismos de busca, o pacote geralmente ficava com o nome <application>gtkmm</application>, e é por isso que o adotamos por fim.</para>

<sect2 id="why-use-gtkmm">
<title>Por que usar <application>gtkmm</application> em vez de GTK+?</title>
<para><application>gtkmm</application> permite escrever código usando as técnicas normais de C++ como encapsulamento, derivação e polimorfismo. Como um programador de C++, você já deve perceber que isso leva a um código mais limpo e melhor organizado.</para>
<para>O <application>gtkmm</application> tem melhor segurança quanto à tipagem, assim o compilador pode detectar erros que só seriam percebidos em tempo de execução ao usar C. Esse uso de tipos específicos também torna a API mais clara, porque você pode ver que tipos deveriam ser usados apenas olhando a declaração de um método.</para>
<para>Herança pode ser usada para derivar novos widgets. A derivação de novos widgets em código GTK+ em C é tão complicada e propensa a erros que quase nenhum programador C a faz. Sendo um desenvolvedor C++, você sabe que derivação é uma técnica essencial em orientação a objetos.</para>
<para>Instâncias membros podem ser usadas, simplificando o gerenciamento de memória. Todos widgets GTK+ C são tratados pelo uso de ponteiros. Como um programador em C++ você sabe que os ponteiros devem ser evitados sempre que possível.</para>
<para><application>gtkmm</application> envolve menos código comparado ao GTK+, que usa nomes de funções com prefixos e muitas macros de conversão.</para>
</sect2>

<sect2 id="gtkmm-vs-qt">
<title><application>gtkmm</application> comparado ao Qt</title>
<para>O Qt da Trolltech é o competidor mais próximo do <application>gtkmm</application>, então merece uma discussão.</para>

<para lang="en"><application>gtkmm</application> developers tend to prefer <application>gtkmm</application> to Qt because <application>gtkmm</application> does things in a more C++ way. Qt originates from a time when C++ and the standard library were not standardised or well supported by compilers. It therefore duplicates a lot of stuff that is now in the standard library, such as containers and type information. Most significantly, Trolltech modified the C++ language to provide signals, so that Qt classes cannot be used easily with non-Qt classes. <application>gtkmm</application> was able to use standard C++ to provide signals without changing the C++ language.
See the <ulink url="https://wiki.gnome.org/Projects/gtkmm/FAQ">FAQ</ulink> for more detailed differences.</para>
</sect2>

<sect2 id="gtkmm-is-a-wrapper">
<title><application>gtkmm</application> é um wrapper</title>
<para><application>gtkmm</application> não é uma ferramenta nativamente em C++, mas um wrapper em C++ para uma ferramenta em C. Essa separação entre interface e implementação tem vantagens. Os desenvolvedores do <application>gtkmm</application> gastam a maior parte do tempo conversando sobre como o <application>gtkmm</application> pode apresentar uma API mais clara, sem se bagunçar devido a detalhes técnicos obscuros. Nós contribuímos um pouco na base do código do GTK+, mas também contribuem os programadores em C, em Perl, em Python, etc. Portanto, o GTK+ se beneficia de uma base de usuários mais ampla do que as de kits de ferramentas de uma linguagem em específico - há mais pessoas que implementam, mais desenvolvedores, mais testadores e mais usuários.</para>
</sect2>
</sect1>

</chapter>

<chapter id="chapter-installation">
<title>Instalação</title>
<sect1 id="sec-installation-dependencies">
<title>Dependências</title>
<para>Antes de tentar instalar o <application>gtkmm</application> 3.0, você pode primeiro precisar instalar estes outros pacotes.</para>
<itemizedlist>
  <listitem><para lang="en"><application>libsigc++ 2.0</application></para></listitem>
  <listitem><para lang="en"><application>GTK+ 3.0</application></para></listitem>
  <listitem><para lang="en"><application>glibmm</application></para></listitem>
  <listitem><para lang="en"><application>cairomm</application></para></listitem>
  <listitem><para lang="en"><application>pangomm</application></para></listitem>
  <listitem><para lang="en"><application>atkmm</application></para></listitem>
</itemizedlist>
<para>Essas dependências têm suas próprias dependências, incluindo os seguintes aplicativos e bibliotecas:</para>
<itemizedlist>
  <listitem><para lang="en"><application>pkg-config</application></para></listitem>
  <listitem><para lang="en"><application>glib</application></para></listitem>
  <listitem><para lang="en"><application>ATK</application></para></listitem>
  <listitem><para lang="en"><application>Pango</application></para></listitem>
  <listitem><para lang="en"><application>cairo</application></para></listitem>
  <listitem><para lang="en"><application>gdk-pixbuf</application></para></listitem>
</itemizedlist>
</sect1>

<sect1 id="sec-install-unix-and-linux">
<title>Unix e Linux</title>

<sect2 id="sec-linux-install-from-packages">
<title>Pacotes pré-compilados</title>

<para>Versões recentes do <application>gtkmm</application> hoje são empacotadas por quase todas as grandes distribuições Linux. Assim, se você usa Linux, é bem possível que possa começar com o <application>gtkmm</application> instalando o pacote do repositório oficial da sua distribuição. Algumas que incluem <application>gtkmm</application> em seus repositórios são Debian, Ubuntu, Red Hat, Fedora, Mandriva, Suse e muitas outras.</para>
<para lang="en">
    The names of the <application>gtkmm</application> packages vary from distribution to distribution
    (e.g. <application>libgtkmm-3.0-dev</application> on Debian and Ubuntu or
    <application>gtkmm30-devel</application> on Red Hat Fedora), so check with
    your distribution's package management program for the correct package name
    and install it like you would any other package.
</para>
<note>
<para lang="en">
The package names will not change when new API/ABI-compatible versions of <application>gtkmm</application>
are released. Otherwise they would not be API/ABI-compatible. So don't be
surprised, for instance, to find <application>gtkmm</application> 3.8 supplied by Debian's
<application>libgtkmm-3.0-dev</application> package.
</para>
</note>
</sect2>

<sect2 id="sec-install-from-source">
<title>Instalando pelo código fonte</title>

<para>Se sua distribuição não fornece um pacote do <application>gtkmm</application> pré-compilado, ou se quer instalar uma versão diferente da oferecida pela sua distribuição, você também pode instalar o <application>gtkmm</application> a partir do código-fonte. Ele pode ser baixado em <ulink url="http://www.gtkmm.org/"/>.</para>
<para>Depois que instalar todas as dependências, baixe o código-fonte do <application>gtkmm</application>, descompacte-o e entre no diretório recém-criado. O <application>gtkmm</application> pode ser compilado e instalado com a seguinte sequência de comandos: </para>
<screen>
# ./configure
# make
# make install
</screen>
<note>
<para lang="en">
  Remember that on a Unix or Linux operating system, you will probably need to
  be <literal>root</literal> to install software. The <command>su</command> or <command>sudo</command>
  command will allow you to enter the <literal>root</literal> password and have
  <literal>root</literal> status temporarily.
</para>
</note>
<para>O script <filename>configure</filename> irá assegurar que todas as dependências exigidas já estão instaladas. Se você estiver sem alguma dependência, ele sairá e mostrará um erro.</para>
<para lang="en">
    By default, <application>gtkmm</application> will be installed under the
    <filename>/usr/local</filename> directory. On some systems you may need to
    install to a different location. For instance, on Red Hat Linux systems
    you might use the <literal>--prefix</literal> option with configure, like
    so:
<screen lang="en">
# ./configure --prefix=/usr
</screen>
</para>
<warning>
    <para>Tenha muito cuidado ao instalar em prefixo padrões do sistema como <filename>/usr</filename>. As distribuições Linux instalam pacotes de programas em <filename>/usr</filename>, então instalar um pacote fonte neste prefixo poderia corromper ou conflitar com os programas instalados usando o sistema de gerenciamento de pacotes da sua distribuição. Idealmente, você deveria usar um prefixo separado para todos os softwares que você instalar a partir do código-fonte.</para>
</warning>
<para>Se você quiser ajudar a desenvolver o <application>gtkmm</application> ou experimentar novos recursos, você pode instalar o <application>gtkmm</application> a partir do git. A maioria dos usuários nunca precisarão fazer isso, mas se estiver interessado em ajudar no desenvolvimento do <application>gtkmm</application> , veja o apêndice <link linkend="chapter-working-with-source">Trabalhando com o código-fonte do gtkmm</link>.</para>
</sect2>

</sect1>

<sect1 id="sec-packages-windows">
<title>Microsoft Windows</title>
<para lang="en">GTK+ and <application>gtkmm</application> were designed to work well with Microsoft Windows, and the developers encourage its use on the win32 platform. However, Windows has no standard installation system for development libraries. Please see the <ulink url="https://wiki.gnome.org/Projects/gtkmm/MSWindows">Windows Installation</ulink>
page for Windows-specific installation instructions and notes.</para>
</sect1>

</chapter>

<chapter id="chapter-basics">
<title>Básico</title>

<para>Este capítulo irá introduzir alguns dos aspectos mais importantes de um código com <application>gtkmm</application>. Isso será demonstrado com um código de exemplo simples e funcional. Mas isso é só um aperitivo, então você precisará olhar os outros capítulos para informações mais substanciais.</para>
<para>Seu conhecimento prévio de C++ lhe ajudará no <application>gtkmm</application> assim como o faria com qualquer biblioteca. A menos que declaremos o contrário, você pode considerar que as classes do <application>gtkmm</application> se comportam como qualquer outra classe C++, e pode contar com o uso de técnicas de C++ que você conhece com as bibliotecas do <application>gtkmm</application>.</para>

<sect1 id="sec-basics-simple-example">
<title>Exemplo simples</title>

<para>Para iniciar a introdução ao <application>gtkmm</application>, comecemos com o programa mais simples possível. Este programa cria uma janela vazia com 200 x 200 pixels.</para>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/base?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>base.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;gtkmm.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app =
    Gtk::Application::create(argc, argv,
      "org.gtkmm.examples.base");

  Gtk::Window window;
  window.set_default_size(200, 200);

  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

<para>Explicaremos agora cada linha do exemplo</para>
<programlisting>#include &lt;gtkmm.h&gt;</programlisting>
<para>Todos os programas <application>gtkmm</application> devem incluir certos cabeçalhos do <application>gtkmm</application>; <literal>gtkmm.h</literal> inclui todo o kit <application>gtkmm</application>. Isso normalmente não é uma boa ideia, porque inclui um megabyte ou mais de cabeçalhos, mas, para programas simples, é o suficiente.</para>

<para lang="en">
The next statement:

<programlisting lang="en">Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");</programlisting>

creates a <classname>Gtk::Application</classname> object, stored in a <classname>RefPtr</classname> smartpointer. This is needed in all <application>gtkmm</application>
applications. The <methodname>create()</methodname> method for this object initializes <application>gtkmm</application>, and checks the
arguments passed to your application on the command line, looking for
standard options such as <literal>--display</literal>. It takes these from the argument list, leaving anything it does not
recognize for your application to parse or ignore. This ensures
that all <application>gtkmm</application> applications accept the same set of standard arguments.
</para>

<para>As próximas duas linhas de código criam uma janela e define seu tamanho padrão (inicial):</para>
<programlisting>Gtk::Window window;
window.set_default_size(200, 200);</programlisting>
<para lang="en">
The last line shows the window and enters the <application>gtkmm</application> main processing loop, which will finish when the window is closed.
Your <function>main()</function> function will then return with an appropriate success or error code.
</para>

<programlisting>return app-&gt;run(window);</programlisting>

<para lang="en">
After putting the source code in <literal>simple.cc</literal> you can compile
the above program with <application>gcc</application> using:
<programlisting lang="en">g++ simple.cc -o simple `pkg-config gtkmm-3.0 --cflags --libs`</programlisting>
Note that you must surround the <literal>pkg-config</literal> invocation with backquotes.
Backquotes cause the shell to execute the command inside them, and to use
the command's output as part of the command line.
Note also that <literal>simple.cc</literal> must come before the <literal>pkg-config</literal>
invocation on the command line.
</para>
</sect1>

<sect1 id="sec-headers-and-linking">
<title>Cabeçalhos e vinculação</title>
<para lang="en">
Although we have shown the compilation command for the simple example, you really should use the automake and autoconf tools, as described in "Autoconf, Automake, Libtool", by G. V. Vaughan et al. The examples used in this book are included in the <application>gtkmm-documentation</application> package, with appropriate build files, so we won't show the build commands in future. You'll just need to find the appropriate directory and type <literal>make</literal>.
</para>
<para>Para simplificar a compilação, usaremos o <literal>pkg-config</literal>, que está presente em todas as instalações do <application>gtkmm</application> (se instaladas apropriadamente). Esse programa "sabe" quais opções de compilador são necessárias para compilar os programa que usam <application>gtkmm</application>. A opção <literal>--cflags</literal> faz com que o <literal>pkg-config</literal> emita uma lista de diretórios de inclusão para o compilador buscar; a opção <literal>--libs</literal> solicita a lista de bibliotecas às quais o compilador deve vincular e os diretórios onde achá-los. Experimente executá-lo no seu prompt do shell para ver os resultados no seu sistema.</para>
<para lang="en">
However, this is even simpler when using the <function>PKG_CHECK_MODULES()</function> macro in a standard configure.ac file with autoconf and automake.
For instance:
<programlisting lang="en">PKG_CHECK_MODULES([MYAPP], [gtkmm-3.0 &gt;= 3.8.0])</programlisting>
This checks for the presence of gtkmm and defines MYAPP_LIBS and MYAPP_CFLAGS for use in your Makefile.am files.
</para>
<para lang="en">gtkmm-3.0 is the name of the current stable API. There was an older API called gtkmm-2-4 which installs in parallel when it is available. There were several versions of gtkmm-2.4, such as gtkmm 2.10 and there are several versions of the gtkmm-3.0 API. Note that the API name does not change for every version because that would be an incompatible API and ABI break. Theoretically, there might be a future gtkmm-4.0 API which would install in parallel with gtkmm-3.0 without affecting existing applications.
</para>

<para>Note que se você mencionar módulos além do gtkmm-3.0, eles seriam separados por espaços, e não por vírgulas.</para>
<para>Openismus tem mais <ulink url="http://www.openismus.com/documents/linux/automake/automake.shtml">ajuda básica sobre automake e autoconf</ulink>.</para>

</sect1>

<sect1 id="sec-widgets-overview">
<title>Widgets</title>
<para>Os aplicativos <application>gtkmm</application> consistem de janelas contendo widgets (componentes), como botões e caixas de texto. Em alguns outros sistemas, widgets são chamados de "controles". Para cada widget em janelas do seu aplicativo, há um objeto C++ em seu código. Então você precisa chamar um método da classe do widget para afetar o widget visível.</para>
 <para lang="en">Widgets are arranged inside container widgets such as frames and notebooks, in a hierarchy of widgets within widgets. Some of these container widgets, such as <classname>Gtk::Grid</classname>, are not visible - they exist only to arrange other widgets. Here is some example code that adds 2 <classname>Gtk::Button</classname> widgets to a <classname>Gtk::Box</classname> container widget:
<programlisting lang="en">m_box.pack_start(m_Button1);
m_box.pack_start(m_Button2);</programlisting>
and here is how to add the <classname>Gtk::Box</classname>, containing those buttons, to a <classname>Gtk::Frame</classname>, which has a visible frame and title:
<programlisting lang="en">m_frame.add(m_box);</programlisting>
</para>
<para>A maioria dos capítulos deste livro trata de widgets específicos. Veja a seção <link linkend="chapter-container-widgets">Widgets contêineres</link> para mais detalhes sobre a adição de widgets a widgets contêineres.</para>

<para>Embora você possa especificar a disposição e a aparência das janelas e widgets com o código C++, você provavelmente achará mais conveniente projetar suas interfaces com o usuário com <literal>Glade</literal> e carregá-las em tempo de execução com o <literal>Gtk::Builder</literal>. Veja o capítulo <link linkend="chapter-builder">Glade e Gtk::Builder</link>.</para>

<para>Embora as instâncias de widgets <application>gtkmm</application> tenham tempo de vida e escopo como qualquer outra classe C++, o <application>gtkmm</application> tem um recurso poupador de tempo opcional que você verá em alguns exemplos. <function>Gtk::manage()</function> permite que você diga que um widget filho pertence ao contêiner em que você o colocou. Isso permite que você crie um novo (<function>new</function>) widget, adicione-o ao contêiner e esqueça sobre sua exclusão. Você pode aprender mais sobre as técnicas de gerenciamento de memória do <application>gtkmm</application> no <link linkend="chapter-memory">capítulo de Gerenciamento de memória</link>.</para>

</sect1>

<sect1 id="sec-signals-overview">
<title>Sinais</title>

<para>O <application>gtkmm</application>, como a maioria dos kits de ferramentas para GUI, é <emphasis>orientado a eventos</emphasis>. Quando um evento ocorre, como o pressionar de botão do mouse, o sinal apropriado será <emphasis>emitido</emphasis> pelo widget que foi pressionado. Cada widget tem um conjunto de sinais diferente que pode emitir. Para fazer um clique de botão resultar em uma ação, nós configuramos um <emphasis>manipulador de sinais</emphasis> para capturar o sinal "clicked" do botão.</para>
<para lang="en"><application>gtkmm</application> uses the libsigc++ library to implement signals. Here is an example line of code that connects a Gtk::Button's "clicked" signal with a signal handler called "on_button_clicked":
<programlisting lang="en">m_button1.signal_clicked().connect( sigc::mem_fun(*this,
  &amp;HelloWorld::on_button_clicked) );</programlisting>
</para>

<para>Para informações mais detalhadas sobre sinais, veja o <link linkend="chapter-signals">apêndice</link>.</para>
<para>Para informações sobre como implementar seus próprios sinais em vez de apenas conectar os sinais <application>gtkmm</application> existentes, veja o <link linkend="chapter-custom-signals">apêndice</link>.</para>

</sect1>

<sect1 id="sec-basics-ustring">
<title>Glib::ustring</title>
<para lang="en">You might be surprised to learn that <application>gtkmm</application> doesn't use <classname>std::string</classname> in its interfaces. Instead it uses <classname>Glib::ustring</classname>, which is so similar and unobtrusive that you could actually pretend that each <classname>Glib::ustring</classname> is a <classname>std::string</classname> and ignore the rest of this section. But read on if you want to use languages other than English in your application.</para>
<para lang="en">std::string uses 8 bit per character, but 8 bits aren't enough to encode languages such as Arabic, Chinese, and Japanese. Although the encodings for these languages have now been specified by the Unicode Consortium, the C and C++ languages do not yet provide any standardised Unicode support. GTK+ and GNOME chose to implement Unicode using UTF-8, and that's what is wrapped by Glib::ustring. It provides almost exactly the same interface as std::string, along with automatic conversions to and from std::string.</para>
<para>Um dos benefícios do UTF-8 é que você não precisa usá-lo a menos que queira, então não precisa mexer no seu código todo de uma vez. <classname>std::string</classname> funcionará também com textos ASCII 7 bits. Porém, quando você tentar fazer a localização do seu aplicativo para idiomas como chinês, por exemplo, você comerçará a ver uns erros estranhos, e possivelmente uns travamentos. Então, tudo que você precisa fazer é começar a usar <classname>Glib::ustring</classname> no lugar.</para>
<para>Note que UTF-8 não é compatível com codificações de 8 bits como ISO-8859-1. Por exemplo, os tremas alemães (umlaut) não estão na faixa ASCII e precisam de mais que 1 byte na codificação UTF-8. Se seu código contém textos constantes em 8 bits, você tem que convertê-los para UTF-8 (exemplo: o cumprimento da Bavária "Grüß Gott" seria "Gr\xC3\xBC\xC3\x9F Gott").</para>
<para>Você deveria evitar aritmética de ponteiros no estilo C e funções como strlen(). Em UTF-8, cada caractere pode precisar em algum lugar de 1 a 6 bytes, então não é possível assumir que o próximo byte é outro caractere. <classname>Glib::ustring</classname> se preocupa com esses detalhes para você para que possa usar métodos tais como Glib::ustring::substr() enquanto ainda raciocina em termos de caracteres em vez de bytes.</para>

<para>Ao contrário da solução Unicode UCS-2 do Windows, ele não exige quaisquer opções especiais do compilador para processar textos contantes, além de não gerar executáveis e biblioteca Unicode que sejam incompatíveis com os em ASCII.</para>

<para lang="en"><ulink url="http://developer.gnome.org/glibmm/unstable/classGlib_1_1ustring.html">Reference</ulink></para>

<para>Veja a seção <link linkend="chapter-internationalization">Internacionalização</link> para informações sobre como fornecer textos constantes em UTF-8.</para>

</sect1>

<sect1 id="sec-intermediate-types">
<title>Tipos intermediários</title>
<para>Algumas API relacionadas ao gtkmm usam contêneires de dados intermediários, como a <classname>Glib::StringArrayHandle</classname>, em vez de usar um contêiner especificamente no padrão C++ como <classname>std::vector</classname> or <classname>std::list</classname>, embora o próprio <application>gtkmm</application> agora use apenas <classname>std::vector</classname> desde a versão <application>gtkmm</application> 3.0.</para>
<para lang="en">You should not declare these types yourself. You should instead use whatever Standard C++ container you prefer. glibmm will do the conversion for you. Here are some of these intermediate types:
<itemizedlist>
    <listitem><para lang="en"><classname>Glib::StringArrayHandle</classname> or <classname>Glib::ArrayHandle&lt;Glib::ustring&gt;</classname>: Use <classname>std::vector&lt;Glib::ustring&gt;</classname>, <classname>std::list&lt;Glib::ustring&gt;</classname>, <type>const char*[]</type>, etc.</para></listitem>
    <listitem><para lang="en"><classname>Glib::ListHandle&lt;Gtk::Widget*&gt;</classname>: Use <classname>std::vector&lt;Gtk::Widget*&gt;</classname>, <classname>std::list&lt;Gtk::Widget*&gt;</classname>, etc.</para></listitem>
    <listitem><para lang="en"><classname>Glib::SListHandle&lt;Gtk::Widget*&gt;</classname>: Use <classname>std::vector&lt;Gtk::Widget*&gt;</classname>, <classname>std::list&lt;Gtk::Widget*&gt;</classname>, etc.</para></listitem>
</itemizedlist>

</para>

</sect1>

<sect1 id="sec-basics-gobj-and-wrap">
<title>Misturando APIs C e C++</title>
<para>Você pode usar APIs C que ainda não tenham interfaces C++ convenientes. Geralmente não há problema usar APIs C no C++, e o <application>gtkmm</application> ajuda a prover acesso ao objeto C que está por trás, e a prover uma maneira fácil de criar um objeto C++ de wrap para um objeto C, desde que a API C também seja baseada no sistema GObject.</para>

<para>Para passar um objeto <application>gtkmm</application> para uma função C que exija um objeto GObject C, use a função <function>gobj()</function> para obter um ponteiro para o objeto GObject escondido. Por exemplo,</para>

<para>
<programlisting>
Gtk::Button* botao = new Gtk::Button("exemplo");
gtk_button_faca_algo_novo(botao-&gt;gobj());
</programlisting>
</para>

<para>Para obter um objeto <application>gtkmm</application> a partir de um GObject C, use a função Glib::wrap(). Por exemplo,</para>
<para>
<programlisting>
GtkButton* botao_c = pegar_um_botao();
Gtk::Button* botao = Glib::wrap(botao_c);
</programlisting>
</para>
</sect1>

<sect1 id="sec-helloworld">
<title>Olá mundo em <application>gtkmm</application></title>

<para>Agora já aprendemos o suficiente para dar uma olhada em um exemplo real. Conforme uma antiga tradição da ciência da computação, apresentaremos um Olá, mundo, à la <application>gtkmm</application>:</para>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/helloworld?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>helloworld.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_HELLOWORLD_H
#define GTKMM_EXAMPLE_HELLOWORLD_H

#include &lt;gtkmm/button.h&gt;
#include &lt;gtkmm/window.h&gt;

class HelloWorld : public Gtk::Window
{

public:
  HelloWorld();
  virtual ~HelloWorld();

protected:
  //Signal handlers:
  void on_button_clicked();

  //Member widgets:
  Gtk::Button m_button;
};

#endif // GTKMM_EXAMPLE_HELLOWORLD_H
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "helloworld.h"
#include &lt;gtkmm/application.h&gt;

int main (int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  HelloWorld helloworld;

  //Shows the window and returns when it is closed.
  return app-&gt;run(helloworld);
}
</programlisting>
<para lang="en">File: <filename>helloworld.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "helloworld.h"
#include &lt;iostream&gt;

HelloWorld::HelloWorld()
: m_button("Hello World")   // creates a new button with label "Hello World".
{
  // Sets the border width of the window.
  set_border_width(10);

  // When the button receives the "clicked" signal, it will call the
  // on_button_clicked() method defined below.
  m_button.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;HelloWorld::on_button_clicked));

  // This packs the button into the Window (a container).
  add(m_button);

  // The final step is to display this newly created widget...
  m_button.show();
}

HelloWorld::~HelloWorld()
{
}

void HelloWorld::on_button_clicked()
{
  std::cout &lt;&lt; "Hello World" &lt;&lt; std::endl;
}
</programlisting>
<!-- end inserted example code -->

<para>Tente compilá-lo e executá-lo antes de continuar. Você deveria ver algo assim:</para>

<figure id="figure-helloworld">
  <title>Olá, Mundo</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/helloworld.png"/>
  </screenshot>
</figure>

<para>Bem empolgante, hein? Vamos examinar o código. Primeiro, a classe <classname>HelloWorld</classname>:</para>

<programlisting>class HelloWorld : public Gtk::Window
{

public:
  HelloWorld();
  virtual ~HelloWorld();

protected:
  //Signal handlers:
  virtual void on_button_clicked();

  //Member widgets:
  Gtk::Button m_button;
};</programlisting>

<para>Esta classe implementa a janela "Hello World". Ela é derivada de <classname>Gtk::Window</classname> e tem um único <classname>Gtk::Button</classname> como membro. Optamos por usar o construtor para fazer todo o trabalho de iniciação para a janela, incluindo a configuração dos sinais. Aqui está, com os comentários omitidos:</para>

<programlisting>HelloWorld::HelloWorld()
:
  m_button ("Hello World")
{
  set_border_width(10);
  m_button.signal_clicked().connect(sigc::mem_fun(*this,
    &amp;HelloWorld::on_button_clicked));
  add(m_button);.
  m_button.show();
}</programlisting>

<para>Note que usamos uma declaração iniciadora para dar ao objeto <literal>m_button</literal> o rótulo "Hello World".</para>

<para>Em seguida, chamamos o método <methodname>set_border_width()</methodname> da janela. Isso define a quantidade de espaço entre as laterais da janela e o widget que ela contém.</para>

<para>Depois, associamos um manipulador para o sinal <literal>clicked</literal> de <literal>m_button</literal>. Ele emitirá nosso cumprimento amistoso para <literal>stdout</literal>.</para>

<para>Em seguida, usamos o método <methodname>add()</methodname> da janela para colocar o <literal>m_button</literal> nela (<methodname>add()</methodname> vem de um <classname>Gtk::Container</classname>, que é descrito no capítulo sobre widgets contêineres). O método <methodname>add()</methodname> põe o widget na janela, mas não o exibe. Os widgets <application>gtkmm</application> são sempre invisíveis ao serem criados: para exibi-los, você tem que chamar o método <methodname>show()</methodname>, que é o que fazemos na linha seguinte.</para>


<para>Agora vamos olhar para a função <function>main()</function> do nosso programa. Aqui está, sem os comentários:</para>

<programlisting lang="en">int main(int argc, char** argv)
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  HelloWorld helloworld;
  return app-&gt;run(helloworld);
}</programlisting>

<para lang="en">
First we instantiate an object stored in a <classname>RefPtr</classname> smartpointer called <literal>app</literal>. This is of type
<classname>Gtk::Application</classname>. Every <application>gtkmm</application> program must have one of these. We pass
our command-line arguments to its create() method. It takes the arguments
it wants, and leaves you the rest, as we described earlier.
</para>

<para lang="en">
Next we make an object of our <classname>HelloWorld</classname> class, whose constructor
takes no arguments, but it isn't visible yet. When we call <methodname>Gtk::Application::run()</methodname>, giving it the helloworld Window, it shows the Window and starts the <application>gtkmm</application> <emphasis>event loop</emphasis>. During the event loop <application>gtkmm</application> idles, waiting for actions from the user, and responding appropriately. When the user closes the Window, run() will return, causing the final line of our main() function be to executed. The application will then finish.
</para>

</sect1>
</chapter>

<chapter id="changes-gtkmm3">
<title>Mudanças na <application>gtkmm</application> 3</title>

<para><application>gtkmm</application>-3.0 é a nova versão da API <application>gtkmm</application> que se instala em paralelo com a antiga API <application>gtkmm</application>-2.4. A última versão da API <application>gtkmm</application>-2.4 foi a <application>gtkmm</application> 2.24. <application>gtkmm</application> 3 não tem grandes diferenças fundamentais com a API <application>gtkmm</application>-2.4 então você pode ignorar este capítulo.</para>

<para>A biblioteca <application>gtkmm</application> 3 é chamada <literal>libgtkmm-3.0</literal> em vez de <literal>libgtkmm-2.4</literal> e instala seus cabeçalhos em um diretório com a mesma versão, assim sua verificação pkg-config, deve pedir por <literal>gtkmm-3.0</literal> em vez de <literal>gtkmm-2.4</literal>.</para>


<para><application>gtkmm</application> 3 adicionou algumas novas classes:</para>

<orderedlist>
<listitem><simpara><classname>Gtk::AppChooser</classname>, <classname>Gtk::AppChooserButton</classname>, <classname>Gtk::AppChooserDialog</classname> permite ao usuário selecionar uma aplicação instalada para abrir um determinado tipo de conteúdo.</simpara></listitem>
<listitem><simpara lang="en"><classname>Gtk::Grid</classname> is a new container widget that will eventually replace <classname>Gtk::Box</classname> and <classname>Gtk::Table</classname>. It arranges its children according to properties of those children rather than its own layout details.</simpara></listitem>
<listitem><simpara><classname>Gtk::Switch</classname> exibe os estados ligado/desligado mais explicitamente do que <classname>Gtk::CheckBox</classname>. Ele pode ser útil, por exemplo, ao permitir que os utilizadores possam ativar o hardware.</simpara></listitem>
</orderedlist>

<para><application>gtkmm</application> 3 também fez várias pequenas mudanças na API, que provavelmente você encontrará quando portar o código usado na <application>gtkmm</application>-2.4. Aqui está uma pequena lista:</para>

<para>
<orderedlist>

<listitem><simpara><classname>Gtk::CellLayout</classname>, utilizado pela <classname>Gtk::IconView</classname>, <classname>Gtk::TreeView::Column</classname> e <classname>Gtk::ComboBox</classname>, agora tem uma <classname>Gtk::CellArea</classname> que pode ser usado para especificar mais detalhes sobre como a <classname>CellRenderer</classname> são dispostos e alinhados.</simpara></listitem>

<listitem><simpara>Gtk::ComboBox agora deriva de CellLayout, permitindo uma fácil distribuição e alinhamento das suas <classname>Gtk::CellRenderer</classname>.</simpara></listitem>

<listitem><simpara><classname>Gtk::Adjustment</classname>, <classname>IconSet</classname> e <classname>Gdk::Cursor</classname> agora são usados através de <classname>Glib::RefPtr</classname>.</simpara></listitem>

<listitem><simpara><classname>Gtk::Box</classname>, <classname>Gtk::ButtonBox</classname>, <classname>Gtk::IconView</classname>, <classname>Gtk::Paned</classname>, <classname>Gtk::ProgressBar</classname>, <classname>Gtk::ScaleButton</classname>, <classname>Gtk::Scrollbar</classname> e <classname>Gtk::Separator</classname> agora derivam de <classname>Gtk::Orientable</classname>, permitindo que sua orientação (vertical ou horizontal) seja especificado sem exigir o uso de uma classe derivada, tal como <classname>Gtk::HBox</classname>.</simpara></listitem>

<listitem><simpara><classname>Gtk::IconView</classname>, <classname>Gtk::TextView</classname>, <classname>Gtk::TreeView</classname> e outros widgets derivam de Scrollable em vez de ter seus próprios métodos, como <methodname>get_vadjustment()</methodname> e ao invés de ter seu próprio sinal set_scroll_adjustments.</simpara></listitem>

<listitem><simpara><classname>Gtk::Style</classname> e <classname>Gtk::Rc</classname> foram removidos, substituídos por <classname>Gtk::StyleContext</classname>, e <classname>Gtk::StyleProvider</classname>, tal como <classname>Gtk::CssProvider</classname>.</simpara></listitem>

<listitem><simpara>Widget::on_expose_event() foi substituido por Widget::on_draw(), que assume que cairomm é utilizado para desenho, por meio do <classname>Cairo::Context</classname> e não requer que você chame <methodname>Cairo::Context::clip()</methodname>.</simpara></listitem>

<listitem><simpara><classname>Gdk::RGBA</classname> substitui <classname>Color</classname>, adicionando um componente alfa para a opacidade. <classname>Colormap</classname> foi removido, juntamente com o seu uso difícil de alocar cores.</simpara></listitem>

<listitem><simpara><classname>Gdk::Pixmap</classname> e <classname>Gdk::Bitmap</classname> foram removidos em favor de <classname>Gdk::Pixbuf</classname>.</simpara></listitem>

<listitem><simpara><classname>Gdk::Drawable</classname> foi removido, com seus método movidos para <classname>Gdk::Window</classname>.</simpara></listitem>

<listitem><simpara>Agora usamos std::vector em vários métodos, em vez do tipo intermediário *Handle para fazer a API mais clara.</simpara></listitem>

</orderedlist>
</para>

<para>Toda API obsoleta foi removida na <application>gtkmm</application> 3.0, que haverá novas depreciações em versões futuras.</para>

<para lang="en">As a first step to porting your source code to <application>gtkmm</application>-3.0 you should probably ensure that your application builds with the deprecated <application>gtkmm</application>-2.4 API disabled, by defining macro such as GTKMM_DISABLE_DEPRECATED. There are some autotools macros that can help with this by defining them optionally at build time. See the <ulink url="https://wiki.gnome.org/Projects/gtkmm/PortingToGtkmm3">gtkmm 3 porting wiki page</ulink> for more details.</para>

</chapter>

<chapter id="chapter-button-widget">
<title>Botões</title>

<para><application>gtkmm</application> provẽ quatro tipos básicos de botões:</para>

<variablelist>

<varlistentry>
<term>Botões de pressão</term>
<listitem>
<para><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Button.html"><classname>Gtk::Button</classname></ulink>. Os botões padrões, normalmente marcados com um rótulo ou imagem. Pressioná-los dispara uma ação. Veja a seção <link linkend="sec-pushbuttons">Botão</link>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Botões de alternância</term>
<listitem>
<para><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToggleButton.html"><classname>Gtk::ToggleButton</classname></ulink>. Ao contrário de um botão normal, que volta à sua posição para cima, um botão de alternância fica pressionado para baixo até que você o pressione novamente. Isso pode ser útil como um interruptor liga/desliga. Veja a seção <link linkend="sec-toggle-buttons">Botão de alternância</link>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Botão de seleção</term>
<listitem>
<para lang="en">
<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1CheckButton.html"><classname>Gtk::CheckButton</classname></ulink>.
These act like ToggleButtons, but show their state in small squares,
with their label at the side. They should be used in most situations
which require an on/off setting.
See the <link linkend="sec-checkboxes">CheckButton</link> section.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Botões de opção</term>
<listitem>
<para><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1RadioButton.html"><classname>Gtk::RadioButton</classname></ulink>. Com o seu nome baseado nos seletores de estação em aparelhos antigos de carro, estes botões são usados em grupos para opções que sejam mutuamente exclusivas. Pressinar um deles faz com que todos os outros do seu grupo sejam desativados. Eles são similares aos botões de seleção (um pequeno widget com um rótulo ao lado), mas normalmente tem uma aparência distinta. Veja a seção <link linkend="sec-radio-buttons">Botão de opção</link>.</para>
</listitem>
</varlistentry>
</variablelist>

<para>Note que, devido ao sistema de temas do GTK+, a aparência desses widgets irá variar. No caso dos botões de seleção e de opção, eles podem variar consideravelmente.</para>

<sect1 id="sec-pushbuttons">
<title>Botão</title>

<sect2 id="pushbutton-constructors"><title>Construtores</title>

<para>Existem duas formas de criar um Botão. Você pode especificar um texto de rótulo no construtor <classname>Gtk::Button</classname> ou defini-lo mais tarde com <methodname>set_label()</methodname>.</para>

<para>Para definir uma tecla aceleradora para navegação por teclado, coloque uma sublinha antes de um dos caracteres do rótulo e especifique <literal>true</literal> para o parâmetro opcional <literal>mnemonic</literal>. Por exemplo:</para>
<programlisting>Gtk::Button* pButton = new Gtk::Button("_Algo", true);</programlisting>

<para lang="en">
Stock items have been recommended for use in buttons. From <application>gtkmm</application>-3.10 they are deprecated.
They should not be used in newly-written code. However, the documentation of
<ulink url="http://developer.gnome.org/gtkmm/unstable/namespaceGtk_1_1Stock.html">namespace Gtk::Stock</ulink>
shows recommended labels and named icons to show in buttons.
</para>

<para><classname>Gtk::Button</classname> é também um contêiner, então você pode colocar qualquer outro widget nele, como um <classname>Gtk::Image</classname>.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Button.html">Reference</ulink></para>
</sect2>

<sect2 id="pushbutton-example"><title>Exemplo</title>

<para>Este exemplo cria um botão com uma figura e um rótulo.</para>

<figure id="figure-buttons">
  <title>exemplo de botões</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/buttons.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/buttons/button?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>buttons.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_BUTTONS_H
#define GTKMM_EXAMPLE_BUTTONS_H

#include &lt;gtkmm/window.h&gt;
#include &lt;gtkmm/button.h&gt;

class Buttons : public Gtk::Window
{
public:
  Buttons();
  virtual ~Buttons();

protected:
  //Signal handlers:
  void on_button_clicked();

  //Child widgets:
  Gtk::Button m_button;
};

#endif //GTKMM_EXAMPLE_BUTTONS_H
</programlisting>
<para lang="en">File: <filename>buttons.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "buttons.h"
#include &lt;iostream&gt;

Buttons::Buttons()
{
  m_button.add_pixlabel("info.xpm", "cool button");

  set_title("Pixmap'd buttons!");
  set_border_width(10);

  m_button.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;Buttons::on_button_clicked) );

  add(m_button);

  show_all_children();
}

Buttons::~Buttons()
{
}

void Buttons::on_button_clicked()
{
  std::cout &lt;&lt; "The Button was clicked." &lt;&lt; std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "buttons.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  Buttons buttons;

  //Shows the window and returns when it is closed.
  return app-&gt;run(buttons);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

<sect2 id="pushbutton-signals"><title>Sinais</title>

<para lang="en">
The <classname>Gtk::Button</classname> widget has the following signals,
but all except the <literal>clicked</literal> signal are deprecated
and should not be used in newly-written code:
</para>

<para>
<variablelist>

<varlistentry>
<term lang="en"><literal>pressed</literal></term>
<listitem>
<para lang="en">
Emitted when the button is pressed.
Use <methodname>Gtk::Widget::signal_button_press_event()</methodname> instead.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en"><literal>released</literal></term>
<listitem>
<para lang="en">
Emitted when the button is released.
Use <methodname>Gtk::Widget::signal_button_release_event()</methodname> instead.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en"><literal>clicked</literal></term>
<listitem>
<para>Emitido quando o botão é pressionado e depois liberado.</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en"><literal>enter</literal></term>
<listitem>
<para lang="en">
Emitted when the mouse pointer enters the button's window.
Use <methodname>Gtk::Widget::signal_enter_notify_event()</methodname> instead.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term lang="en"><literal>leave</literal></term>
<listitem>
<para lang="en">
Emitted when the mouse pointer leaves the button's window.
Use <methodname>Gtk::Widget::signal_leave_notify_event()</methodname> instead.
</para>
</listitem>
</varlistentry>
</variablelist>
</para>

</sect2>
</sect1>

<sect1 id="sec-toggle-buttons">
<title>Botão de alternância</title>

<para>Um <classname>ToggleButton</classname> é como um <classname>Button</classname> normal, só que uma vez clicados, eles permanecem ativados, ou pressionados, até que sejam clicados de novo.</para>

<para>para obter o estado do <classname>ToggleButton</classname>, você pode usar o método <methodname>get_active()</methodname>. Ele retorna <literal>true</literal> se o botão está "para baixo". Você também pode definir o estado do botão de alternância, para isso use <methodname>set_active()</methodname>. Note que, se você fizer isso e o estado mudar de fato, isso faz com que o sinal <literal>clicked</literal> seja emitido. Isso é o que você quer normalmente.</para>

<para>Você pode usar o método <methodname>toggled()</methodname> para alternar o botão, em vez de forçá-lo para cima ou para baixo: isso troca o estado do botão e faz com que o sinal <literal>toggled</literal> seja emitido.</para>

<para><classname>Gtk::ToggleButton</classname> é mais útil como uma base para as classes <classname>Gtk::CheckButton</classname> e <classname>Gtk::RadioButton</classname>.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToggleButton.html">Reference</ulink></para>

</sect1>

<sect1 id="sec-checkboxes">
<title>Botão de seleção</title>

<para><classname>Gtk::CheckButton</classname> é derivado de <classname>Gtk::ToggleButton</classname>. A única diferença real entre os dois é a aparência de <classname>Gtk::CheckButton</classname>. Você pode selecionar, definir e alternar um botão de seleção usando os mesmos métodos membros de um <classname>Gtk::ToggleButton</classname>.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1CheckButton.html">Reference</ulink></para>

<sect2 id="checkbutton-example"><title>Exemplo</title>

<figure id="figure-checkbutton">
  <title>Botão de seleção</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/checkbutton.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/buttons/checkbutton?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_BUTTONS_H
#define GTKMM_EXAMPLE_BUTTONS_H

#include &lt;gtkmm/window.h&gt;
#include &lt;gtkmm/checkbutton.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_clicked();

  //Child widgets:
  Gtk::CheckButton m_button;
};

#endif //GTKMM_EXAMPLE_BUTTONS_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_button("something")
{
  set_title("checkbutton example");
  set_border_width(10);

  m_button.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_clicked) );

  add(m_button);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_clicked()
{
  std::cout &lt;&lt; "The Button was clicked: state="
      &lt;&lt; (m_button.get_active() ? "true" : "false")
      &lt;&lt; std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>

</sect1>

<sect1 id="sec-radio-buttons">
<title>Botão de opção</title>

<para>Como os de seleção, botões de opção também é uma classe filho de <classname>Gtk::ToggleButton</classname>, mas eles trabalham em grupos, e só um botão de opção em um grupo pode estar selecionado por vez.</para>

<sect2 id="radiobutton-groups"><title>Grupos</title>
<para>Existem duas maneiras de definir um grupo de botões de opção. A primeira é criar os botões e configurar os seus grupos em seguida. Somente os dois primeiros construtores são usados. No exemplo a seguir, fazemos uma nova classe janela chamada <classname>RadioButtons</classname>, e então colocamos três botões nela:</para>

<programlisting>class RadioButtons : public Gtk::Window
{
public:
    RadioButtons();

protected:
    Gtk::RadioButton m_rb1, m_rb2, m_rb3;
};

RadioButtons::RadioButtons()
  : m_rb1("botão1"),
    m_rb2("botão2"),
    m_rb3("botão3")
{
    Gtk::RadioButton::Group grupo = m_rb1.get_group();
    m_rb2.set_group(grupo);
    m_rb3.set_group(grupo);
}</programlisting>
<para>Dissemos a <application>gtkmm</application> para colocar os três <classname>RadioButton</classname>s no mesmo grupo obtendo o grupo com  <methodname>get_group()</methodname> e usando <methodname>set_group()</methodname> para dizer ao outro <classname>RadioButton</classname> compartilhar esse grupo.</para>

<para lang="en">
Note that you can't just do
<programlisting lang="en">m_rb2.set_group(m_rb1.get_group()); //doesn't work</programlisting>
because the group is modified by <methodname>set_group()</methodname> and therefore
non-const.
</para>


<para>A segunda maneira de configurar os botões de opção é criar um grupo primeiro, e depois adicionar botões de opção a ele. Aqui está um exemplo:</para>
<programlisting>class RadioButtons : public Gtk::Window
{
public:
    RadioButtons();
};

RadioButtons::RadioButtons()
{
    Gtk::RadioButton::Group group;
    Gtk::RadioButton *m_rb1 = Gtk::manage(
      new Gtk::RadioButton(group,"botão 1"));
    Gtk::RadioButton *m_rb2 = manage(
      new Gtk::RadioButton(group,"botão 2"));
      Gtk::RadioButton *m_rb3 = manage(
        new Gtk::RadioButton(group,"botão 3"));
}</programlisting>

<para>Criar um novo grupo, simplesmente declarando uma variável <literal>group</literal>, do tipo <classname>Gtk::RadioButton::Group</classname>. Depois criamos três botões de opção, usando um construtor para fazer cada um parte de <literal>group</literal>.</para>
</sect2>

<sect2 id="radiobutton-methods"><title>Métodos</title>
<para><classname>RadioButtons</classname> são "desligado" quando criado; o que significa que quando você faz um grupo deles, todos eles irão estar desligado. Não esqueça de ativar um deles na utilização com <methodname>set_active()</methodname>:</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1RadioButton.html">Reference</ulink></para>

</sect2>

<sect2 id="radiobutton-example"><title>Exemplo</title>
<para>O exemplo seguinte demonstra o uso de <classname>RadioButton</classname>s:</para>

<figure id="figure-radiobutton">
  <title>Botão de opção</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/radiobuttons.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/buttons/radiobutton?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>radiobuttons.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_RADIOBUTTONS_H
#define GTKMM_EXAMPLE_RADIOBUTTONS_H

#include &lt;gtkmm/box.h&gt;
#include &lt;gtkmm/window.h&gt;
#include &lt;gtkmm/radiobutton.h&gt;
#include &lt;gtkmm/separator.h&gt;

class RadioButtons : public Gtk::Window
{
public:
  RadioButtons();
  virtual ~RadioButtons();

protected:
  //Signal handlers:
  void on_button_clicked();

  //Child widgets:
  Gtk::Box m_Box_Top, m_Box1, m_Box2;
  Gtk::RadioButton m_RadioButton1, m_RadioButton2, m_RadioButton3;
  Gtk::Separator m_Separator;
  Gtk::Button m_Button_Close;
};

#endif //GTKMM_EXAMPLE_RADIOBUTTONS_H
</programlisting>
<para lang="en">File: <filename>radiobuttons.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "radiobuttons.h"


RadioButtons::RadioButtons() :
  m_Box_Top(Gtk::ORIENTATION_VERTICAL),
  m_Box1(Gtk::ORIENTATION_VERTICAL, 10),
  m_Box2(Gtk::ORIENTATION_VERTICAL, 10),
  m_RadioButton1("button1"),
  m_RadioButton2("button2"),
  m_RadioButton3("button3"),
  m_Button_Close("close")
{
  // Set title and border of the window
  set_title("radio buttons");
  set_border_width(0);

  // Put radio buttons 2 and 3 in the same group as 1:
  Gtk::RadioButton::Group group = m_RadioButton1.get_group();
  m_RadioButton2.set_group(group);
  m_RadioButton3.set_group(group);

  // Add outer box to the window (because the window
  // can only contain a single widget)
  add(m_Box_Top);

  //Put the inner boxes and the separator in the outer box:
  m_Box_Top.pack_start(m_Box1);
  m_Box_Top.pack_start(m_Separator);
  m_Box_Top.pack_start(m_Box2);

  // Set the inner boxes' borders
  m_Box2.set_border_width(10);
  m_Box1.set_border_width(10);

  // Put the radio buttons in Box1:
  m_Box1.pack_start(m_RadioButton1);
  m_Box1.pack_start(m_RadioButton2);
  m_Box1.pack_start(m_RadioButton3);

  // Set the second button active
  m_RadioButton2.set_active();

  // Put Close button in Box2:
  m_Box2.pack_start(m_Button_Close);

  // Make the button the default widget
  m_Button_Close.set_can_default();
  m_Button_Close.grab_default();

  // Connect the clicked signal of the button to
  // RadioButtons::on_button_clicked()
  m_Button_Close.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;RadioButtons::on_button_clicked) );

  // Show all children of the window
  show_all_children();
}

RadioButtons::~RadioButtons()
{
}

void RadioButtons::on_button_clicked()
{
  hide(); //to close the application.
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "radiobuttons.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  RadioButtons buttons;

  //Shows the window and returns when it is closed.
  return app-&gt;run(buttons);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

</sect1>

</chapter>


<chapter id="chapter-range-widgets">
<title>Widgets de intervalos</title>

<para><classname>Gtk::Scale</classname> e <classname>Gtk::Scrollbar</classname> ambos herdam de <classname>Gtk::Range</classname> e compartilham muitas funcionalidades. Eles contêm uma "calha" e um "deslizante" (às vezes chamado "botão deslizante" em outros ambientes GUI). Arrastando o controle deslizante com o ponteiro movendo dentro da calha, enquanto clica nos avanços da calha o controle desliza para a localização do clique, quer inteiramente, quer por um valor designado, dependendo de qual botão do mouse é usado. Este deve ser um comportamento de rolagem familiar. </para>

<para lang="en">
As will be explained in the <link linkend="chapter-adjustment">Adjustment</link>
section, all Range widgets are associated with a
<classname>Adjustment</classname> object. To change the lower, upper, and
current values used by the widget you need to use the methods of its
<classname>Adjustment</classname>, which you can get with the
<methodname>get_adjustment()</methodname> method. The <classname>Range</classname>
widgets' default constructors create an <classname>Adjustment</classname>
automatically, or you can specify an existing
<classname>Adjustment</classname>, maybe to share it with another widget. See
the <link linkend="chapter-adjustment">Adjustments</link> section for further
details.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Range.html">Reference</ulink></para>

<sect1 id="sec-scrollbar-widgets">
<title>Widgets de barra de rolagem</title>

<para lang="en">
These are standard scrollbars. They should be used only to scroll another
widget, such as, a <classname>Gtk::Entry</classname>, or a
<classname>Gtk::Viewport</classname>, though it's usually easier to use the
<classname>Gtk::ScrolledWindow</classname> widget in most cases.
</para>

<para>A orientação de um <classname>Gtk::Scrollbar</classname> pode ser horizontal ou vertical.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Scrollbar.html">Reference</ulink></para>

</sect1>

<sect1 id="sec-scale-widgets">
<title>Widgets de escala</title>

<para lang="en">
<classname>Gtk::Scale</classname> widgets (or "sliders") allow the user to
visually select and manipulate a value within a specific range. You
might use one, for instance, to adjust the
magnification level on a zoomed preview of a picture, or to control
the brightness of a colour, or to specify the number of minutes of
inactivity before a screensaver takes over the screen.
</para>

<para lang="en">
As with <classname>Scrollbar</classname>s, the orientation can be either
horizontal or vertical. The default constructor creates an
<classname>Adjustment</classname> with all of its values set to
<literal>0.0</literal>. This isn't useful so you will need to set some
<classname>Adjustment</classname> details to get meaningful behaviour.
</para>

<sect2 id="scale-useful-methods">
<title>Métodos úteis</title>

<para>Widgets de <classname>Scala</classname> pode exibir seu valor atual com um número próximo à calha. Por padrão, eles mostram o valor, você pode mudar isso com o método <methodname>set_draw_value()</methodname>.</para>

<para lang="en">
The value displayed by a scale widget is rounded to one decimal point
by default, as is the <literal>value</literal> field in its
<classname>Gtk::Adjustment</classname>. You can change this with the
<methodname>set_digits()</methodname> method.
</para>

<para>Além disso, o valor pode ser desenhado em diferentes posições em relação à calha, especificado pelo método <methodname>set_value_pos()</methodname>.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Scale.html">Reference</ulink></para>

</sect2>
</sect1>

<sect1 id="sec-range-example">
<title>Exemplo</title>

<para lang="en">
This example displays a window with three range widgets all connected
to the same adjustment, along with a couple of controls for adjusting
some of the parameters mentioned above and in the section on
adjustments, so you can see how they affect the way these widgets work
for the user.
</para>

<figure id="figure-range-widgets">
  <title>Widgets de intervalos</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/range_widgets.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/range_widgets?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_RANGEWIDGETS_H
#define GTKMM_EXAMPLE_RANGEWIDGETS_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_checkbutton_toggled();
  void on_combo_position();
  void on_adjustment1_value_changed();
  void on_adjustment2_value_changed();
  void on_button_quit();

  //Child widgets:
  Gtk::Box m_VBox_Top, m_VBox2, m_VBox_HScale;
  Gtk::Box m_HBox_Scales, m_HBox_Combo, m_HBox_Digits, m_HBox_PageSize;

  Glib::RefPtr&lt;Gtk::Adjustment&gt; m_adjustment, m_adjustment_digits, m_adjustment_pagesize;

  Gtk::Scale m_VScale;
  Gtk::Scale m_HScale, m_Scale_Digits, m_Scale_PageSize;

  Gtk::Separator m_Separator;

  Gtk::CheckButton m_CheckButton;

  Gtk::Scrollbar m_Scrollbar;

  //Tree model columns:
  class ModelColumns : public Gtk::TreeModel::ColumnRecord
  {
  public:

    ModelColumns()
    { add(m_col_position_type); add(m_col_title); }

    Gtk::TreeModelColumn&lt;Gtk::PositionType&gt; m_col_position_type;
    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_title;
  };

  ModelColumns m_Columns;

  //Child widgets:
  Gtk::ComboBox m_ComboBox_Position;
  Glib::RefPtr&lt;Gtk::ListStore&gt; m_refTreeModel;

  Gtk::Button m_Button_Quit;
};

#endif //GTKMM_EXAMPLE_RANGEWIDGETS_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
:
  m_VBox_Top(Gtk::ORIENTATION_VERTICAL, 0),
  m_VBox2(Gtk::ORIENTATION_VERTICAL, 20),
  m_VBox_HScale(Gtk::ORIENTATION_VERTICAL, 10),
  m_HBox_Scales(Gtk::ORIENTATION_HORIZONTAL, 10),
  m_HBox_Combo(Gtk::ORIENTATION_HORIZONTAL, 10),
  m_HBox_Digits(Gtk::ORIENTATION_HORIZONTAL, 10),
  m_HBox_PageSize(Gtk::ORIENTATION_HORIZONTAL, 10),

  // Value, lower, upper, step_increment, page_increment, page_size:
  // Note that the page_size value only makes a difference for
  // scrollbar widgets, and the highest value you'll get is actually
  // (upper - page_size).
  m_adjustment( Gtk::Adjustment::create(0.0, 0.0, 101.0, 0.1, 1.0, 1.0) ),
  m_adjustment_digits( Gtk::Adjustment::create(1.0, 0.0, 5.0, 1.0, 2.0) ),
  m_adjustment_pagesize( Gtk::Adjustment::create(1.0, 1.0, 101.0) ),

  m_VScale(m_adjustment, Gtk::ORIENTATION_VERTICAL),
  m_HScale(m_adjustment, Gtk::ORIENTATION_HORIZONTAL),
  m_Scale_Digits(m_adjustment_digits),
  m_Scale_PageSize(m_adjustment_pagesize),

  // A checkbutton to control whether the value is displayed or not:
  m_CheckButton("Display value on scale widgets", 0),

  // Reuse the same adjustment again.
  // Notice how this causes the scales to always be updated
  // continuously when the scrollbar is moved.
  m_Scrollbar(m_adjustment),

  m_Button_Quit("Quit")
{
  set_title("range controls");
  set_default_size(300, 350);

  //VScale:
  m_VScale.set_digits(1);
  m_VScale.set_value_pos(Gtk::POS_TOP);
  m_VScale.set_draw_value();
  m_VScale.set_inverted(); // highest value at top

  //HScale:
  m_HScale.set_digits(1);
  m_HScale.set_value_pos(Gtk::POS_TOP);
  m_HScale.set_draw_value();

  add(m_VBox_Top);
  m_VBox_Top.pack_start(m_VBox2);
  m_VBox2.set_border_width(10);
  m_VBox2.pack_start(m_HBox_Scales);

  //Put VScale and HScale (above scrollbar) side-by-side.
  m_HBox_Scales.pack_start(m_VScale);
  m_HBox_Scales.pack_start(m_VBox_HScale);

  m_VBox_HScale.pack_start(m_HScale);

  //Scrollbar:
  m_VBox_HScale.pack_start(m_Scrollbar);

  //CheckButton:
  m_CheckButton.set_active();
  m_CheckButton.signal_toggled().connect( sigc::mem_fun(*this,
    &amp;ExampleWindow::on_checkbutton_toggled) );
  m_VBox2.pack_start(m_CheckButton, Gtk::PACK_SHRINK);

  //Position ComboBox:
  //Create the Tree model:
  m_refTreeModel = Gtk::ListStore::create(m_Columns);
  m_ComboBox_Position.set_model(m_refTreeModel);
  m_ComboBox_Position.pack_start(m_Columns.m_col_title);

  //Fill the ComboBox's Tree Model:
  Gtk::TreeModel::Row row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_position_type] = Gtk::POS_TOP;
  row[m_Columns.m_col_title] = "Top";
  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_position_type] = Gtk::POS_BOTTOM;
  row[m_Columns.m_col_title] = "Bottom";
  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_position_type] = Gtk::POS_LEFT;
  row[m_Columns.m_col_title] = "Left";
  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_position_type] = Gtk::POS_RIGHT;
  row[m_Columns.m_col_title] = "Right";

  m_VBox2.pack_start(m_HBox_Combo, Gtk::PACK_SHRINK);
  m_HBox_Combo.pack_start(
    *Gtk::manage(new Gtk::Label("Scale Value Position:", 0)), Gtk::PACK_SHRINK);
  m_HBox_Combo.pack_start(m_ComboBox_Position);
  m_ComboBox_Position.signal_changed().connect( sigc::mem_fun(*this, &amp;ExampleWindow::on_combo_position) );
  m_ComboBox_Position.set_active(0); // Top

  //Digits:
  m_HBox_Digits.pack_start(
    *Gtk::manage(new Gtk::Label("Scale Digits:", 0)), Gtk::PACK_SHRINK);
  m_Scale_Digits.set_digits(0);
  m_adjustment_digits-&gt;signal_value_changed().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_adjustment1_value_changed));
  m_HBox_Digits.pack_start(m_Scale_Digits);

  //Page Size:
  m_HBox_PageSize.pack_start(
    *Gtk::manage(new Gtk::Label("Scrollbar Page Size:", 0)),
    Gtk::PACK_SHRINK);
  m_Scale_PageSize.set_digits(0);
  m_adjustment_pagesize-&gt;signal_value_changed().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_adjustment2_value_changed));
  m_HBox_PageSize.pack_start(m_Scale_PageSize);

  m_VBox2.pack_start(m_HBox_Digits, Gtk::PACK_SHRINK);
  m_VBox2.pack_start(m_HBox_PageSize, Gtk::PACK_SHRINK);
  m_VBox_Top.pack_start(m_Separator, Gtk::PACK_SHRINK);
  m_VBox_Top.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);

  m_Button_Quit.set_can_default();
  m_Button_Quit.grab_default();
  m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_button_quit));
  m_Button_Quit.set_border_width(10);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_checkbutton_toggled()
{
  m_VScale.set_draw_value(m_CheckButton.get_active());
  m_HScale.set_draw_value(m_CheckButton.get_active());
}

void ExampleWindow::on_combo_position()
{
  Gtk::TreeModel::iterator iter = m_ComboBox_Position.get_active();
  if(!iter)
    return;

  Gtk::TreeModel::Row row = *iter;
  if(!row)
    return;

  const Gtk::PositionType postype = row[m_Columns.m_col_position_type];

  m_VScale.set_value_pos(postype);
  m_HScale.set_value_pos(postype);
}

void ExampleWindow::on_adjustment1_value_changed()
{
  const double val = m_adjustment_digits-&gt;get_value();
  m_VScale.set_digits((int)val);
  m_HScale.set_digits((int)val);
}

void ExampleWindow::on_adjustment2_value_changed()
{
  const double val = m_adjustment_pagesize-&gt;get_value();
  m_adjustment-&gt;set_page_size(val);
  m_adjustment-&gt;set_page_increment(val);

  // Note that we don't have to emit the "changed" signal
  // because gtkmm does this for us.
}

void ExampleWindow::on_button_quit()
{
  hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect1>

</chapter>

<chapter id="chapter-misc-widgets">
<title>Diversos widgets</title>

<sect1 id="sec-labels">
<title>Rótulo</title>

<para lang="en">
Labels are the  main method of placing non-editable text in windows, for
instance to place a title next to a <classname>Entry</classname> widget. You
can specify the text in the constructor, or later with the
<methodname>set_text()</methodname> or <methodname>set_markup()</methodname> methods.
</para>

<para lang="en">
The width of the label will be adjusted automatically. You can produce multi-line labels by putting line breaks ("\n") in the label string.
</para>

<para lang="en">
The label text can be justified using the <methodname>set_justify()</methodname>
method. The widget is also capable of word-wrapping, which can be activated
with <methodname>set_line_wrap()</methodname>.
</para>

<para lang="en">
Gtk::Label support some simple formatting, for instance allowing you to make some
text bold, colored, or larger. You can do this by providing a string to
<methodname>set_markup()</methodname>, using the <ulink url="http://developer.gnome.org/pango/unstable/PangoMarkupFormat.html">Pango Markup syntax</ulink>. For instance,
<code>
&lt;b&gt;bold text&lt;/b&gt; and &lt;s&gt;strikethrough text&lt;/s&gt;
</code>
.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Label.html">Reference</ulink></para>

<sect2 id="label-example"><title>Exemplo</title>
<para lang="en">
Below is a short example to illustrate these functions. This example
makes use of the Frame widget to better demonstrate the label styles.
 (The Frame widget is explained in the <link linkend="sec-frame">Frame</link> section.)
It is possible that the first character in <literal>m_Label_Normal</literal> is shown
underlined only when you press the <keycap>Alt</keycap> key.
</para>

<figure id="figure-label">
  <title>Rótulo</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/label.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/label?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:

  //Child widgets:
  Gtk::Box m_HBox;
  Gtk::Box m_VBox, m_VBox2;
  Gtk::Frame m_Frame_Normal, m_Frame_Multi, m_Frame_Left, m_Frame_Right,
    m_Frame_LineWrapped, m_Frame_FilledWrapped, m_Frame_Underlined;
  Gtk::Label m_Label_Normal, m_Label_Multi, m_Label_Left, m_Label_Right,
    m_Label_LineWrapped, m_Label_FilledWrapped, m_Label_Underlined;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
:
  m_HBox(Gtk::ORIENTATION_HORIZONTAL, 5),
  m_VBox(Gtk::ORIENTATION_VERTICAL, 5),
  m_VBox2(Gtk::ORIENTATION_VERTICAL, 5),
  m_Frame_Normal("Normal Label"),
  m_Frame_Multi("Multi-line Label"),
  m_Frame_Left("Left Justified Label"),
  m_Frame_Right("Right Justified Label"),
  m_Frame_LineWrapped("Line wrapped label"),
  m_Frame_FilledWrapped("Filled, wrapped label"),
  m_Frame_Underlined("Underlined label"),
  m_Label_Normal("_This is a Normal label", true),
  m_Label_Multi("This is a Multi-line label.\nSecond line\nThird line"),
  m_Label_Left("This is a Left-Justified\nMulti-line label.\nThird line"),
  m_Label_Right("This is a Right-Justified\nMulti-line label.\nThird line"),
  m_Label_Underlined("This label is underlined!\n"
          "This one is underlined in quite a funky fashion")
{
  set_title("Label");
  set_border_width(5);

  add(m_HBox);

  m_HBox.pack_start(m_VBox, Gtk::PACK_SHRINK);

  m_Frame_Normal.add(m_Label_Normal);
  m_VBox.pack_start(m_Frame_Normal, Gtk::PACK_SHRINK);

  m_Frame_Multi.add(m_Label_Multi);
  m_VBox.pack_start(m_Frame_Multi, Gtk::PACK_SHRINK);

  m_Label_Left.set_justify(Gtk::JUSTIFY_LEFT);
  m_Frame_Left.add(m_Label_Left);
  m_VBox.pack_start(m_Frame_Left, Gtk::PACK_SHRINK);

  m_Label_Right.set_justify(Gtk::JUSTIFY_RIGHT);
  m_Frame_Right.add(m_Label_Right);
  m_VBox.pack_start(m_Frame_Right, Gtk::PACK_SHRINK);

  m_HBox.pack_start(m_VBox2, Gtk::PACK_SHRINK);

  m_Label_LineWrapped.set_text(
          "This is an example of a line-wrapped label.  It "
          /* add a big space to the next line to test spacing */
          "should not be taking up the entire             "
          "width allocated to it, but automatically "
          "wraps the words to fit.  "
          "The time has come, for all good men, to come to "
          "the aid of their party.  "
          "The sixth sheik's six sheep's sick.\n"
          "     It supports multiple paragraphs correctly, "
          "and  correctly   adds "
          "many          extra  spaces. ");
  m_Label_LineWrapped.set_line_wrap();
  m_Frame_LineWrapped.add(m_Label_LineWrapped);
  m_VBox2.pack_start(m_Frame_LineWrapped, Gtk::PACK_SHRINK);

  m_Label_FilledWrapped.set_text(
          "This is an example of a line-wrapped, filled label.  "
          "It should be taking "
          "up the entire              width allocated to it.  "
          "Here is a sentence to prove "
          "my point.  Here is another sentence. "
          "Here comes the sun, do de do de do.\n"
          "    This is a new paragraph.\n"
          "    This is another newer, longer, better "
          "paragraph.  It is coming to an end, "
          "unfortunately.");
  m_Label_FilledWrapped.set_justify(Gtk::JUSTIFY_FILL);
  m_Label_FilledWrapped.set_line_wrap();
  m_Frame_FilledWrapped.add(m_Label_FilledWrapped);
  m_VBox2.pack_start(m_Frame_FilledWrapped, Gtk::PACK_SHRINK);

  m_Label_Underlined.set_justify(Gtk::JUSTIFY_LEFT);
  m_Label_Underlined.set_pattern (
          "_________________________ _ _________ _ ______"
          "     __ _______ ___");
  m_Frame_Underlined.add(m_Label_Underlined);
  m_VBox2.pack_start(m_Frame_Underlined, Gtk::PACK_SHRINK);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

</sect1>

<sect1 id="sec-text-entry">
<title>Entrada</title>

<sect2 id="sec-text-entry-simple">
<title>Uso simples</title>

<para>Campos de entrada permite o usuário digitar texto. Você pode alterar o conteúdo com o método <methodname>set_text()</methodname>, e ler o conteúdo atual com o método <methodname>get_text()</methodname>.</para>

<para lang="en">
Occasionally you might want to make an <classname>Entry</classname> widget
read-only. This can be done by passing <literal>false</literal> to the
<methodname>set_editable()</methodname> method.
</para>

<para>Para entrada de senhas, frases e outras informações que você não deseja mostrar na tela, chamando <methodname>set_visibility()</methodname> com <literal>false</literal> irá fazer com que o texto seja escondido.</para>

<para lang="en">
You might want to be notified whenever the user types in a text entry widget.
<classname>Gtk::Entry</classname> provides two signals,
<literal>activate</literal> and <literal>changed</literal>, for this purpose.
<literal>activate</literal> is emitted when the user presses the Enter key in
a text-entry widget; <literal>changed</literal> is emitted when the text in
the widget changes. You can use these, for instance, to validate or filter
the text the user types. Moving the keyboard focus to another widget may also
signal that the user has finished entering text. The <literal>focus_out_event</literal>
signal that <classname>Gtk::Entry</classname> inherits from
<classname>Gtk::Widget</classname> can notify you when that happens.
The <link linkend="sec-comboboxentry">ComboBox with an Entry</link> section
contains example programs that use these signals.
</para>

<para lang="en">
If you pass <literal>true</literal> to the <methodname>set_activates_default()</methodname>
method, pressing Enter in the <classname>Gtk::Entry</classname> will activate
the default widget for the window containing the <classname>Gtk::Entry</classname>.
This is especially useful in dialog boxes. The default widget is usually one of
the dialog buttons, which e.g. will close the dialog box. To set a widget as the
default widget, use <methodname>Gtk::Widget::set_can_default()</methodname> and
<methodname>Gtk::Widget::grab_default()</methodname>.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Entry.html">Reference</ulink></para>

<sect3 id="entry-example"><title>Exemplo de entrada simples</title>
<para lang="en">
This example uses <classname>Gtk::Entry</classname>. It also has two
<classname>CheckButton</classname>s, with which you can toggle the editable and
visible flags.
</para>

<figure id="figure-entry-simple">
  <title>Entrada</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/entry.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/entry/simple?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_checkbox_editable_toggled();
  void on_checkbox_visibility_toggled();
  void on_button_close();

  //Child widgets:
  Gtk::Box m_HBox;
  Gtk::Box m_VBox;
  Gtk::Entry m_Entry;
  Gtk::Button m_Button_Close;
  Gtk::CheckButton m_CheckButton_Editable, m_CheckButton_Visible;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_Close("Close"),
  m_CheckButton_Editable("Editable"),
  m_CheckButton_Visible("Visible")
{
  set_size_request(200, 100);
  set_title("Gtk::Entry");

  add(m_VBox);

  m_Entry.set_max_length(50);
  m_Entry.set_text("hello");
  m_Entry.set_text(m_Entry.get_text() + " world");
  m_Entry.select_region(0, m_Entry.get_text_length());
  m_VBox.pack_start(m_Entry);

  // Note that add() can also be used instead of pack_xxx()
  m_VBox.add(m_HBox);

  m_HBox.pack_start(m_CheckButton_Editable);
  m_CheckButton_Editable.signal_toggled().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_checkbox_editable_toggled) );
  m_CheckButton_Editable.set_active(true);

  m_HBox.pack_start(m_CheckButton_Visible);
  m_CheckButton_Visible.signal_toggled().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_checkbox_visibility_toggled) );
  m_CheckButton_Visible.set_active(true);

  m_Button_Close.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_close) );
  m_VBox.pack_start(m_Button_Close);
  m_Button_Close.set_can_default();
  m_Button_Close.grab_default();

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_checkbox_editable_toggled()
{
  m_Entry.set_editable(m_CheckButton_Editable.get_active());
}

void ExampleWindow::on_checkbox_visibility_toggled()
{
  m_Entry.set_visibility(m_CheckButton_Visible.get_active());
}

void ExampleWindow::on_button_close()
{
  hide();
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect3>

</sect2>

<sect2 id="sec-text-entry-completion">
<title>Entrada com auto completar</title>
<para lang="en">A <classname>Entry</classname> widget can offer a drop-down list of
pre-existing choices based on the first few characters typed by the user. For
instance, a search dialog could suggest text from previous searches.
</para>

<para lang="en">To enable this functionality, you must create a
<classname>EntryCompletion</classname> object, and provide it to the
<classname>Entry</classname> widget via the
<methodname>set_completion()</methodname> method.</para>

<para lang="en">The <classname>EntryCompletion</classname> may use a
<classname>TreeModel</classname> containing possible entries, specified with
<methodname>set_model()</methodname>. You should then call
<methodname>set_text_column()</methodname> to specify which of your model columns
should be used to match possible text entries.</para>

<para lang="en">Alternatively, if a complete list of possible entries
would be too large or too inconvenient to generate, a callback slot may instead
be specified with <methodname>set_match_func()</methodname>.
This is also useful if you wish to match on a part of the string other
than the start.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1EntryCompletion.html">Reference</ulink></para>

<sect3 id="entry-completion-example"><title>Exemplo de entrada com auto completar</title>
<para lang="en">
This example creates a <classname>Gtk::EntryCompletion</classname> and associates
it with a <classname>Gtk::Entry</classname> widget. The completion uses a
<classname>Gtk::TreeModel</classname> of possible entries, and some additional
actions.
</para>

<figure id="figure-entry-completion">
  <title>Entrada com auto completar</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/entry_completion.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/entry/completion?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_close();

  void on_completion_action_activated(int index);

  //See the comment in the implementation:
  //bool on_completion_match(const Glib::ustring&amp; key, const Gtk::TreeModel::const_iterator&amp; iter);


  //Tree model columns, for the EntryCompletion's filter model:
  class ModelColumns : public Gtk::TreeModel::ColumnRecord
  {
  public:

    ModelColumns()
    { add(m_col_id); add(m_col_name); }

    Gtk::TreeModelColumn&lt;unsigned int&gt; m_col_id;
    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
  };

  ModelColumns m_Columns;

  typedef std::map&lt;int, Glib::ustring&gt; type_actions_map;
  type_actions_map m_CompletionActions;
  
  //Child widgets:
  Gtk::Box m_HBox;
  Gtk::Box m_VBox;
  Gtk::Entry m_Entry;
  Gtk::Label m_Label;
  Gtk::Button m_Button_Close;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Label("Press a or b to see a list of possible completions and actions."),
  m_Button_Close("Close")
{
  //set_size_request(200, 100);
  set_title("Gtk::EntryCompletion");

  add(m_VBox);
  m_VBox.pack_start(m_Entry, Gtk::PACK_SHRINK);

  m_VBox.pack_start(m_Label, Gtk::PACK_EXPAND_WIDGET);

  m_Button_Close.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_close) );
  m_VBox.pack_start(m_Button_Close, Gtk::PACK_SHRINK);
  m_Button_Close.set_can_default();
  m_Button_Close.grab_default();

  //Add an EntryCompletion:
  Glib::RefPtr&lt;Gtk::EntryCompletion&gt; completion =
      Gtk::EntryCompletion::create();
  m_Entry.set_completion(completion);

  //Create and fill the completion's filter model
  Glib::RefPtr&lt;Gtk::ListStore&gt; refCompletionModel =
      Gtk::ListStore::create(m_Columns);
  completion-&gt;set_model(refCompletionModel);

  // For more complex comparisons, use a filter match callback, like this.
  // See the comment below for more details:
  //completion-&gt;set_match_func( sigc::mem_fun(*this,
              //&amp;ExampleWindow::on_completion_match) );

  //Fill the TreeView's model
  Gtk::TreeModel::Row row = *(refCompletionModel-&gt;append());
  row[m_Columns.m_col_id] = 1;
  row[m_Columns.m_col_name] = "Alan Zebedee";

  row = *(refCompletionModel-&gt;append());
  row[m_Columns.m_col_id] = 2;
  row[m_Columns.m_col_name] = "Adrian Boo";

  row = *(refCompletionModel-&gt;append());
  row[m_Columns.m_col_id] = 3;
  row[m_Columns.m_col_name] = "Bob McRoberts";

  row = *(refCompletionModel-&gt;append());
  row[m_Columns.m_col_id] = 4;
  row[m_Columns.m_col_name] = "Bob McBob";

  //Tell the completion what model column to use to
  //- look for a match (when we use the default matching, instead of
  //  set_match_func().
  //- display text in the entry when a match is found.
  completion-&gt;set_text_column(m_Columns.m_col_name);

  //Add actions to the completion:
  //These are just extra items shown at the bottom of the list of possible
  //completions.

  //Remember them for later.
  m_CompletionActions[0] = "Use Wizard";
  m_CompletionActions[1] = "Browse for Filename";

  for(type_actions_map::iterator iter = m_CompletionActions.begin();
          iter != m_CompletionActions.end(); ++iter)
  {
    int position = iter-&gt;first;
    Glib::ustring title = iter-&gt;second;
    completion-&gt;insert_action_text(title, position);
  }

  completion-&gt;signal_action_activated().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_completion_action_activated) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_close()
{
  hide();
}

/* You can do more complex matching with a handler like this.
 * For instance, you could check for substrings inside the string instead of the start,
 * or you could look for the key in extra model columns as well as the model column that will be displayed.
 * The code here is not actually more complex - it's a reimplementation of the default behaviour.
 *
bool ExampleWindow::on_completion_match(const Glib::ustring&amp; key, const
        Gtk::TreeModel::const_iterator&amp; iter)
{
  if(iter)
  {
    Gtk::TreeModel::Row row = *iter;

    Glib::ustring::size_type key_length = key.size();
    Glib::ustring filter_string = row[m_Columns.m_col_name];

    Glib::ustring filter_string_start = filter_string.substr(0, key_length);
    //The key is lower-case, even if the user input is not.
    filter_string_start = filter_string_start.lowercase();

    if(key == filter_string_start)
      return true; //A match was found.
  }

  return false; //No match.
}
*/

void ExampleWindow::on_completion_action_activated(int index)
{
  type_actions_map::iterator iter = m_CompletionActions.find(index);
  if(iter != m_CompletionActions.end()) //If it's in the map
  {
    Glib::ustring title = iter-&gt;second;
    std::cout &lt;&lt; "Action selected: " &lt;&lt; title &lt;&lt; std::endl;
  }
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect3>
</sect2>

<sect2 id="sec-text-entry-icons">
<title>Entrada com ícones</title>
<para lang="en">An <classname>Entry</classname> widget can show an icon at the start or
end of the text area. The icon can be specifed by methods such as
<methodname>set_icon_from_pixbuf()</methodname> or
<methodname>set_icon_from_icon_name()</methodname>. An application can respond to the
user pressing the icon by handling the
<methodname>signal_icon_press</methodname> signal.</para>

<sect3 id="entry-icon-example"><title>Exemplo de entrada com ícones</title>
<para lang="en">
This example shows a <classname>Gtk::Entry</classname> widget with a named
search icon, and prints text to the terminal when the icon is pressed.
</para>

<figure id="figure-entry-icon">
  <title>Entrada com ícone</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/entry_icon.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/entry/icon?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_icon_pressed(Gtk::EntryIconPosition icon_pos, const GdkEventButton* event);
  void on_button_close();

  //Child widgets:
  Gtk::Box m_VBox;
  Gtk::Entry m_Entry;
  Gtk::Button m_Button_Close;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_Close("Close")
{
  set_title("Gtk::Entry");

  add(m_VBox);

  m_Entry.set_max_length(50);
  m_Entry.set_text("Hello world");
  m_VBox.pack_start(m_Entry, Gtk::PACK_SHRINK);

  m_Entry.set_icon_from_icon_name("edit-find");
  m_Entry.signal_icon_press().connect( sigc::mem_fun(*this, &amp;ExampleWindow::on_icon_pressed) );
 

  m_Button_Close.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_close) );
  m_VBox.pack_start(m_Button_Close, Gtk::PACK_SHRINK);
  m_Button_Close.set_can_default();
  m_Button_Close.grab_default();

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_icon_pressed(Gtk::EntryIconPosition /* icon_pos */, const GdkEventButton* /* event */)
{
  std::cout &lt;&lt; "Icon pressed." &lt;&lt; std::endl;
}

void ExampleWindow::on_button_close()
{
  hide();
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect3>
</sect2>

<sect2 id="sec-text-entry-progress">
<title>Entrada com barra de progresso</title>
<para lang="en">An <classname>Entry</classname> widget can show a progress bar inside the
text area, under the entered text. The progress bar will be shown if the
<methodname>set_progress_fraction()</methodname> or
<methodname>set_progress_pulse_step()</methodname> methods are called.</para>

<sect3 id="entry-progress-example"><title>Exemplo de entrada com barra de progresso</title>
<para lang="en">
This example shows a <classname>Gtk::Entry</classname> widget with a progress
bar.
</para>

<figure id="figure-entry-progress">
  <title>Entrada com barra de progresso</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/entry_progress.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/entry/progress?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  bool on_timeout();
  void on_button_close();

  //Child widgets:
  Gtk::Box m_VBox;
  Gtk::Entry m_Entry;
  Gtk::Button m_Button_Close;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_Close("Close")
{
  set_title("Gtk::Entry");

  add(m_VBox);

  m_Entry.set_max_length(50);
  m_Entry.set_text("Hello world");
  m_VBox.pack_start(m_Entry, Gtk::PACK_SHRINK);

  //Change the progress fraction every 0.1 second:
  Glib::signal_timeout().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::on_timeout), 
    100
  );

  m_Button_Close.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_close) );
  m_VBox.pack_start(m_Button_Close, Gtk::PACK_SHRINK);
  m_Button_Close.set_can_default();
  m_Button_Close.grab_default();

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

bool ExampleWindow::on_timeout()
{
  static double fraction = 0;
  m_Entry.set_progress_fraction(fraction);

  fraction += 0.01;
  if(fraction &gt; 1)
    fraction = 0;

  return true;
}

void ExampleWindow::on_button_close()
{
  hide();
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect3>
</sect2>

</sect1>

<sect1 id="sec-spinbutton">
<title>SpinButton</title>

<para lang="en">
A <classname>SpinButton</classname> allows the user to select a value from a
range of numeric values. It has an <classname>Entry</classname> widget with increment and decrement buttons
at the side. Clicking the buttons causes the value to 'spin' up and down across
the range of possible values. The <classname>Entry</classname> widget may also
be used to enter a value directly.
</para>

<para lang="en">
The value can have an adjustable number of decimal places, and the step size is
configurable. <classname>SpinButton</classname>s have an 'auto-repeat' feature
as well: holding down the increment or decrement button can optionally cause the value to
change more quickly the longer the button is held down.
</para>

<para lang="en">
<classname>SpinButton</classname>s use an <link linkend="chapter-adjustment">Adjustment</link> object to hold information about
the range of values. These Adjustment attributes are used by the Spin Button
like so:
<itemizedlist>
<listitem>

<para lang="en">
 <literal>value</literal>: value for the Spin Button
</para>
</listitem>
<listitem>

<para lang="en">
 <literal>lower</literal>: lower range value
</para>
</listitem>
<listitem>

<para lang="en">
 <literal>upper</literal>: upper range value
</para>
</listitem>
<listitem>
<para lang="en">
 <literal>step_increment</literal>: value to increment/decrement when pressing
mouse button 1 on a button
</para>
</listitem>
<listitem>

<para lang="en">
 <literal>page_increment</literal>: value to increment/decrement when pressing
mouse button 2 on a button
</para>
</listitem>
<listitem>

<para lang="en">
 <literal>page_size</literal>: unused
</para>
</listitem>

</itemizedlist>
</para>

<para>Além disso, o botão 3 do mouse pode ser usado para ir diretamente aos valores <literal>upper</literal> ou <literal>lower</literal>.</para>

<para lang="en">
The <classname>SpinButton</classname> can create a default
<classname>Adjustment</classname>, which you can access via the
<methodname>get_adjustment()</methodname> method, or you can specify an existing
<classname>Adjustment</classname> in the constructor.
</para>


<sect2 id="spinbutton-methods"><title>Métodos</title>

<para lang="en">
The number of decimal places can be altered using the
<methodname>set_digits()</methodname> method.
</para>

<para lang="en">
You can set the spinbutton's value using the <methodname>set_value()</methodname>
method, and retrieve it with <methodname>get_value()</methodname>.
</para>

<para lang="en">
The <methodname>spin()</methodname> method 'spins' the
<classname>SpinButton</classname>, as if its increment or decrement button had been clicked.
You need to specify a <classname>Gtk::SpinType</classname> to specify the
direction or new position.
</para>

<para lang="en">
To prevent the user from typing non-numeric characters into the entry box, pass
<literal>true</literal> to the <methodname>set_numeric()</methodname> method.
</para>

<para lang="en">
To make the <classname>SpinButton</classname> 'wrap' between its upper and
lower bounds, use the <methodname>set_wrap()</methodname> method.
</para>

<para lang="en">
To force it to snap to the nearest <literal>step_increment</literal>,
use <methodname>set_snap_to_ticks()</methodname>.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1SpinButton.html">Reference</ulink></para>

</sect2>

<sect2 id="spinbutton-example"><title>Exemplo</title>

<para lang="en">
Here's an example of a <classname>SpinButton</classname> in action:
</para>

<figure id="figure-spinbutton">
  <title>SpinButton</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/spinbutton.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/spinbutton?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_checkbutton_snap();
  void on_checkbutton_numeric();
  void on_spinbutton_digits_changed();
  void on_button_close();

  enum enumValueFormats
  {
    VALUE_FORMAT_INT,
    VALUE_FORMAT_FLOAT
  };
  void on_button_getvalue(enumValueFormats display);

  //Child widgets:
  Gtk::Frame m_Frame_NotAccelerated, m_Frame_Accelerated;
  Gtk::Box m_HBox_NotAccelerated, m_HBox_Accelerated,
    m_HBox_Buttons;
  Gtk::Box m_VBox_Main, m_VBox, m_VBox_Day, m_VBox_Month, m_VBox_Year,
    m_VBox_Accelerated, m_VBox_Value, m_VBox_Digits;
  Gtk::Label m_Label_Day, m_Label_Month, m_Label_Year,
    m_Label_Value, m_Label_Digits,
    m_Label_ShowValue;
  Glib::RefPtr&lt;Gtk::Adjustment&gt; m_adjustment_day, m_adjustment_month, m_adjustment_year,
    m_adjustment_value, m_adjustment_digits;
  Gtk::SpinButton m_SpinButton_Day, m_SpinButton_Month, m_SpinButton_Year,
    m_SpinButton_Value, m_SpinButton_Digits;
  Gtk::CheckButton m_CheckButton_Snap, m_CheckButton_Numeric;
  Gtk::Button m_Button_Int, m_Button_Float, m_Button_Close;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;
#include &lt;cstdio&gt;

ExampleWindow::ExampleWindow()
:
  m_Frame_NotAccelerated("Not accelerated"),
  m_Frame_Accelerated("Accelerated"),
  m_VBox_Main(Gtk::ORIENTATION_VERTICAL, 5),
  m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_VBox_Day(Gtk::ORIENTATION_VERTICAL),
  m_VBox_Month(Gtk::ORIENTATION_VERTICAL),
  m_VBox_Year(Gtk::ORIENTATION_VERTICAL),
  m_VBox_Accelerated(Gtk::ORIENTATION_VERTICAL),
  m_VBox_Value(Gtk::ORIENTATION_VERTICAL),
  m_VBox_Digits(Gtk::ORIENTATION_VERTICAL),
  m_Label_Day("Day: ", Gtk::ALIGN_START),
  m_Label_Month("Month: ", Gtk::ALIGN_START),
  m_Label_Year("Year: ", Gtk::ALIGN_START),
  m_Label_Value("Value: ", Gtk::ALIGN_START),
  m_Label_Digits("Digits: ", Gtk::ALIGN_START),
  m_adjustment_day( Gtk::Adjustment::create(1.0, 1.0, 31.0, 1.0, 5.0, 0.0) ),
  m_adjustment_month( Gtk::Adjustment::create(1.0, 1.0, 12.0, 1.0, 5.0, 0.0) ),
  m_adjustment_year( Gtk::Adjustment::create(2012.0, 1.0, 2200.0, 1.0, 100.0, 0.0) ),
  m_adjustment_value( Gtk::Adjustment::create(0.0, -10000.0, 10000.0, 0.5, 100.0, 0.0) ),
  m_adjustment_digits( Gtk::Adjustment::create(2.0, 1.0, 5.0, 1.0, 1.0, 0.0) ),
  m_SpinButton_Day(m_adjustment_day),
  m_SpinButton_Month(m_adjustment_month),
  m_SpinButton_Year(m_adjustment_year),
  m_SpinButton_Value(m_adjustment_value, 1.0, 2),
  m_SpinButton_Digits(m_adjustment_digits),
  m_CheckButton_Snap("Snap to 0.5-ticks"),
  m_CheckButton_Numeric("Numeric only input mode"),
  m_Button_Int("Value as Int"),
  m_Button_Float("Value as Float"),
  m_Button_Close("Close")
{
  set_title("SpinButton");

  m_VBox_Main.set_border_width(10);
  add(m_VBox_Main);

  m_VBox_Main.pack_start(m_Frame_NotAccelerated);

  m_VBox.set_border_width(5);
  m_Frame_NotAccelerated.add(m_VBox);

  /* Day, month, year spinners */

  m_VBox.pack_start(m_HBox_NotAccelerated, Gtk::PACK_EXPAND_WIDGET, 5);

  m_VBox_Day.pack_start(m_Label_Day);

  m_SpinButton_Day.set_wrap();

  m_VBox_Day.pack_start(m_SpinButton_Day);

  m_HBox_NotAccelerated.pack_start(m_VBox_Day, Gtk::PACK_EXPAND_WIDGET, 5);

  m_VBox_Month.pack_start(m_Label_Month);

  m_SpinButton_Month.set_wrap();
  m_VBox_Month.pack_start(m_SpinButton_Month);

  m_HBox_NotAccelerated.pack_start(m_VBox_Month, Gtk::PACK_EXPAND_WIDGET, 5);

  m_VBox_Year.pack_start(m_Label_Year);

  m_SpinButton_Year.set_wrap();
  m_SpinButton_Year.set_size_request(55, -1);
  m_VBox_Year.pack_start(m_SpinButton_Year);

  m_HBox_NotAccelerated.pack_start(m_VBox_Year, Gtk::PACK_EXPAND_WIDGET, 5);

  //Accelerated:
  m_VBox_Main.pack_start(m_Frame_Accelerated);

  m_VBox_Accelerated.set_border_width(5);
  m_Frame_Accelerated.add(m_VBox_Accelerated);

  m_VBox_Accelerated.pack_start(m_HBox_Accelerated, Gtk::PACK_EXPAND_WIDGET, 5);

  m_HBox_Accelerated.pack_start(m_VBox_Value, Gtk::PACK_EXPAND_WIDGET, 5);

  m_VBox_Value.pack_start(m_Label_Value);

  m_SpinButton_Value.set_wrap();
  m_SpinButton_Value.set_size_request(100, -1);
  m_VBox_Value.pack_start(m_SpinButton_Value);

  m_HBox_Accelerated.pack_start(m_VBox_Digits, Gtk::PACK_EXPAND_WIDGET, 5);

  m_VBox_Digits.pack_start(m_Label_Digits);

  m_SpinButton_Digits.set_wrap();
  m_adjustment_digits-&gt;signal_value_changed().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_spinbutton_digits_changed) );

  m_VBox_Digits.pack_start(m_SpinButton_Digits);


  //CheckButtons:
  m_VBox_Accelerated.pack_start(m_CheckButton_Snap);
  m_CheckButton_Snap.set_active();
  m_CheckButton_Snap.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_checkbutton_snap) );

  m_VBox_Accelerated.pack_start(m_CheckButton_Numeric);
  m_CheckButton_Numeric.set_active();
  m_CheckButton_Numeric.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_checkbutton_numeric) );


  //Buttons:
  m_VBox_Accelerated.pack_start (m_HBox_Buttons, Gtk::PACK_SHRINK, 5);

  m_Button_Int.signal_clicked().connect( sigc::bind( sigc::mem_fun(*this,
                  &amp;ExampleWindow::on_button_getvalue), VALUE_FORMAT_INT) );
  m_HBox_Buttons.pack_start(m_Button_Int, Gtk::PACK_EXPAND_WIDGET, 5);

  m_Button_Float.signal_clicked().connect( sigc::bind( sigc::mem_fun(*this,
                  &amp;ExampleWindow::on_button_getvalue), VALUE_FORMAT_FLOAT) );
  m_HBox_Buttons.pack_start(m_Button_Float, Gtk::PACK_EXPAND_WIDGET, 5);

  m_VBox_Accelerated.pack_start(m_Label_ShowValue);
  m_Label_ShowValue.set_text("0");

  //Close button:
  m_Button_Close.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_close) );
  m_VBox_Main.pack_start(m_Button_Close, Gtk::PACK_SHRINK);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}


void ExampleWindow::on_button_close()
{
  hide();
}

void ExampleWindow::on_checkbutton_snap()
{
  m_SpinButton_Value.set_snap_to_ticks( m_CheckButton_Snap.get_active() );
}

void ExampleWindow::on_checkbutton_numeric()
{
  m_SpinButton_Value.set_numeric( m_CheckButton_Numeric.get_active() );
}

void ExampleWindow::on_spinbutton_digits_changed()
{
  m_SpinButton_Value.set_digits( m_SpinButton_Digits.get_value_as_int() );
}

void ExampleWindow::on_button_getvalue(enumValueFormats display)
{
  gchar buf[32];

  if (display == VALUE_FORMAT_INT)
    sprintf (buf, "%d", m_SpinButton_Value.get_value_as_int());
  else
    sprintf (buf, "%0.*f", m_SpinButton_Value.get_digits(),
            m_SpinButton_Value.get_value());

  m_Label_ShowValue.set_text(buf);
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

</sect1>

<sect1 id="sec-progressbar">
<title lang="en">ProgressBar</title>

<para lang="en">
Progress bars are used to show the status of an ongoing operation. For
instance, a <classname>ProgressBar</classname> can show how much of a task has
been completed.
</para>

<para lang="en">
To change the value shown, use the <methodname>set_fraction()</methodname> method,
passing a <type>double</type> between 0.0 and 1.0 to provide the new percentage.
</para>

<para lang="en">
A <classname>ProgressBar</classname> is horizontal and left-to-right by default,
but you can change it to a vertical progress bar by using the
<methodname>set_orientation()</methodname> method.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ProgressBar.html">Reference</ulink></para>

<sect2 id="progressbar-activity-mode">
<title>Modo de atividade</title>
<para lang="en">
Besides indicating the amount of progress that has occured, the
progress bar can also be used to indicate that there is some activity;
this is done by placing the progress bar in <emphasis>activity mode</emphasis>. In
this mode, the progress bar displays a small rectangle which moves
back and forth. Activity mode is useful in situations where the
progress of an operation cannot be calculated as a value range (e.g.,
receiving a file of unknown length).
</para>

<para lang="en">
To do this, you need to call the <methodname>pulse()</methodname> method at regular
intervals. You can also choose the step size, with the
<methodname>set_pulse_step()</methodname> method.
</para>

<para lang="en">
The progress bar can also display a configurable text
string within its trough, using the <methodname>set_text()</methodname> method.
</para>
</sect2>

<sect2 id="progressbar-example"><title>Exemplo</title>

<figure id="figure-progressbar">
  <title lang="en">ProgressBar</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/progressbar.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/progressbar?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_checkbutton_text();
  void on_checkbutton_activity();
  void on_checkbutton_inverted();
  virtual bool on_timeout();
  void on_button_close();

  //Child widgets:
  Gtk::Box m_VBox;
  Gtk::Grid m_Grid;
  Gtk::ProgressBar m_ProgressBar;
  Gtk::Separator m_Separator;
  Gtk::CheckButton m_CheckButton_Text, m_CheckButton_Activity, m_CheckButton_Inverted;
  Gtk::Button m_Button_Close;

  int m_connection_id_timeout;
  bool m_bActivityMode;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL, 5),
  m_CheckButton_Text("Show text"),
  m_CheckButton_Activity("Activity mode"),
  m_CheckButton_Inverted("Right to Left"),
  m_Button_Close("Close"),
  m_bActivityMode(false)
{
  set_resizable();
  set_title("Gtk::ProgressBar");

  m_VBox.set_border_width(10);
  add(m_VBox);

  m_VBox.pack_start(m_ProgressBar, Gtk::PACK_SHRINK, 5);
  m_ProgressBar.set_halign(Gtk::ALIGN_CENTER);
  m_ProgressBar.set_valign(Gtk::ALIGN_CENTER);
  m_ProgressBar.set_text("some text");
  m_ProgressBar.set_show_text(false);

  //Add a timer callback to update the value of the progress bar:
  m_connection_id_timeout = Glib::signal_timeout().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_timeout), 50 );

  m_VBox.pack_start(m_Separator, Gtk::PACK_SHRINK);
  m_VBox.pack_start(m_Grid);
  m_Grid.set_row_homogeneous(true);

  //Add a check button to select displaying of the trough text:
  m_Grid.attach(m_CheckButton_Text, 0, 0, 1, 1);
  m_CheckButton_Text.property_margin() = 5;
  m_CheckButton_Text.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_checkbutton_text) );

  //Add a check button to toggle activity mode:
  m_Grid.attach(m_CheckButton_Activity, 0, 1, 1, 1);
  m_CheckButton_Activity.property_margin() = 5;
  m_CheckButton_Activity.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_checkbutton_activity) );

  //Add a check button to select growth from left to right or from right to left:
  m_Grid.attach(m_CheckButton_Inverted, 0, 2, 1, 1);
  m_CheckButton_Inverted.property_margin() = 5;
  m_CheckButton_Inverted.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_checkbutton_inverted) );

  //Add a button to exit the program.
  m_VBox.pack_start(m_Button_Close, Gtk::PACK_SHRINK);
  m_Button_Close.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_close) );
  m_Button_Close.set_can_default();
  m_Button_Close.grab_default();

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_checkbutton_text()
{
  const bool show_text = m_CheckButton_Text.get_active();
  m_ProgressBar.set_show_text(show_text);
}

void ExampleWindow::on_checkbutton_activity()
{
  m_bActivityMode = m_CheckButton_Activity.get_active();

  if(m_bActivityMode)
    m_ProgressBar.pulse();
  else
    m_ProgressBar.set_fraction(0.0);
}

void ExampleWindow::on_checkbutton_inverted()
{
  const bool inverted = m_CheckButton_Inverted.get_active();
  m_ProgressBar.set_inverted(inverted);
}

void ExampleWindow::on_button_close()
{
  hide();
}

/* Update the value of the progress bar so that we get
 * some movement */
bool ExampleWindow::on_timeout()
{
  if(m_bActivityMode)
    m_ProgressBar.pulse();
  else
  {
    double new_val = m_ProgressBar.get_fraction() + 0.01;

    if(new_val &gt; 1.0)
      new_val = 0.0;

    //Set the new value:
    m_ProgressBar.set_fraction(new_val);
  }

  //As this is a timeout function, return true so that it
  //continues to get called
  return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

</sect1>


<sect1 id="sec-infobar">
<title lang="en">InfoBar</title>

<para lang="en">
An <classname>InfoBar</classname> may show small items of information or ask brief questions. Unlike a <classname>Dialog</classname>, it appears at the top of the current window instead of opening a new window. Its API is very similar to the <link linkend="chapter-dialogs">Gtk::Dialog</link> API.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1InfoBar.html">Reference</ulink></para>

<sect2 id="infobar-example"><title>Exemplo</title>

<figure id="figure-infobar">
  <title lang="en">InfoBar</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/infobar.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/infobar?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_infobar_response(int response);
  void on_button_quit();
  void on_button_clear();
  void on_textbuffer_changed();

  //Child widgets:
  Gtk::Box m_VBox;

  Gtk::ScrolledWindow m_ScrolledWindow;
  Gtk::TextView m_TextView;
  
  Glib::RefPtr&lt;Gtk::TextBuffer&gt; m_refTextBuffer;

  Gtk::InfoBar m_InfoBar;
  Gtk::Label m_Message_Label;

  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Quit, m_Button_Clear;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL, 6),
  m_Button_Quit("_Quit", true),
  m_Button_Clear("_Clear", true)
{
  set_title("Gtk::InfoBar example");
  set_border_width(6);
  set_default_size(400, 200);

  add(m_VBox);

  // Add the message label to the InfoBar:
  Gtk::Container* infoBarContainer =
    dynamic_cast&lt;Gtk::Container*&gt;(m_InfoBar.get_content_area());
  if (infoBarContainer)
    infoBarContainer-&gt;add(m_Message_Label);

  // Add an ok button to the InfoBar:
  m_InfoBar.add_button("_OK", 0);

  // Add the InfoBar to the vbox:
  m_VBox.pack_start(m_InfoBar, Gtk::PACK_SHRINK);

  // Create the buffer and set it for the TextView:
  m_refTextBuffer = Gtk::TextBuffer::create();
  m_TextView.set_buffer(m_refTextBuffer);

  // Add the TreeView, inside a ScrolledWindow:
  m_ScrolledWindow.add(m_TextView);

  // Show the scrollbars only when they are necessary:
  m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

  m_VBox.pack_start(m_ScrolledWindow);

  // Add button box:
  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);

  m_ButtonBox.pack_start(m_Button_Clear, Gtk::PACK_SHRINK);
  m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
  m_ButtonBox.set_spacing(6);
  m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);

  // Connect signals:
  m_InfoBar.signal_response().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_infobar_response) );
  m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_quit) );
  m_Button_Clear.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_clear) );
  m_refTextBuffer-&gt;signal_changed().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_textbuffer_changed) );

  show_all();

  // Keep the InfoBar hidden until a message needs to be shown:
  m_InfoBar.hide();

  // Make the clear button insensitive until text is typed in the buffer.  When
  // the button is sensitive and it is pressed, the InfoBar is displayed with a
  // message.
  m_Button_Clear.set_sensitive(false);
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_infobar_response(int)
{
  // Clear the message and hide the info bar:
  m_Message_Label.set_text("");
  m_InfoBar.hide();
}

void ExampleWindow::on_button_quit()
{
  hide();
}

void ExampleWindow::on_button_clear()
{
  m_refTextBuffer-&gt;set_text("");
  m_Message_Label.set_text("Cleared the text.");
  m_InfoBar.set_message_type(Gtk::MESSAGE_INFO);
  m_InfoBar.show();
}

void ExampleWindow::on_textbuffer_changed()
{
  m_Button_Clear.set_sensitive(m_refTextBuffer-&gt;size() &gt; 0);
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;
  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

</sect1>

<sect1 id="sec-tooltips">
<title>Dicas</title>

<para lang="en">
Tooltips are the little information windows that pop up when you leave your
pointer over a widget for a few seconds. Use
<methodname>set_tooltip_text()</methodname> to set a text string as a tooltip
on any <classname>Widget</classname>. <classname>Gtk::ToolItem</classname>s are
not <classname>Widget</classname>s, but have the same method for convenience.
<classname>Gtk::Tooltip</classname> is used for more advanced tooltip usage,
such as showing an image as well as text.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Widget.html">Widget Reference</ulink></para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Tooltip.html">Tooltip Reference</ulink></para>

<sect2 id="tooltip-example"><title>Exemplo</title>

<figure id="figure-tooltip">
  <title>Dica de Ferramenta</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/tooltip.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/tooltips?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:

  ExampleWindow();
  virtual ~ExampleWindow();

protected:

  //Methods:
  void prepare_textview();
  void connect_signals();

  //Signal handlers:
  void on_markup_checkbutton_click();
  bool on_textview_query_tooltip(int x, int y, bool keyboard_tooltip, const Glib::RefPtr&lt;Gtk::Tooltip&gt;&amp; tooltip);
  bool on_button_query_tooltip(int x, int y, bool keyboard_tooltip, const Glib::RefPtr&lt;Gtk::Tooltip&gt;&amp; tooltip);

  //Child widgets:
  Gtk::Box m_vbox;

  Gtk::CheckButton m_checkbutton;
  Gtk::Label m_label;

  Gtk::ScrolledWindow m_scrolled_window;
  Gtk::TextView m_text_view;
  Glib::RefPtr&lt;Gtk::TextBuffer&gt; m_ref_text_buffer;
  Glib::RefPtr&lt;Gtk::TextTag&gt; m_ref_bold_tag;

  Gtk::Button m_button;
  Gtk::Window m_button_tooltip_window;

};

#endif // GTKMM_EXAMPLEWINDOW_H

</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"

#include &lt;vector&gt;

const Glib::ustring app_title = "gtkmm tooltips example";
const Glib::ustring non_markedup_tip = "A tooltip without markup.";
const Glib::ustring markedup_tip = "&lt;i&gt;Markup&lt;/i&gt; in a tooltip.";

ExampleWindow::ExampleWindow()
  :
  m_vbox(Gtk::ORIENTATION_VERTICAL, 3),
  m_checkbutton("Click to alternate markup in tooltip"),
  m_label("A label"),
  m_button("Custom widget in tooltip window"),
  m_button_tooltip_window(Gtk::WINDOW_POPUP)
{
  //Set up window and the top-level container:
  set_title(app_title);
  set_border_width(10);

  add(m_vbox);

  //Check button with markup in tooltip:
  m_checkbutton.set_tooltip_text(non_markedup_tip);
  m_vbox.pack_start(m_checkbutton, Gtk::PACK_SHRINK);

  //Label:
  m_label.set_tooltip_text("Another tooltip");
  m_vbox.pack_start(m_label, Gtk::PACK_SHRINK);

  //Textview:
  prepare_textview();

  //Button:
  // set_tooltip_window(), like set_tooltip_text(),
  // will call set_has_tooltip() for us.
  m_button.set_tooltip_window(m_button_tooltip_window);
  m_vbox.pack_start(m_button, Gtk::PACK_SHRINK);

  //Button's custom tooltip window:
  m_button_tooltip_window.set_default_size(250, 30);
  Gtk::Label* label =
    Gtk::manage(new Gtk::Label("A label in a custom tooltip window"));
  label-&gt;show();
  m_button_tooltip_window.add(*label);

  connect_signals();

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::prepare_textview()
{
  Gtk::TextIter iter;
  std::vector&lt; Glib::RefPtr&lt;Gtk::TextTag&gt; &gt; tags;

  //Set up a scrolled window:
  m_scrolled_window.add(m_text_view);
  m_scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
  m_vbox.pack_start(m_scrolled_window);

  //Create a text buffer with some text:
  m_ref_text_buffer = Gtk::TextBuffer::create();

  iter = m_ref_text_buffer-&gt;end();
  m_ref_text_buffer-&gt;insert(iter, "Hover over the text ");

  //Insert some text with a tag.
  //In the tooltip signal handler below, we will show a tooltip
  //when mouse pointer is above this tagged text.
  m_ref_bold_tag = m_ref_text_buffer-&gt;create_tag("bold");
  m_ref_bold_tag-&gt;set_property("weight", Pango::WEIGHT_BOLD);

  tags.push_back(m_ref_bold_tag);

  iter = m_ref_text_buffer-&gt;end();
  m_ref_text_buffer-&gt;insert_with_tags(iter, "in bold", tags);

  iter = m_ref_text_buffer-&gt;end();
  m_ref_text_buffer-&gt;insert(iter, " to see its tooltip");

  m_text_view.set_buffer(m_ref_text_buffer);

  m_text_view.set_size_request(320, 50);

  //When only connecting to the query-tooltip signal, and not using any
  //of set_tooltip_text(), set_tooltip_markup() or set_tooltip_window(),
  //we need to explicitly tell GTK+ that the widget has a tooltip which
  //we'll show.
  m_text_view.set_has_tooltip();
}

void ExampleWindow::connect_signals()
{
  m_checkbutton.signal_clicked().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::on_markup_checkbutton_click));

  m_text_view.signal_query_tooltip().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::on_textview_query_tooltip));

  m_button.signal_query_tooltip().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::on_button_query_tooltip));
}

void ExampleWindow::on_markup_checkbutton_click()
{
  if (m_checkbutton.get_active() == true)
  {
    m_checkbutton.set_tooltip_markup(markedup_tip);
  }
  else
  {
    m_checkbutton.set_tooltip_markup(non_markedup_tip);
  }
}

bool ExampleWindow::on_textview_query_tooltip(int x, int y, bool keyboard_tooltip, const Glib::RefPtr&lt;Gtk::Tooltip&gt;&amp; tooltip)
{
  Gtk::TextIter iter;

  if (keyboard_tooltip)
  {
    int offset = m_ref_text_buffer-&gt;property_cursor_position().get_value();
    iter = m_ref_text_buffer-&gt;get_iter_at_offset(offset);
  }
  else
  {
    int mouse_x, mouse_y, trailing;
    m_text_view.window_to_buffer_coords(Gtk::TEXT_WINDOW_TEXT,
                                        x, y, mouse_x, mouse_y);
    m_text_view.get_iter_at_position(iter, trailing, mouse_x, mouse_y);
  }

  //Show a tooltip if the cursor or mouse pointer is over the text
  //with the specific tag:
  if (iter.has_tag(m_ref_bold_tag))
  {
    tooltip-&gt;set_markup("&lt;b&gt;Information&lt;/b&gt; attached to a text tag");
    tooltip-&gt;set_icon_from_icon_name("dialog-information", Gtk::ICON_SIZE_MENU);
  }
  else
  {
    return false;
  }

  return true;
}

bool ExampleWindow::on_button_query_tooltip(int, int, bool, const Glib::RefPtr&lt;Gtk::Tooltip&gt;&amp;)
{
  //We already have a custom window ready, just return true to show it:
  return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

</sect1>

</chapter>

<chapter id="chapter-container-widgets">
<title>Widgets de empacotamento</title>

<para lang="en">
All container widgets derive from <classname>Gtk::Container</classname>, not
always directly. Some container widgets, such as
<classname>Gtk::Grid</classname> can hold many child widgets, so these
typically have more complex interfaces. Others, such as
<classname>Gtk::Frame</classname> contain only one child widget.
</para>

<sect1 id="sec-single-item-containers">
<title>Empacotamento de item único</title>

<para lang="en">
The single-item container widgets derive from <classname>Gtk::Bin</classname>,
which provides the <methodname>add()</methodname> and <methodname>remove()</methodname>
methods for the child widget. Note that <classname>Gtk::Button</classname> and
<classname>Gtk::Window</classname> are technically single-item containers, but
we have discussed them already elsewhere.
</para>

<para lang="en">
We also discuss the <classname>Gtk::Paned</classname> widget, which allows you
to divide a window into two separate "panes". This widget actually contains
two child widgets, but the number is fixed so it seems appropriate.
</para>

<sect2 id="sec-frame">
<title>Moldura</title>

<para lang="en">
Frames can enclose one or a group of widgets within a box, optionally with a
title. For instance, you might place a group of
<classname>RadioButton</classname>s or <classname>CheckButton</classname>s in a
<classname>Frame</classname>.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Frame.html">Reference</ulink></para>

<sect3 id="frame-example"><title>Exemplo</title>

<figure id="figure-frame">
  <title>Moldura</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/frame.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/frame?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:

  //Child widgets:
  Gtk::Frame m_Frame;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
{
 /* Set some window properties */
  set_title("Frame Example");
  set_size_request(300, 300);

  /* Sets the border width of the window. */
  set_border_width(10);

  add(m_Frame);

  /* Set the frames label */
  m_Frame.set_label("Gtk::Frame Widget");

  /* Align the label at the right of the frame */
  //m_Frame.set_label_align(Gtk::ALIGN_END, Gtk::ALIGN_START);

  /* Set the style of the frame */
  m_Frame.set_shadow_type(Gtk::SHADOW_ETCHED_OUT);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect3>

</sect2>


<sect2 id="sec-paned">
<title>Painel</title>

<para lang="en">
Panes divide a widget into two halves, separated by a moveable divider.
The two halves (panes) can be oriented either horizontally (side by side) or
vertically (one above the other).
</para>

<para lang="en">
Unlike the other widgets in this section, pane widgets contain not one but two
child widgets, one in each pane. Therefore, you should use
<methodname>add1()</methodname> and <methodname>add2()</methodname> instead of the
<methodname>add()</methodname> method.
</para>

<para lang="en">
You can adjust the position of the divider using the
<methodname>set_position()</methodname> method, and you will probably need to do
so.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Paned.html">Reference</ulink></para>

<sect3 id="paned-example"><title>Exemplo</title>

<figure id="figure-paned">
  <title>Painel</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/paned.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/paned?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include "messageslist.h"
#include "messagetext.h"
#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:

  //Child widgets:
  Gtk::Paned m_VPaned;
  MessagesList m_MessagesList;
  MessageText m_MessageText;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>messagetext.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MESSAGETEXT_H
#define GTKMM_EXAMPLE_MESSAGETEXT_H

#include &lt;gtkmm.h&gt;

class MessageText : public Gtk::ScrolledWindow
{
public:
  MessageText();
  virtual ~MessageText();

  void insert_text();

protected:
  Gtk::TextView m_TextView;
};

#endif //GTKMM_EXAMPLE_MESSAGETEXT_H
</programlisting>
<para lang="en">File: <filename>messageslist.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MESSAGESLIST_H
#define GTKMM_EXAMPLE_MESSAGESLIST_H

#include &lt;gtkmm.h&gt;

class MessagesList: public Gtk::ScrolledWindow
{
public:
  MessagesList();
  virtual ~MessagesList();

  class ModelColumns : public Gtk::TreeModel::ColumnRecord
  {
  public:

    ModelColumns()
    { add(m_col_text); }

    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_text;
  };

  ModelColumns m_Columns;

protected:
  Glib::RefPtr&lt;Gtk::ListStore&gt; m_refListStore; //The Tree Model.
  Gtk::TreeView m_TreeView; //The Tree View.
};
#endif //GTKMM_EXAMPLE_MESSAGESLIST_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_VPaned(Gtk::ORIENTATION_VERTICAL)
{
  set_title ("Paned Windows");
  set_border_width(10);
  set_default_size(450, 400);

  /* Add a vpaned widget to our toplevel window */
  add(m_VPaned);

  /* Now add the contents of the two halves of the window */
  m_VPaned.add1(m_MessagesList);
  m_VPaned.add2(m_MessageText);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}
</programlisting>
<para lang="en">File: <filename>messageslist.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "messageslist.h"
#include &lt;sstream&gt;

MessagesList::MessagesList()
{
  /* Create a new scrolled window, with scrollbars only if needed */
  set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

  add(m_TreeView);

  /* create list store */
  m_refListStore = Gtk::ListStore::create(m_Columns);

  m_TreeView.set_model(m_refListStore);

  /* Add some messages to the window */
  for(int i = 0; i &lt; 10; ++i)
  {
    std::ostringstream text;
    text &lt;&lt; "message #" &lt;&lt; i;

    Gtk::TreeModel::Row row = *(m_refListStore-&gt;append());
    row[m_Columns.m_col_text] = text.str();
  }

  //Add the Model's column to the View's columns:
  m_TreeView.append_column("Messages", m_Columns.m_col_text);

  show_all_children();
}

MessagesList::~MessagesList()
{
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<para lang="en">File: <filename>messagetext.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "messagetext.h"

MessageText::MessageText()
{
  set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

  add(m_TextView);
  insert_text();

  show_all_children();
}

MessageText::~MessageText()
{
}

void MessageText::insert_text()
{
  Glib::RefPtr&lt;Gtk::TextBuffer&gt; refTextBuffer = m_TextView.get_buffer();

  Gtk::TextBuffer::iterator iter = refTextBuffer-&gt;get_iter_at_offset(0);
  refTextBuffer-&gt;insert(iter,
    "From: pathfinder@nasa.gov\n"
    "To: mom@nasa.gov\n"
    "Subject: Made it!\n"
    "\n"
    "We just got in this morning. The weather has been\n"
    "great - clear but cold, and there are lots of fun sights.\n"
    "Sojourner says hi. See you soon.\n"
    " -Path\n");
}
</programlisting>
<!-- end inserted example code -->

</sect3>

</sect2>

<sect2 id="sec-scrolledwindow">
<title lang="en">ScrolledWindow</title>

<para lang="en">
<classname>ScrolledWindow</classname> widgets create a scrollable
area. You can insert any type of widget into a
<classname>ScrolledWindow</classname> window, and it will be accessible
regardless of its size by using the scrollbars. Note that
<classname>ScrolledWindow</classname> is not a
<classname>Gtk::Window</classname> despite the slightly misleading name.
</para>

<para lang="en">
Scrolled windows have <emphasis>scrollbar policies</emphasis> which determine
whether the <classname>Scrollbar</classname>s will be displayed. The policies
can be set with the <methodname>set_policy()</methodname> method. The policy may be
one of <literal>Gtk::POLICY_AUTOMATIC</literal> or
<literal>Gtk::POLICY_ALWAYS</literal>.
<literal>Gtk::POLICY_AUTOMATIC</literal> will cause the scrolled window
to display the scrollbar only if the contained widget is larger than the
visible area. <literal>Gtk::POLICY_ALWAYS</literal> will cause the
scrollbar to be displayed always.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ScrolledWindow.html">Reference</ulink></para>

<sect3 id="scrolledwindow-example"><title>Exemplo</title>

<para lang="en">
Here is a simple example that packs 100 toggle buttons into a ScrolledWindow. Try resizing the window to see the scrollbars react.
</para>

<figure id="figure-scrolledwindow">
  <title lang="en">ScrolledWindow</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/scrolledwindow.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/scrolledwindow?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Dialog
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_dialog_response(int response_id);

  //Child widgets:
  Gtk::ScrolledWindow m_ScrolledWindow;
  Gtk::Grid m_Grid;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
{
  set_title("Gtk::ScrolledWindow example");
  set_border_width(0);
  set_size_request(300, 300);

  m_ScrolledWindow.set_border_width(10);

  /* the policy is one of Gtk::POLICY AUTOMATIC, or Gtk::POLICY_ALWAYS.
   * Gtk::POLICY_AUTOMATIC will automatically decide whether you need
   * scrollbars, whereas Gtk::POLICY_ALWAYS will always leave the scrollbars
   * there.  The first one is the horizontal scrollbar, the second,
   * the vertical. */
  m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS);

  get_content_area()-&gt;pack_start(m_ScrolledWindow);

  /* set the spacing to 10 on x and 10 on y */
  m_Grid.set_row_spacing(10);
  m_Grid.set_column_spacing(10);

  /* pack the grid into the scrolled window */
  m_ScrolledWindow.add(m_Grid);

  /* this simply creates a grid of toggle buttons
   * to demonstrate the scrolled window. */
  for(int i = 0; i &lt; 10; i++)
  {
     for(int j = 0; j &lt; 10; j++)
     {
        char buffer[32];
        sprintf(buffer, "button (%d,%d)\n", i, j);
        Gtk::Button* pButton = Gtk::manage(new Gtk::ToggleButton(buffer));
        m_Grid.attach(*pButton, i, j, 1, 1);
     }
  }

  /* Add a "close" button to the bottom of the dialog */
  add_button("_Close", Gtk::RESPONSE_CLOSE);
  signal_response().connect(sigc::mem_fun(*this, &amp;ExampleWindow::on_dialog_response));

  /* This makes it so the button is the default.
   * Simply hitting the "Enter" key will cause this button to activate. */
  set_default_response(Gtk::RESPONSE_CLOSE);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_dialog_response(int response_id)
{
  switch (response_id)
  {
  case Gtk::RESPONSE_CLOSE:
  case Gtk::RESPONSE_DELETE_EVENT:
    hide();
    break;
  default:
    std::cout &lt;&lt; "Unexpected response_id=" &lt;&lt; response_id &lt;&lt; std::endl;
    break;
  }
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect3>

</sect2>

<sect2 id="sec-aspectframe">
<title lang="en">AspectFrame</title>

<para lang="en">
The <classname>AspectFrame</classname> widget looks like a
<classname>Frame</classname> widget, but it also enforces the <emphasis>aspect
    ratio</emphasis> (the ratio of the width to the height) of the child
widget, adding extra space if necessary. For instance, this would allow you to
display a photograph without allowing the user to distort it horizontally or
vertically while resizing.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1AspectFrame.html">Reference</ulink></para>

<sect3 id="aspectframe-example">
<title>Exemplo</title>
<para lang="en">
The following program uses a <classname>Gtk::AspectFrame</classname> to present a
drawing area whose aspect ratio will always be 2:1, no matter how the user
resizes the top-level window.
</para>

<figure id="figure-aspectframe">
  <title lang="en">AspectFrame</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/aspectframe.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/aspectframe?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:

  //Child widgets:
  Gtk::AspectFrame m_AspectFrame;
  Gtk::DrawingArea m_DrawingArea;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_AspectFrame("2x1", /* label */
    Gtk::ALIGN_CENTER, /* center x */
    Gtk::ALIGN_CENTER, /* center y */
    2.0, /* xsize/ysize = 2 */
    false /* ignore child's aspect */)
{
  set_title("Aspect Frame");
  set_border_width(10);

  // Add a child widget to the aspect frame */
  // Ask for a 200x200 window, but the AspectFrame will give us a 200x100
  // window since we are forcing a 2x1 aspect ratio */
  m_DrawingArea.set_size_request(200, 200);
  m_AspectFrame.add(m_DrawingArea);

  // Add the aspect frame to our toplevel window:
  add(m_AspectFrame);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect3>

</sect2>


<sect2 id="sec-alignment">
<title>Alinhamento</title>

<para lang="en">
The <classname>Alignment</classname> widget allows you to place a widget at a
position and size relative to the size of the <classname>Alignment</classname>
widget itself. For instance, it might be used to center a widget.
</para>

<para lang="en">
The <classname>Alignment</classname> widget is deprecated from <application>gtkmm</application> version 3.14
and should not be used in newly-written code. Use <classname>Gtk::Widget</classname>'s
alignment and margin methods instead.
</para>

<sect3 id="alignment-example">
<title>Exemplo</title>
<para lang="en">
This example right-aligns a button in a window by using
<methodname>Gtk::Widget::set_halign()</methodname>.
</para>

<figure id="figure-alignment">
  <title>Alinhamento</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/alignment.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/alignment?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_clicked();

  //Child widgets:
  Gtk::Button m_Button;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_Button("_Close", /* mnemonic= */ true)
{
  set_title("Alignment");
  set_border_width(10);
  set_default_size(200, 50);

  m_Button.set_halign(Gtk::ALIGN_END);
  m_Button.set_valign(Gtk::ALIGN_CENTER);
  add(m_Button);

  m_Button.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_clicked) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_clicked()
{
  hide();
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

<para lang="en">
See the <link linkend="sec-progressbar">ProgressBar</link> section for another
example that uses <methodname>set_halign()</methodname>.
</para>

</sect3>

</sect2>

</sect1>

<sect1 id="sec-multi-item-containers">
<title>Widgets de múltiplos itens</title>

<para lang="en">
Multiple-item widgets inherit from <classname>Gtk::Container</classname>; just
as with <classname>Gtk::Bin</classname>, you use the <methodname>add()</methodname>
and <methodname>remove()</methodname> methods to add and remove contained widgets.
Unlike <methodname>Gtk::Bin::remove()</methodname>, however, the
<methodname>remove()</methodname> method for <classname>Gtk::Container</classname>
takes an argument, specifiying which widget to remove.
</para>

<sect2 id="container-packing">
<title lang="en">Packing</title>
<para lang="en">
You've probably noticed that <application>gtkmm</application> windows seem "elastic" - they can usually be stretched in many  different ways. This is due to the <emphasis>widget packing</emphasis>
system.
</para>

<para lang="en">
Many GUI toolkits require you to precisely place widgets in a window, using absolute positioning, often using a visual editor. This leads to several problems:
</para>

<itemizedlist>

<listitem>
<para lang="en">The widgets don't rearrange themselves when the window is resized. Some widgets are hidden when the window is made smaller, and lots of useless space appears when the window is made larger.</para>
</listitem>

<listitem>
<para lang="en">It's impossible to predict the amount of space necessary for text after it has been translated to other languages, or displayed in a different font. On Unix it is also impossible to anticipate the effects of every theme and window manager.</para>
</listitem>

<listitem>
<para lang="en">
Changing the layout of a window "on the fly", to make some extra widgets appear, for instance, is complex. It  requires tedious recalculation of every widget's position.</para>
</listitem>

</itemizedlist>

<para lang="en">
<application>gtkmm</application> uses the packing system to solve these problems. Rather than specifying the position and size of each widget in the window,
you can arrange your widgets in rows, columns,
and/or grids. <application>gtkmm</application> can size your window automatically, based on the
sizes of the widgets it contains. And the sizes of the widgets are, in turn, determined by the amount of text they contain, or the minimum and maximum sizes that you specify, and/or how you have requested that the available space should be shared between sets of widgets.
You can perfect your layout by
specifying padding distance and centering values for each of your widgets. <application>gtkmm</application> then uses
all this information to resize and reposition everything sensibly and smoothly when the user manipulates the window. </para>

<para lang="en">
<application>gtkmm</application> arranges widgets hierarchically, using <emphasis>containers</emphasis>.
A Container widget contains other widgets. Most <application>gtkmm</application> widgets are
containers. Windows, Notebook tabs, and Buttons are all container widgets.
There are two flavours of containers: single-child containers, which are all
descendants of <classname>Gtk::Bin</classname>, and multiple-child containers,
which are descendants of <classname>Gtk::Container</classname>. Most widgets
in <application>gtkmm</application> are descendants of <classname>Gtk::Bin</classname>, including
<classname>Gtk::Window</classname>.
</para>

<para lang="en">
Yes, that's correct: a Window can contain at most one widget. How, then, can
we use a window for anything useful?  By placing a multiple-child container in
the window. The most useful container widgets are
<classname>Gtk::Grid</classname> and <classname>Gtk::Box</classname>.
</para>


<itemizedlist>

<listitem>
<para lang="en">
<classname>Gtk::Grid</classname> arranges its child widgets in rows and
columns. Use <methodname>attach()</methodname>,
<methodname>attach_next_to()</methodname> and <methodname>add()</methodname> to
insert child widgets.
</para>
</listitem>

<listitem>
<para lang="en">
<classname>Gtk::Box</classname> arranges its child widgets vertically or horizontally. Use
<methodname>pack_start()</methodname> and <methodname>pack_end()</methodname> to insert
child widgets.
</para>
</listitem>

</itemizedlist>

<para lang="en">
 There are several other containers, which we will also discuss.
</para>

<para lang="en">
If you've never used a packing toolkit before, it can take some
getting used to. You'll probably find, however, that you don't
need to rely on visual form editors quite as much as you might with
other toolkits.
</para>

</sect2>

<sect2 id="sec-helloworld2">
<title>Um olá mundo melhorado</title>

<para lang="en">
Let's take a look at a slightly improved <literal>helloworld</literal>, showing what we've learnt.
</para>

<figure id="figure-helloworld2">
  <title>Olá, mundo 2</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/helloworld2.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/helloworld2?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>helloworld.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_HELLOWORLD_H
#define GTKMM_EXAMPLE_HELLOWORLD_H

#include &lt;gtkmm/box.h&gt;
#include &lt;gtkmm/button.h&gt;
#include &lt;gtkmm/window.h&gt;

class HelloWorld : public Gtk::Window
{
public:
  HelloWorld();
  virtual ~HelloWorld();

protected:

  // Signal handlers:
  // Our new improved on_button_clicked(). (see below)
  void on_button_clicked(Glib::ustring data);

  // Child widgets:
  Gtk::Box m_box1;
  Gtk::Button m_button1, m_button2;
};

#endif // GTKMM_EXAMPLE_HELLOWORLD_H
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "helloworld.h"
#include &lt;gtkmm/application.h&gt;

int main (int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  HelloWorld helloworld;

  //Shows the window and returns when it is closed.
  return app-&gt;run(helloworld);
}
</programlisting>
<para lang="en">File: <filename>helloworld.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "helloworld.h"
#include &lt;iostream&gt;

HelloWorld::HelloWorld()
: m_button1("Button 1"),
  m_button2("Button 2")
{
  // This just sets the title of our new window.
  set_title("Hello Buttons!");

  // sets the border width of the window.
  set_border_width(10);

  // put the box into the main window.
  add(m_box1);

  // Now when the button is clicked, we call the "on_button_clicked" function
  // with a pointer to "button 1" as it's argument
  m_button1.signal_clicked().connect(sigc::bind&lt;Glib::ustring&gt;(
              sigc::mem_fun(*this, &amp;HelloWorld::on_button_clicked), "button 1"));

  // instead of gtk_container_add, we pack this button into the invisible
  // box, which has been packed into the window.
  // note that the pack_start default arguments are Gtk::EXPAND | Gtk::FILL, 0
  m_box1.pack_start(m_button1);

  // always remember this step, this tells GTK that our preparation
  // for this button is complete, and it can be displayed now.
  m_button1.show();

  // call the same signal handler with a different argument,
  // passing a pointer to "button 2" instead.
  m_button2.signal_clicked().connect(sigc::bind&lt;-1, Glib::ustring&gt;(
              sigc::mem_fun(*this, &amp;HelloWorld::on_button_clicked), "button 2"));

  m_box1.pack_start(m_button2);

  // Show the widgets.
  // They will not really be shown until this Window is shown.
  m_button2.show();
  m_box1.show();
}

HelloWorld::~HelloWorld()
{
}

// Our new improved signal handler.  The data passed to this method is
// printed to stdout.
void HelloWorld::on_button_clicked(Glib::ustring data)
{
  std::cout &lt;&lt; "Hello World - " &lt;&lt; data &lt;&lt; " was pressed" &lt;&lt; std::endl;
}

</programlisting>
<!-- end inserted example code -->

<para lang="en">
After building and running this program, try resizing the window to see the
behaviour. Also, try playing with the options to
<methodname>pack_start()</methodname> while reading the <link linkend="sec-boxes">Boxes</link> section.
</para>

</sect2>

<sect2 id="sec-boxes">
<title>Caixas</title>

<para lang="en">
Most packing uses boxes as in the above example. These
are invisible containers into which we can pack our widgets. When
packing widgets into a horizontal box, the objects are inserted
horizontally from left to right or right to left depending on whether
<methodname>pack_start()</methodname> or <methodname>pack_end()</methodname> is used.
In a vertical box, widgets are packed from top to bottom or vice
versa. You may use any combination of boxes inside or beside other
boxes to create the desired effect.
</para>

<sect3 id="boxes-adding-widgets"><title>Adicionando widgets</title>
<sect4 id="per-child-packing-options"><title>Opções de empacotamento por filhos</title>
<para lang="en">
The <methodname>pack_start()</methodname> and
<methodname>pack_end()</methodname> methods place widgets inside these
containers. The <methodname>pack_start()</methodname> method will start at
the top and work its way down in a <classname>Box</classname> with vertical
orientation, or pack left to right in a <classname>Box</classname> with horizontal
orientation. <methodname>pack_end()</methodname> will do the opposite, packing from
bottom to top or from right to left. Using these methods allows us to right justify or
left justify our widgets. We will use <methodname>pack_start()</methodname>
in most of our examples.
</para>

<para lang="en">
There are several options governing how  widgets are to be packed, and this can
be confusing at first. If you have difficulties then it is sometimes a good
idea to play with the <application>glade</application> GUI designer to see what
is possible. You might even decide to use the
<application>Gtk::Builder</application> API to load your GUI at runtime.
</para>

<para lang="en">
There are basically five
different styles, as shown in this picture:
</para>

<figure id="figure-box-packing1">
  <title lang="en">Box Packing 1</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/box_packing1.png"/>
  </screenshot>
</figure>

<para lang="en">
Each line contains one horizontal <classname>Box</classname> with
several buttons. Each of the buttons on a line is packed into the
<classname>Box</classname> with the same arguments to the
<methodname>pack_start()</methodname> method.
</para>

<para lang="en">
This is the declaration of the <methodname>pack_start()</methodname> method:
</para>
<programlisting lang="en">void pack_start(Gtk::Widget&amp; child,
                Gtk::PackOptions options = Gtk::PACK_EXPAND_WIDGET,
                guint padding = 0);</programlisting>

<para lang="en">
The first argument is the widget you're packing. In our example these are all <classname>Button</classname>s.
</para>

<para lang="en">
The <parameter>options</parameter> argument can take one of these three options:
<itemizedlist>
<listitem><para lang="en"><literal>Gtk::PACK_SHRINK</literal>: Space is contracted to the child widget size. The widget will take up just-enough space and never expand.</para></listitem>
<listitem><para lang="en"><literal>Gtk::PACK_EXPAND_PADDING</literal>: Extra space is filled with padding. The widgets will be spaced out evenly, but their sizes won't change - there will be empty space between the widgets instead. </para></listitem>
<listitem><para lang="en"><literal>Gtk::PACK_EXPAND_WIDGET</literal>: Extra space is taken up by increasing the child widget size, without changing the amount of space between widgets.</para></listitem>
</itemizedlist>
</para>

<para lang="en">
The <parameter>padding</parameter> argument specifies the width of an extra
border area to leave around the packed widget.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Box.html">Reference</ulink></para>

</sect4>

<sect4 id="per-container-packing-options"><title>Opções de empacotamento por recipiente</title>
<para lang="en">
Here's the constructor for the <classname>Box</classname> widget,
and methods that set per-container packing options:
<programlisting lang="en">Gtk::Box(Gtk::Orientation orientation = Gtk::ORIENTATION_HORIZONTAL, int spacing = 0);
void set_spacing(int spacing);
void set_homogeneous(bool homogeneous = true);</programlisting>
Passing <literal>true</literal> to <methodname>set_homogeneous()</methodname> will
cause all of the contained widgets to be the same size.
<parameter>spacing</parameter> is a (minimum) number of pixels to leave between
each widget.
</para>

<para lang="en">
What's the difference between spacing (set when the box is created)
and padding (set when elements are packed)? Spacing is added between
objects, and padding is added on either side of a widget. The following
figure should make it clearer:
</para>

<figure id="figure-box-packing2">
  <title>Caixa de embalagem 2</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/box_packing2.png"/>
  </screenshot>
</figure>

</sect4>
</sect3>

<sect3 id="boxes-command-line-options">
<title>Gtk::Application e opções de linha de comando</title>
<para>O programa de exemplo a seguir exige uma opção de linha de comando. O código fonte mostra duas maneiras de lidar com linhas de comando em combinação com <classname>Gtk::Application</classname>.</para>

<itemizedlist>
<listitem><para lang="en">
Handle the options in <function>main()</function> and hide them from
<classname>Gtk::Application</classname> by setting <literal>argc = 1</literal>
in the call to <methodname>Gtk::Application::create()</methodname>.
</para></listitem>

<listitem><para lang="en">
Give all command-line options to <methodname>Gtk::Application::create()</methodname>
and add the flag <literal>Gio::APPLICATION_HANDLES_COMMAND_LINE</literal>.
Connect a signal handler to the <literal>command_line</literal> signal, and
handle the command-line options in the signal handler.</para>

<para lang="en">You must set the optional parameter <literal>after = false</literal> in
the call to <literal>signal_command_line().connect()</literal>, because your signal
handler must be called before the default signal handler. You must also call
<methodname>Gio::Application::activate()</methodname> in the signal handler,
unless you want your application to exit without showing its main window.
(<classname>Gio::Application</classname> is a base class of
<classname>Gtk::Application</classname>.)
</para></listitem>
</itemizedlist>
</sect3>

<sect3 id="box-packing-example">
<title>Exemplo</title>
<para>Aqui está o código fonte para o exemplo que produziu as imagens acima. Quando você executar esse exemplo, fornecer um número entre 1 e 3 como uma opção de linha de comando, para ver diferentes opções de empacotamento em uso.</para>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/box?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow(int which);
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_quit_clicked();

  //Child widgets:
  Gtk::Button m_button;
  Gtk::Box m_box1;
  Gtk::Box m_boxQuit;
  Gtk::Button m_buttonQuit;

  Gtk::Label m_Label1, m_Label2;

  Gtk::Separator m_separator1, m_separator2;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>packbox.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_PACKBOX_H
#define GTKMM_EXAMPLE_PACKBOX_H

#include &lt;gtkmm.h&gt;

class PackBox : public Gtk::Box
{
public:
  PackBox(bool homogeneous, int spacing, Gtk::PackOptions options, int padding = 0);
  virtual ~PackBox();

protected:
  Gtk::Button m_button1, m_button2, m_button3;
  Gtk::Button* m_pbutton4;
};

#endif //GTKMM_EXAMPLE_PACKBOX_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include "examplewindow.h"
#include "packbox.h"

ExampleWindow::ExampleWindow(int which)
: m_box1(Gtk::ORIENTATION_VERTICAL),
  m_buttonQuit("Quit")
{
  set_title("Gtk::Box example");

  PackBox *pPackBox1, *pPackBox2, *pPackBox3, *pPackBox4, *pPackBox5;

  switch(which)
  {
    case 1:
    {
      m_Label1.set_text("Gtk::Box(Gtk::ORIENTATION_HORIZONTAL); set_homogeneous(false);");

      // Align the label to the left side.
      m_Label1.set_halign(Gtk::ALIGN_START);
      m_Label1.set_valign(Gtk::ALIGN_START);

      // Pack the label into the vertical box (vbox box1).  Remember that
      // widgets added to a vbox will be packed one on top of the other in
      // order.
      m_box1.pack_start(m_Label1, Gtk::PACK_SHRINK);

      // Create a PackBox - homogeneous = false, spacing = 0,
      // options = Gtk::PACK_SHRINK, padding = 0
      pPackBox1 = Gtk::manage(new PackBox(false, 0, Gtk::PACK_SHRINK));
      m_box1.pack_start(*pPackBox1, Gtk::PACK_SHRINK);

      // Create a PackBox - homogeneous = false, spacing = 0,
      // options = Gtk::PACK_EXPAND_PADDING, padding = 0
      pPackBox2 = Gtk::manage(new PackBox(false, 0, Gtk::PACK_EXPAND_PADDING));
      m_box1.pack_start(*pPackBox2, Gtk::PACK_SHRINK);

      // Create a PackBox - homogeneous = false, spacing = 0,
      // options = Gtk::PACK_EXPAND_WIDGET, padding = 0
      pPackBox3 = Gtk::manage(new PackBox(false, 0, Gtk::PACK_EXPAND_WIDGET));
      m_box1.pack_start(*pPackBox3, Gtk::PACK_SHRINK);

      // pack the separator into the vbox.  Remember each of these
      // widgets are being packed into a vbox, so they'll be stacked
      // vertically.
      m_box1.pack_start(m_separator1, Gtk::PACK_SHRINK, 5);

      // create another new label, and show it.
      m_Label2.set_text("Gtk::Box(Gtk::ORIENTATION_HORIZONTAL); set_homogeneous(true);");
      m_Label2.set_halign(Gtk::ALIGN_START);
      m_Label2.set_valign(Gtk::ALIGN_START);
      m_box1.pack_start(m_Label2, Gtk::PACK_SHRINK);

      // Args are: homogeneous, spacing, options, padding
      pPackBox4 = Gtk::manage(new PackBox(true, 0, Gtk::PACK_EXPAND_PADDING));
      m_box1.pack_start(*pPackBox4, Gtk::PACK_SHRINK);

      // Args are: homogeneous, spacing, options, padding
      pPackBox5 = Gtk::manage(new PackBox(true, 0, Gtk::PACK_EXPAND_WIDGET));
      m_box1.pack_start(*pPackBox5, Gtk::PACK_SHRINK);

      m_box1.pack_start(m_separator2, Gtk::PACK_SHRINK, 5);

      break;
    }

    case 2:
    {

      m_Label1.set_text("Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 10); set_homogeneous(false);");
      m_Label1.set_halign(Gtk::ALIGN_START);
      m_Label1.set_valign(Gtk::ALIGN_START);
      m_box1.pack_start(m_Label1, Gtk::PACK_SHRINK);

      pPackBox1 = Gtk::manage(new PackBox(false, 10, Gtk::PACK_EXPAND_PADDING));
      m_box1.pack_start(*pPackBox1, Gtk::PACK_SHRINK);

      pPackBox2 = Gtk::manage(new PackBox(false, 10, Gtk::PACK_EXPAND_WIDGET));
      m_box1.pack_start(*pPackBox2, Gtk::PACK_SHRINK);

      m_box1.pack_start(m_separator1, Gtk::PACK_SHRINK, 5);

      m_Label2.set_text("Gtk::Box(Gtk::ORIENTATION_HORIZONTAL); set_homogeneous(false);");
      m_Label2.set_halign(Gtk::ALIGN_START);
      m_Label2.set_valign(Gtk::ALIGN_START);
      m_box1.pack_start(m_Label2, Gtk::PACK_SHRINK);

      pPackBox3 = Gtk::manage(new PackBox(false, 0, Gtk::PACK_SHRINK, 10));
      m_box1.pack_start(*pPackBox3, Gtk::PACK_SHRINK);

      pPackBox4 = Gtk::manage(new PackBox(false, 0, Gtk::PACK_EXPAND_WIDGET, 10));
      m_box1.pack_start(*pPackBox4, Gtk::PACK_SHRINK);

      m_box1.pack_start(m_separator2, Gtk::PACK_SHRINK, 5);

      break;
    }

    case 3:
    {
      // This demonstrates the ability to use Gtk::Box::pack_end() to
      // right justify widgets.  First, we create a new box as before.
      pPackBox1 = Gtk::manage(new PackBox(false, 0, Gtk::PACK_SHRINK));

      // create the label that will be put at the end.
      m_Label1.set_text("end");

      // pack it using pack_end(), so it is put on the right side
      // of the PackBox.
      pPackBox1-&gt;pack_end(m_Label1, Gtk::PACK_SHRINK);

      m_box1.pack_start(*pPackBox1, Gtk::PACK_SHRINK);

      // this explicitly sets the separator to 500 pixels wide by 5 pixels
      // high.  This is so the hbox we created will also be 500 pixels wide,
      // and the "end" label will be separated from the other labels in the
      // hbox.  Otherwise, all the widgets in the hbox would be packed as
      // close together as possible.
      m_separator1.set_size_request(500, 5);

      // pack the separator into the vbox.
      m_box1.pack_start(m_separator1, Gtk::PACK_SHRINK, 5);

      break;
    }

    default:
    {
      std::cerr &lt;&lt; "Unexpected command-line option." &lt;&lt; std::endl;
      break;
    }
  }

  // Connect the signal to hide the window:
  m_buttonQuit.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_quit_clicked) );

  // pack the button into the quitbox.
  // The last 2 arguments to Box::pack_start are: options, padding.
  m_boxQuit.pack_start(m_buttonQuit, Gtk::PACK_EXPAND_PADDING);
  m_box1.pack_start(m_boxQuit, Gtk::PACK_SHRINK);

  // pack the vbox (box1) which now contains all our widgets, into the
  // main window.
  add(m_box1);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_quit_clicked()
{
  hide();
}

</programlisting>
<para lang="en">File: <filename>packbox.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "packbox.h"

PackBox::PackBox(bool homogeneous, int spacing, Gtk::PackOptions options,
        int padding)
: Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, spacing),
  m_button1("box.pack_start("),
  m_button2("button,"),
  m_button3((options == Gtk::PACK_SHRINK) ? "Gtk::PACK_SHRINK" :
            ((options == Gtk::PACK_EXPAND_PADDING) ?
             "Gtk::PACK_EXPAND_PADDING" : "Gtk::PACK_EXPAND_WIDGET"))
{
  set_homogeneous(homogeneous);

  pack_start(m_button1, options, padding);
  pack_start(m_button2, options, padding);
  pack_start(m_button3, options, padding);

  m_pbutton4 = new Gtk::Button(Glib::ustring::format(padding) + ");");
  pack_start(*m_pbutton4, options, padding);
}

PackBox::~PackBox()
{
  delete m_pbutton4;
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;
#include &lt;iostream&gt;
#include &lt;cstdlib&gt;

#define GTK_APPLICATION_RECEIVES_COMMAND_LINE_ARGUMENTS 0

#if GTK_APPLICATION_RECEIVES_COMMAND_LINE_ARGUMENTS
namespace
{
int on_command_line(const Glib::RefPtr&lt;Gio::ApplicationCommandLine&gt;&amp; command_line,
                    Glib::RefPtr&lt;Gtk::Application&gt;&amp; app)
{
  int argc = 0;
  char** argv = command_line-&gt;get_arguments(argc);

  for (int i = 0; i &lt; argc; ++i)
    std::cout &lt;&lt; "argv[" &lt;&lt; i &lt;&lt; "] = " &lt;&lt; argv[i] &lt;&lt; std::endl;

  app-&gt;activate(); // Without activate() the window won't be shown.
  return EXIT_SUCCESS;
}
} // anonymous namespace
#endif


int main(int argc, char *argv[])
{
  if (argc != 2)
  {
    std::cerr &lt;&lt; "Usage: example &lt;num&gt;, where &lt;num&gt; is 1, 2, or 3." &lt;&lt; std::endl;
    return EXIT_FAILURE;
  }

#if GTK_APPLICATION_RECEIVES_COMMAND_LINE_ARGUMENTS
  // The command line arguments must be checked before Gtk::Application::run()
  // is called. The Gio::APPLICATION_HANDLES_COMMAND_LINE flag and the
  // on_command_line() signal handler are not necessary. This program is simpler
  // without them, and with argc = 1 in the call to Gtk::Application::create().
  // They are included to show a program with Gio::APPLICATION_HANDLES_COMMAND_LINE.
  // Gio::APPLICATION_NON_UNIQUE makes it possible to run several instances of
  // this application simultaneously.
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv,
    "org.gtkmm.example", Gio::APPLICATION_HANDLES_COMMAND_LINE | Gio::APPLICATION_NON_UNIQUE);

  // Note after = false.
  // Only one signal handler is invoked. This signal handler must run before
  // the default signal handler, or else it won't run at all.
  app-&gt;signal_command_line().connect(sigc::bind(sigc::ptr_fun(&amp;on_command_line), app), false);
#else
  // Gio::APPLICATION_NON_UNIQUE makes it possible to run several instances of
  // this application simultaneously.
  int argc1 = 1; // Don't give the command line arguments to Gtk::Application.
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc1, argv,
    "org.gtkmm.example", Gio::APPLICATION_NON_UNIQUE);
#endif

  ExampleWindow window(std::atoi(argv[1]));
  return app-&gt;run(window); //Shows the window and returns when it is closed.
}
</programlisting>
<!-- end inserted example code -->
</sect3>

</sect2>

<sect2 id="sec-buttonbox">
<title>Caixa de botões</title>

<para>Caixas de botões são uma forma conveniente de arranjar rapidamente um grupo de botões. Sua orientação pode ser horizontal ou vertical.</para>

<para lang="en">
<classname>ButtonBox</classname>es help to make applications appear consistent
because they use standard settings, such as inter-button spacing and packing.
</para>

<para>Os botões são adicionados a um <classname>ButtonBox</classname> com o método <methodname>add()</methodname>.</para>

<para>Caixa de botões suportam varios estilos de layout. O estilo pode ser recuperado e alterado usando <methodname>get_layout()</methodname> and <methodname>set_layout()</methodname>.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ButtonBox.html">Reference</ulink></para>

<sect3 id="buttonbox-example">
<title>Exemplo</title>

<figure id="figure-buttonbox">
  <title>Caixa de botões</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/buttonbox.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/buttonbox?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_clicked();

  //Child widgets:
  Gtk::Box m_VBox_Main, m_VBox;
  Gtk::Box m_HBox;
  Gtk::Frame m_Frame_Horizontal, m_Frame_Vertical;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplebuttonbox.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_BUTTONBOX_H
#define GTKMM_EXAMPLE_BUTTONBOX_H

#include &lt;gtkmm.h&gt;

class ExampleButtonBox : public Gtk::Frame
{
public:
  ExampleButtonBox(bool horizontal,
       const Glib::ustring&amp; title,
       gint spacing,
       Gtk::ButtonBoxStyle layout);

protected:
  Gtk::Button m_Button_OK, m_Button_Cancel, m_Button_Help;
};

#endif //GTKMM_EXAMPLE_BUTTONBOX_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include "examplebuttonbox.h"

ExampleWindow::ExampleWindow()
: m_VBox_Main(Gtk::ORIENTATION_VERTICAL),
  m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Frame_Horizontal("Horizontal Button Boxes"),
  m_Frame_Vertical("Vertical Button Boxes")
{
  set_title("Gtk::ButtonBox");
  add(m_VBox_Main);

  m_VBox_Main.pack_start(m_Frame_Horizontal, Gtk::PACK_EXPAND_WIDGET, 10);

  //The horizontal ButtonBoxes:
  m_VBox.set_border_width(10);
  m_Frame_Horizontal.add(m_VBox);

  m_VBox.pack_start(*Gtk::manage(
              new ExampleButtonBox(true, "Spread (spacing 40)", 40,
                  Gtk::BUTTONBOX_SPREAD)),
          Gtk::PACK_EXPAND_WIDGET);

  m_VBox.pack_start(*Gtk::manage(
              new ExampleButtonBox(true, "Edge (spacing 30)", 30,
                  Gtk::BUTTONBOX_EDGE)),
          Gtk::PACK_EXPAND_WIDGET, 5);

  m_VBox.pack_start(*Gtk::manage(
              new ExampleButtonBox(true, "Start (spacing 20)", 20,
                  Gtk::BUTTONBOX_START)),
          Gtk::PACK_EXPAND_WIDGET, 5);

  m_VBox.pack_start(*Gtk::manage(
              new ExampleButtonBox(true, "end (spacing 10)", 10,
                  Gtk::BUTTONBOX_END)),
          Gtk::PACK_EXPAND_WIDGET, 5);


  //The vertical ButtonBoxes:
  m_VBox_Main.pack_start(m_Frame_Vertical, Gtk::PACK_EXPAND_WIDGET, 10);

  m_HBox.set_border_width(10);
  m_Frame_Vertical.add(m_HBox);

  m_HBox.pack_start(*Gtk::manage(
              new ExampleButtonBox(false, "Spread (spacing 5)", 5,
                  Gtk::BUTTONBOX_SPREAD)),
          Gtk::PACK_EXPAND_WIDGET);

  m_HBox.pack_start(*Gtk::manage(
              new ExampleButtonBox(false, "Edge (spacing 30)", 30,
                  Gtk::BUTTONBOX_EDGE)),
          Gtk::PACK_EXPAND_WIDGET, 5);

  m_HBox.pack_start(*Gtk::manage(
              new ExampleButtonBox(false, "Start (spacing 20)", 20,
                  Gtk::BUTTONBOX_START)),
          Gtk::PACK_EXPAND_WIDGET, 5);

  m_HBox.pack_start(*Gtk::manage(new ExampleButtonBox(false, "End (spacing 10)",
                  10, Gtk::BUTTONBOX_END)),
          Gtk::PACK_EXPAND_WIDGET, 5);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_clicked()
{
  hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<para lang="en">File: <filename>examplebuttonbox.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplebuttonbox.h"

ExampleButtonBox::ExampleButtonBox(bool horizontal,
       const Glib::ustring&amp; title,
       gint spacing,
       Gtk::ButtonBoxStyle layout)
: Gtk::Frame(title),
  m_Button_OK("OK"),
  m_Button_Cancel("Cancel"),
  m_Button_Help("Help")
{
  Gtk::ButtonBox* bbox = 0;

  if(horizontal)
    bbox = Gtk::manage( new Gtk::ButtonBox(Gtk::ORIENTATION_HORIZONTAL) );
  else
    bbox = Gtk::manage( new Gtk::ButtonBox(Gtk::ORIENTATION_VERTICAL) );

  bbox-&gt;set_border_width(5);

  add(*bbox);

  /* Set the appearance of the Button Box */
  bbox-&gt;set_layout(layout);
  bbox-&gt;set_spacing(spacing);

  bbox-&gt;add(m_Button_OK);
  bbox-&gt;add(m_Button_Cancel);
  bbox-&gt;add(m_Button_Help);
}

</programlisting>
<!-- end inserted example code -->

</sect3>

</sect2>

<sect2 id="sec-grid">
<title>Grade</title>

<para>Uma <classname>Grid</classname> dinamicamente estabelece widgets filhos em linhas e colunas. As dimensões da grade não precisa ser especificado no construtor.</para>

<para lang="en">
Child widgets can span multiple rows or columns, using
<methodname>attach()</methodname>, or added next to an existing widget inside
the grid with <methodname>attach_next_to()</methodname>. Individual rows and columns of the grid can be set to have uniform height or width with
<methodname>set_row_homogeneous()</methodname> and
<methodname>set_column_homogeneous()</methodname>.
</para>
<para lang="en">You can set the <emphasis>margin</emphasis> and <emphasis>expand</emphasis> properties of the
child <classname>Widget</classname>s to control their spacing and their behaviour when the Grid is resized.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Grid.html">Reference</ulink></para>

<sect3 id="grid-example"><title>Exemplo</title>
<para lang="en">
This example creates a window with three buttons in a grid.
The first two buttons are in the upper row, from left to right. A
third button is attached underneath the first button, in a new lower row,
spanning two columns.
</para>

<figure id="figure-grid">
  <title>Grade</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/grid.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/grid?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

private:
  // Signal handlers:
  void on_button_quit();
  void on_button_numbered(const Glib::ustring&amp; data);

  // Child widgets:
  Gtk::Grid m_grid;
  Gtk::Button m_button_1, m_button_2, m_button_quit;
};

#endif /* GTKMM_EXAMPLEWINDOW_H */
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_button_1("button 1"),
  m_button_2("button 2"),
  m_button_quit("Quit")
{
  set_title("Gtk::Grid");
  set_border_width(12);

  add(m_grid);

  m_grid.add(m_button_1);
  m_grid.add(m_button_2);
  m_grid.attach_next_to(m_button_quit, m_button_1, Gtk::POS_BOTTOM, 2, 1);

  m_button_1.signal_clicked().connect(
    sigc::bind&lt;Glib::ustring&gt;( sigc::mem_fun(*this,
      &amp;ExampleWindow::on_button_numbered), "button 1") );
  m_button_2.signal_clicked().connect(
    sigc::bind&lt;Glib::ustring&gt;( sigc::mem_fun(*this,
      &amp;ExampleWindow::on_button_numbered), "button 2") );

  m_button_quit.signal_clicked().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_button_quit) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_quit()
{
  hide();
}

void
ExampleWindow::on_button_numbered(const Glib::ustring&amp; data)
{
  std::cout &lt;&lt; data &lt;&lt; " was pressed" &lt;&lt; std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  // Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect3>

</sect2>

<sect2 id="sec-table">
<title>Tabela</title>

<para><classname>Gtk::Table</classname> nos permite colocar widgets em uma grade, semelhante à <classname>Gtk::Grid</classname>.</para>
<para><classname>Gtk::Table</classname> está obsoleto a partir da <application>gtkmm</application> versão 3.4 e não deve ser utilizado em códigos recentemente escritos. Ao invés use <classname>Gtk::Grid</classname>.</para>
</sect2>

<sect2 id="sec-notebook">
<title>Painel com abas</title>

<para lang="en">
A <classname>Notebook</classname> has a set of stacked
<literal>pages</literal>, each of which contains widgets. Labelled
<literal>tabs</literal> allow the user to select the pages.
<classname>Notebook</classname>s allow several sets of widgets to be placed in a
small space, by only showing one page at a time. For instance, they are often
used in preferences dialogs.
</para>

<para lang="en">
Use the <methodname>append_page()</methodname>, <methodname>prepend_page()</methodname>
and <methodname>insert_page()</methodname> methods to add tabbed pages to the
<literal>Notebook</literal>, supplying the child widget and the name for the
tab.
</para>

<para lang="en">
To discover the currently visible page, use the
<methodname>get_current_page()</methodname> method. This returns the page number,
and then calling <methodname>get_nth_page()</methodname> with that number will give
you a pointer to the actual child widget.
</para>

<para>Para alterar programaticamente a página selecionada, use o método <methodname>set_current_page()</methodname>.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Notebook.html">Reference</ulink></para>

<sect3 id="notebook-example"><title>Exemplo</title>

<figure id="figure-notebook">
  <title>Painel com abas</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/notebook.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/notebook/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_quit();
  void on_notebook_switch_page(Gtk::Widget* page, guint page_num);

  //Child widgets:
  Gtk::Box m_VBox;
  Gtk::Notebook m_Notebook;
  Gtk::Label m_Label1, m_Label2;

  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Quit;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Label1("Contents of tab 1"),
  m_Label2("Contents of tab 2"),
  m_Button_Quit("Quit")
{
  set_title("Gtk::Notebook example");
  set_border_width(10);
  set_default_size(400, 200);


  add(m_VBox);

  //Add the Notebook, with the button underneath:
  m_Notebook.set_border_width(10);
  m_VBox.pack_start(m_Notebook);
  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);

  m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
  m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_quit) );

  //Add the Notebook pages:
  m_Notebook.append_page(m_Label1, "First");
  m_Notebook.append_page(m_Label2, "Second");

  m_Notebook.signal_switch_page().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_notebook_switch_page) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_quit()
{
  hide();
}

void ExampleWindow::on_notebook_switch_page(Gtk::Widget* /* page */, guint page_num)
{
  std::cout &lt;&lt; "Switched to tab with index " &lt;&lt; page_num &lt;&lt; std::endl;

  //You can also use m_Notebook.get_current_page() to get this index.
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect3>

</sect2>

<sect2 id="sec-assistant">
<title>Assistente</title>

<para lang="en">
An <classname>Assistant</classname> splits a complex operation into steps. Each step is a page, containing a header, a child widget and an action area. The Assistant's action area has navigation buttons which update automatically depending on the type of the page, set with <methodname>set_page_type()</methodname>.
</para>

<para>Use os métodos <methodname>append_page()</methodname>, <methodname>prepend_page</methodname> e <methodname>insert_page()</methodname> para adicionar páginas ao <classname>Assistant</classname>, fornecendo o widget filho para cada página.</para>

<para lang="en">
To determine the currently-visible page, use the <methodname>get_current_page()</methodname> method, and pass the result to <methodname>get_nth_page()</methodname>, which returns a pointer to the actual widget. To programmatically change the current page, use the <methodname>set_current_page()</methodname> method.
</para>

<para>Para definir o título de uma página, utilize o método <methodname>set_page_title()</methodname>. As imagens de cabeçalho e do lado de uma página pode ser definido com os métodos <methodname>set_page_header_image()</methodname> e <methodname>set_page_side_image()</methodname>.</para>

<para>Para adicionar widgets para a área de ação, usar o método <methodname>add_action_widget()</methodname>. Eles serão acondicionados ao lado dos botões padrão. Usar o método <methodname>remove_action_widget()</methodname> para remover widgets.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Assistant.html">Reference</ulink></para>

<sect3 id="assistant-example"><title>Exemplo</title>

<figure id="figure-assistant">
  <title>Assistente</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/assistant.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/assistant/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include "exampleassistant.h"
#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

private:
  // Signal handlers:
  void on_button_clicked();
  void on_assistant_apply();

  // Child widgets:
  Gtk::Grid m_grid;
  Gtk::Button m_button;
  Gtk::Label m_label1, m_label2;
  Gtk::CheckButton m_check;
  Gtk::Entry m_entry;
  ExampleAssistant m_assistant;
};

#endif /* GTKMM_EXAMPLEWINDOW_H */
</programlisting>
<para lang="en">File: <filename>exampleassistant.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEASSISTANT_H
#define GTKMM_EXAMPLEASSISTANT_H

#include &lt;gtkmm.h&gt;

class ExampleAssistant : public Gtk::Assistant
{
public:
  ExampleAssistant();
  virtual ~ExampleAssistant();

  void get_result(bool&amp; check_state, Glib::ustring&amp; entry_text);

private:
  // Signal handlers:
  void on_assistant_apply();
  void on_assistant_cancel();
  void on_assistant_close();
  void on_assistant_prepare(Gtk::Widget* widget);
  void on_entry_changed();

  // Member functions:
  void print_status();

  // Child widgets:
  Gtk::Box m_box;
  Gtk::Label m_label1, m_label2;
  Gtk::CheckButton m_check;
  Gtk::Entry m_entry;
};

#endif /* GTKMM_EXAMPLEASSISTANT_H */
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include "exampleassistant.h"

ExampleWindow::ExampleWindow()
: m_button("Show the assistant"),
  m_label1("State of assistant checkbutton:", Gtk::ALIGN_START, Gtk::ALIGN_CENTER),
  m_label2("Contents of assistant entry:", Gtk::ALIGN_START, Gtk::ALIGN_CENTER)
{
  set_title("Gtk::Assistant example");
  set_border_width(12);

  m_grid.set_row_homogeneous(true);

  m_grid.attach(m_button, 0, 0, 2, 1);
  m_button.set_hexpand(true);
  m_button.set_valign(Gtk::ALIGN_CENTER);

  m_grid.attach(m_label1, 0, 1, 1, 1);

  m_grid.attach(m_label2, 0, 2, 1, 1);

  m_grid.attach(m_check, 1, 1, 1, 1);
  m_check.set_halign(Gtk::ALIGN_START);

  m_grid.attach(m_entry, 1, 2, 1, 1);
  m_entry.set_hexpand(true);

  add(m_grid);

  m_button.signal_clicked().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_button_clicked));
  m_assistant.signal_apply().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_assistant_apply));

  m_check.set_sensitive(false);
  m_entry.set_sensitive(false);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_assistant_apply()
{
  bool check_state;
  Glib::ustring entry_text;

  m_assistant.get_result(check_state, entry_text);
  m_check.set_active(check_state);
  m_entry.set_text(entry_text);
}

void ExampleWindow::on_button_clicked()
{
  m_assistant.show();
}
</programlisting>
<para lang="en">File: <filename>exampleassistant.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include "exampleassistant.h"

ExampleAssistant::ExampleAssistant()
: m_box(Gtk::ORIENTATION_HORIZONTAL, 12),
  m_label1("Type text to allow the assistant to continue:"),
  m_label2("Confirmation page"),
  m_check("Optional extra information")
{
  set_title("Gtk::Assistant example");
  set_border_width(12);
  set_default_size(400, 300);

  m_box.pack_start(m_label1);
  m_box.pack_start(m_entry);

  append_page(m_box);
  append_page(m_check);
  append_page(m_label2);

  set_page_title(*get_nth_page(0), "Page 1");
  set_page_title(*get_nth_page(1), "Page 2");
  set_page_title(*get_nth_page(2), "Confirmation");

  set_page_complete(m_check, true);
  set_page_complete(m_label2, true);

  set_page_type(m_box, Gtk::ASSISTANT_PAGE_INTRO);
  set_page_type(m_label2, Gtk::ASSISTANT_PAGE_CONFIRM);

  signal_apply().connect(sigc::mem_fun(*this,
    &amp;ExampleAssistant::on_assistant_apply));
  signal_cancel().connect(sigc::mem_fun(*this,
    &amp;ExampleAssistant::on_assistant_cancel));
  signal_close().connect(sigc::mem_fun(*this,
    &amp;ExampleAssistant::on_assistant_close));
  signal_prepare().connect(sigc::mem_fun(*this,
    &amp;ExampleAssistant::on_assistant_prepare));

  m_entry.signal_changed().connect(sigc::mem_fun(*this,
    &amp;ExampleAssistant::on_entry_changed));

  show_all_children();
}

ExampleAssistant::~ExampleAssistant()
{
}

void ExampleAssistant::get_result(bool&amp; check_state, Glib::ustring&amp; entry_text)
{
  check_state = m_check.get_active();
  entry_text = m_entry.get_text();
}

void ExampleAssistant::on_assistant_apply()
{
  std::cout &lt;&lt; "Apply was clicked";
  print_status();
}

void ExampleAssistant::on_assistant_cancel()
{
  std::cout &lt;&lt; "Cancel was clicked";
  print_status();
  hide();
}

void ExampleAssistant::on_assistant_close()
{
  std::cout &lt;&lt; "Assistant was closed";
  print_status();
  hide();
}

void ExampleAssistant::on_assistant_prepare(Gtk::Widget* /* widget */)
{
  set_title(Glib::ustring::compose("Gtk::Assistant example (Page %1 of %2)",
    get_current_page() + 1, get_n_pages()));
}

void ExampleAssistant::on_entry_changed()
{
  // The page is only complete if the entry contains text.
  if(m_entry.get_text_length())
    set_page_complete(m_box, true);
  else
    set_page_complete(m_box, false);
}

void ExampleAssistant::print_status()
{
  std::cout &lt;&lt; ", entry contents: \"" &lt;&lt; m_entry.get_text()
    &lt;&lt; "\", checkbutton status: " &lt;&lt; m_check.get_active() &lt;&lt; std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  // Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect3>

</sect2>

</sect1>

</chapter>

<chapter id="chapter-treeview">

<title>Widget de visualização em árvore</title>
<para>O widget <classname>Gtk::TreeView</classname> pode conter listas ou árvores de dados, em colunas.</para>

<sect1 id="sec-treeview-model">
<title>Modelo</title>
<para lang="en">
Each <classname>Gtk::TreeView</classname> has an associated
<classname>Gtk::TreeModel</classname>, which contains the data displayed by the
<classname>TreeView</classname>. Each <classname>Gtk::TreeModel</classname> can
be used by more than one <classname>Gtk::TreeView</classname>. For instance,
this allows the same underlying data to be displayed and edited in 2 different
ways at the same time. Or the 2 Views might display different columns from the
same Model data, in the same way that 2 SQL queries (or "views") might
show different fields from the same database table.
</para>
<para>Embora você pode, teoricamente, implementar seu próprio modelo, normalmente você vai usar a classe modelo <classname>ListStore</classname> ou <classname>TreeStore</classname>.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeModel.html">Reference</ulink></para>

<sect2 id="treeview-model-liststore">
<title lang="en">ListStore, for rows</title>
<para lang="en">
The <classname>ListStore</classname> contains simple rows of data, and each row
has no children.
</para>

<figure id="figure-treeview-liststore-model">
  <title lang="en">TreeView - ListStore</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/treeview_list.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ListStore.html">Reference</ulink></para>

</sect2>

<sect2 id="treeview-model-treestore">
<title>TreeStore, por hierarquia</title>
<para lang="en">
The <classname>TreeStore</classname> contains rows of data, and each row may
have child rows.
</para>

<figure id="figure-treeview-treestore-model">
  <title>TreeView - TreeStore</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/treeview_tree.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeStore.html">Reference</ulink></para>

</sect2>

<sect2 id="treeview-model-columns">
<title>Modelo de colunas</title>
<para lang="en">
The <classname>TreeModelColumnRecord</classname> class is used to keep track
of the columns and their data types. You add
<classname>TreeModelColumn</classname> instances to the
<classname>ColumnRecord</classname> and then use those
<classname>TreeModelColumns</classname> when getting and setting the data in
model rows. You will probably find it convenient to derive a new
<classname>TreeModelColumnRecord</classname> which has your
<classname>TreeModelColumn</classname> instances as member data.
</para>

<programlisting lang="en">class ModelColumns : public Gtk::TreeModelColumnRecord
{
public:

  ModelColumns()
    { add(m_col_text); add(m_col_number); }

  Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_text;
  Gtk::TreeModelColumn&lt;int&gt; m_col_number;
};

ModelColumns m_Columns;</programlisting>

<para lang="en">
You specify the <classname>ColumnRecord</classname> when creating the Model,
like so:
</para>
<programlisting lang="en">Glib::RefPtr&lt;Gtk::ListStore&gt; refListStore =
    Gtk::ListStore::create(m_Columns);</programlisting>
<para lang="en">Note that the instance (such as m_Columns here) should usually not be static, because it often needs to be instantiated after
glibmm has been instantiated.</para>
</sect2>

<sect2 id="treeview-adding-rows">
<title>Adicionando linhas</title>
<para lang="en">
Add rows to the model with the <methodname>append()</methodname>,
<methodname>prepend()</methodname>, or <methodname>insert()</methodname> methods.
</para>
<programlisting lang="en">Gtk::TreeModel::iterator iter = m_refListStore-&gt;append();</programlisting>
<para lang="en">You can dereference the iterator to get the Row:
</para>
<programlisting>Gtk::TreeModel::Row row = *iter;</programlisting>
<sect3 id="treeview-adding-child-rows"><title>Adicionando linhas filhas</title>
<para lang="en">
<classname>Gtk::TreeStore</classname> models can have child items. Add them
with the <methodname>append()</methodname>, <methodname>prepend()</methodname>, or
<methodname>insert()</methodname> methods, like so:
</para>
<programlisting lang="en">Gtk::TreeModel::iterator iter_child =
    m_refTreeStore-&gt;append(row.children());</programlisting>
</sect3>

</sect2>

<sect2 id="treeview-setting-values">
<title>Ajustando valores</title>
<para lang="en">
You can use the <methodname>operator[]</methodname> override to set the data for a
particular column in the row, specifying the
<classname>TreeModelColumn</classname> used to create the model.
</para>
<programlisting lang="en">row[m_Columns.m_col_text] = "sometext";</programlisting>
</sect2>

<sect2 id="treeview-getting-values">
<title>Obtenção de valores</title>
<para lang="en">
You can use the <methodname>operator[]</methodname> override to get the data in a
particular column in a row, specifiying the
<classname>TreeModelColumn</classname> used to create the model.
</para>
<programlisting lang="en">Glib::ustring strText = row[m_Columns.m_col_text];
int number = row[m_Columns.m_col_number];</programlisting>
<para lang="en">
The compiler will complain if you use an inappropriate type. For
instance, this would generate a compiler error:
</para>
<programlisting lang="en">//compiler error - no conversion from ustring to int.
int number = row[m_Columns.m_col_text];</programlisting>
</sect2>

<sect2 id="treeview-hidden-columns">
<title>"Ocultando" colunas</title>
<para lang="en">
You might want to associate extra data with each row. If so, just add
it as a Model column, but don't add it to the View.
</para>
</sect2>

</sect1>

<sect1 id="sec-treeview">
<title>Visualização</title>
<para lang="en">
The View is the actual widget (<classname>Gtk::TreeView</classname>) that
displays the model (<classname>Gtk::TreeModel</classname>) data and allows the
user to interact with it. The View can show all of the model's columns, or just
some, and it can show them in various ways.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeView.html">Reference</ulink></para>

<sect2 id="sec-treeview-using-a-model">
<title>Utilizando um modelo</title>
<para lang="en">
You can specify a <classname>Gtk::TreeModel</classname> when constructing the
<classname>Gtk::TreeView</classname>, or you can use the
<methodname>set_model()</methodname> method, like so:
</para>
<programlisting>m_TreeView.set_model(m_refListStore);</programlisting>
</sect2>

<sect2 id="treeview-adding-view-columns">
<title>Adicionando visualização em colunas</title>
<para lang="en">
You can use the <methodname>append_column()</methodname> method to  tell the View
that it should display certain Model columns, in a certain order, with a
certain column title.
</para>
<programlisting lang="en">m_TreeView.append_column("Messages", m_Columns.m_col_text);</programlisting>
<para lang="en">
When using this simple <methodname>append_column()</methodname> override, the
<classname>TreeView</classname> will display the model data with an appropriate
<classname>CellRenderer</classname>. For instance, strings and numbers are
shown in a simple <classname>Gtk::Entry</classname> widget, and booleans are
shown in a <classname>Gtk::CheckButton</classname>. This is usually what you
need. For other column types you must either connect a callback that converts
your type into a string representation, with
<methodname>TreeViewColumn::set_cell_data_func()</methodname>, or derive a custom
<classname>CellRenderer</classname>. Note that (unsigned) short is not
supported by default - You could use (unsigned) int or (unsigned) long as the
column type instead.
</para>
</sect2>

<sect2 id="treeview-multiple-model-columns-per-view-column">
<title lang="en">More than one Model Column per View Column</title>
<para lang="en">
To render more than one model column in a view column, you need to create the
<classname>TreeView::Column</classname> widget manually, and use
<methodname>pack_start()</methodname> to add the model columns to it.
</para>

<para lang="en">
Then use <methodname>append_column()</methodname> to add the view Column to the
View. Notice that <methodname>Gtk::TreeView::append_column()</methodname> is overridden
to accept either a prebuilt <classname>Gtk::TreeView::Column</classname> widget, or
just the <classname>TreeModelColumn</classname> from which it generates an
appropriate <classname>Gtk::TreeView::Column</classname> widget.
</para>
<para lang="en">
Here is some example code from
<filename>gtkmm/demos/gtk-demo/example_icontheme.cc</filename>, which has a pixbuf
icon and a text name in the same column:
</para>
<programlisting lang="en">Gtk::TreeView::Column* pColumn =
  Gtk::manage(new Gtk::TreeView::Column("Icon Name"));

// m_columns.icon and m_columns.iconname are columns in the model.
// pColumn is the column in the TreeView:
pColumn-&gt;pack_start(m_columns.icon, /* expand= */ false);
pColumn-&gt;pack_start(m_columns.iconname);

m_TreeView.append_column(*pColumn);</programlisting>
</sect2>

<sect2 id="treeview-cellrenderer-details">
<title>Especificando detalhes do renderizador de célula</title>
<para lang="en">
The default <classname>CellRenderers</classname> and their default behaviour
will normally suffice, but you might occasionally need finer control. For
instance, this example code from
<filename>gtkmm/demos/gtk-demo/example_treeview_treestore.cc</filename>, appends a
<classname>Gtk::CellRenderer</classname> widget and instructs it to render the
data from various model columns through various aspects of its appearance.
</para>
<programlisting lang="en">int cols_count = m_TreeView.append_column_editable("Alex", m_columns.alex);
Gtk::TreeViewColumn* pColumn = m_TreeView.get_column(cols_count-1);
if(pColumn)
{
  Gtk::CellRendererToggle* pRenderer =
    static_cast&lt;Gtk::CellRendererToggle*&gt;(pColumn-&gt;get_first_cell());
  pColumn-&gt;add_attribute(pRenderer-&gt;property_visible(), m_columns.visible);
  pColumn-&gt;add_attribute(pRenderer-&gt;property_activatable(), m_columns.world);</programlisting>

<para lang="en">
    You can also connect to <classname>CellRenderer</classname> signals to detect user
actions. For instance:
</para>
<programlisting lang="en">Gtk::CellRendererToggle* pRenderer =
    Gtk::manage( new Gtk::CellRendererToggle() );
pRenderer-&gt;signal_toggled().connect(
    sigc::bind( sigc::mem_fun(*this,
        &amp;Example_TreeView_TreeStore::on_cell_toggled), m_columns.dave)
);</programlisting>
</sect2>

<sect2 id="treeview-editable-cells">
<title>Células editáveis</title>

<sect3 id="treeview-editable-cells-automatic">
<title lang="en">Automatically-stored editable cells.</title>
<para lang="en">
Cells in a <classname>TreeView</classname> can be edited in-place by the user.
To allow this, use the <classname>Gtk::TreeView</classname>
<methodname>insert_column_editable()</methodname> and
<methodname>append_column_editable()</methodname> methods instead of
<methodname>insert_column()</methodname> and <methodname>append_column()</methodname>.
When these cells are edited the new values will be stored immediately in the
Model. Note that these methods are templates which can only be instantiated for
simple column types such as <classname>Glib::ustring</classname>, int, and
long.
</para>
</sect3>

<sect3 id="treeview-editable-cells-custom">
<title lang="en">Implementing custom logic for editable cells.</title>
<para lang="en">
However, you might not want the new values to be stored
immediately. For instance, maybe you want to restrict the input to
certain characters or ranges of values.
</para>
<para lang="en">
To achieve this, you should use the normal <classname>Gtk::TreeView</classname>
<methodname>insert_column()</methodname> and <methodname>append_column()</methodname>
methods, then use <methodname>get_column_cell_renderer()</methodname> to get the
<classname>Gtk::CellRenderer</classname> used by that column.
</para>
<para lang="en">
You should then cast that <classname>Gtk::CellRenderer*</classname> to the
specific <classname>CellRenderer</classname> that you expect, so you can use specific API.
</para>
<para lang="en">For instance, for a CellRendererText, you would set the cell's <emphasis>editable</emphasis> property to true, like
so:
</para>
<programlisting lang="en">cell.property_editable() = true;</programlisting>
<para lang="en">
For a CellRendererToggle, you would set the <emphasis>activatable</emphasis>
property instead.
</para>
<para lang="en">You can then connect
to the appropriate "edited" signal. For instance, connect to
<methodname>Gtk::CellRendererText::signal_edited()</methodname>, or
<methodname>Gtk::CellRendererToggle::signal_toggled()</methodname>. If the column
contains more than one <classname>CellRenderer</classname> then you will need
to use <methodname>Gtk::TreeView::get_column()</methodname> and then call
<methodname>get_cell_renderers()</methodname> on that view Column.
</para>
<para lang="en">
In your signal handler, you should examine the new value and then
store it in the Model if that is appropriate for your application.
</para>
</sect3>

</sect2>


</sect1>

<sect1 id="sec-iterating-over-model-rows">
<title lang="en">Iterating over Model Rows</title>
<para lang="en">
<classname>Gtk::TreeModel</classname> provides a C++ Standard Library-style container of its
children, via the <methodname>children()</methodname> method. You can use the
familiar <methodname>begin()</methodname> and <methodname>end()</methodname> methods
iterator incrementing, like so:
</para>
<programlisting lang="en">typedef Gtk::TreeModel::Children type_children; //minimise code length.
type_children children = refModel-&gt;children();
for(type_children::iterator iter = children.begin();
    iter != children.end(); ++iter)
{
  Gtk::TreeModel::Row row = *iter;
  //Do something with the row - see above for set/get.
}</programlisting>

<sect2 id="treeview-row-children">
<title>Linhas filhas</title>
<para lang="en">
When using a <classname>Gtk::TreeStore</classname>, the rows can have child
rows, which can have their own children in turn. Use
<methodname>Gtk::TreeModel::Row::children()</methodname> to get the container of child <classname>Row</classname>s:
<programlisting lang="en">Gtk::TreeModel::Children children = row.children();</programlisting>
</para>
</sect2>

</sect1>

<sect1 id="sec-treeview-selection">
<title>Seleção</title>
<para lang="en">
To find out what rows the user has selected, get the
<classname>Gtk::TreeView::Selection</classname> object from the
<classname>TreeView</classname>, like so:
</para>
<programlisting lang="en">Glib::RefPtr&lt;Gtk::TreeSelection&gt; refTreeSelection =
    m_TreeView.get_selection();</programlisting>

<sect2 id="treeview-selection-mode">
<title>Seleção única ou múltipla</title>
<para lang="en">
By default, only single rows can be selected, but you can allow
multiple selection by setting the mode, like so:
<programlisting lang="en">refTreeSelection-&gt;set_mode(Gtk::SELECTION_MULTIPLE);</programlisting>
</para>
</sect2>

<sect2 id="treeview-selected-rows">
<title>As linhas selecionadas</title>
<para lang="en">
For single-selection, you can just call <methodname>get_selected()</methodname>,
like so:
</para>
<programlisting lang="en">TreeModel::iterator iter = refTreeSelection-&gt;get_selected();
if(iter) //If anything is selected
{
  TreeModel::Row row = *iter;
  //Do something with the row.
}</programlisting>

<para lang="en">
For multiple-selection, you need to define a callback, and give it to
<methodname>selected_foreach()</methodname>,
<methodname>selected_foreach_path()</methodname>, or
<methodname>selected_foreach_iter()</methodname>, like so:
</para>
<programlisting lang="en">refTreeSelection-&gt;selected_foreach_iter(
    sigc::mem_fun(*this, &amp;TheClass::selected_row_callback) );

void TheClass::selected_row_callback(
    const Gtk::TreeModel::iterator&amp; iter)
{
  TreeModel::Row row = *iter;
  //Do something with the row.
}</programlisting>

</sect2>

<sect2 id="treeview-selection-changed-signal">
<title>O sinal "changed"</title>
<para lang="en">
To respond to the user clicking on a row or range of rows, connect to the
signal like so:
</para>
<programlisting lang="en">refTreeSelection-&gt;signal_changed().connect(
    sigc::mem_fun(*this, &amp;Example_IconTheme::on_selection_changed)
);</programlisting>
</sect2>

<sect2 id="treeview-selection-preventing">
<title>Impedindo a seleção de linhas</title>
<para lang="en">
Maybe the user should not be able to select every item in your list or tree.
For instance, in the gtk-demo, you can select a demo to see the source code,
but it doesn't make any sense to select a demo category.
</para>
<para lang="en">
To control which rows can be selected, use the
<methodname>set_select_function()</methodname> method, providing a
<classname>sigc::slot</classname> callback. For instance:
</para>
<programlisting lang="en">m_refTreeSelection-&gt;set_select_function( sigc::mem_fun(*this,
    &amp;DemoWindow::select_function) );</programlisting>
<para>e, em seguida,</para>
<programlisting lang="en">bool DemoWindow::select_function(
    const Glib::RefPtr&lt;Gtk::TreeModel&gt;&amp; model,
    const Gtk::TreeModel::Path&amp; path, bool)
{
  const Gtk::TreeModel::iterator iter = model-&gt;get_iter(path);
  return iter-&gt;children().empty(); // only allow leaf nodes to be selected
}</programlisting>
</sect2>

<sect2 id="treeview-selection-changing">
<title>Alterando a seleção</title>
<para lang="en">
To change the selection, specify a
<classname>Gtk::TreeModel::iterator</classname> or
<classname>Gtk::TreeModel::Row</classname>, like so:
</para>
<programlisting lang="en">Gtk::TreeModel::Row row = m_refModel-&gt;children()[5]; //The fifth row.
if(row)
  refTreeSelection-&gt;select(row);</programlisting>
<para> ou </para>
<programlisting lang="en">Gtk::TreeModel::iterator iter = m_refModel-&gt;children().begin()
if(iter)
  refTreeSelection-&gt;select(iter);</programlisting>
</sect2>

</sect1>


<sect1 id="sec-treeview-sort">
<title>Classificando</title>
<para lang="en">
The standard tree models (<classname>TreeStore</classname> and <classname>ListStore</classname>) derive from <classname>TreeSortable</classname>, so they offer sorting functionality. For instance, call <methodname>set_sort_column()</methodname>, to sort the model by the specified column. Or supply a callback function to <methodname>set_sort_func()</methodname> to implement a more complicated sorting algorithm.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeSortable.html">TreeSortable Reference</ulink></para>

<sect2 id="treeview-sort-headers">
<title lang="en">Sorting by clicking on columns</title>
<para lang="en">
So that a user can click on a <classname>TreeView</classname>'s column header to sort the <classname>TreeView</classname>'s contents, call <methodname>Gtk::TreeView::Column::set_sort_column()</methodname>, supplying the model column on which model should be sorted when the header is clicked. For instance:
</para>
<programlisting lang="en">Gtk::TreeView::Column* pColumn = treeview.get_column(0);
if(pColumn)
  pColumn-&gt;set_sort_column(m_columns.m_col_id);</programlisting>
</sect2>

<sect2 id="treeview-sort-independent-views">
<title lang="en">Independently sorted views of the same model</title>
<para lang="en">
The <classname>TreeView</classname> already allows you to show the same <classname>TreeModel</classname> in two <classname>TreeView</classname> widgets. If you need one of these TreeViews to sort the model differently than the other then you should use a <classname>TreeModelSort</classname> instead of just, for instance, <methodname>Gtk::TreeViewModel::set_sort_column()</methodname>. <classname>TreeModelSort</classname> is a model that contains another model, presenting a sorted version of that model. For instance, you might add a sorted version of a model to a <classname>TreeView</classname> like so:
</para>
<programlisting lang="en">Glib::RefPtr&lt;Gtk::TreeModelSort&gt; sorted_model =
    Gtk::TreeModelSort::create(model);
sorted_model-&gt;set_sort_column(columns.m_col_name, Gtk::SORT_ASCENDING);
treeview.set_model(sorted_model);</programlisting>

<para lang="en">Note, however, that the TreeView will provide iterators to the sorted model. You must convert them to iterators to the underlying child model in order to perform actions on that model. For instance:
</para>
<programlisting lang="en">void ExampleWindow::on_button_delete()
{
  Glib::RefPtr&lt;Gtk::TreeSelection&gt; refTreeSelection =
      m_treeview.get_selection();
  if(refTreeSelection)
  {
    Gtk::TreeModel::iterator sorted_iter =
        m_refTreeSelection-&gt;get_selected();
    if(sorted_iter)
    {
      Gtk::TreeModel::iterator iter =
          m_refModelSort-&gt;convert_iter_to_child_iter(sorted_iter);
      m_refModel-&gt;erase(iter);
    }
  }
}</programlisting>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TreeModelSort.html">TreeModelSort Reference</ulink></para>
</sect2>

</sect1>

<sect1 id="sec-treeview-draganddrop">
<title>Arrastar e soltar</title>
<para lang="en">
<classname>Gtk::TreeView</classname> already implements simple drag-and-drop
when used with the <classname>Gtk::ListStore</classname> or
<classname>Gtk::TreeStore</classname> models. If necessary, it also allows you
to implement more complex behaviour when items are dragged and dropped, using
the normal <link linkend="chapter-draganddrop">Drag and Drop</link> API.
</para>

<sect2 id="treeview-reorderable-rows">
<title>Linhas reordenáveis</title>
<para lang="en">
If you call <methodname>Gtk::TreeView::set_reorderable()</methodname> then your
TreeView's items can be moved within the treeview itself. This is demonstrated
in the <classname>TreeStore</classname> example.
</para>
<para lang="en">However, this does not allow you any control of which items can be dragged, and where they can be dropped. If you need that extra control then you might create a derived <literal>Gtk::TreeModel</literal> from <literal>Gtk::TreeStore</literal> or <literal>Gtk::ListStore</literal> and override the <literal>Gtk::TreeDragSource::row_draggable()</literal> and <literal>Gdk::TreeDragDest::row_drop_possible()</literal> virtual methods. You can examine the <literal>Gtk::TreeModel::Path</literal>s provided and allow or disallow dragging or dropping by returning <literal>true</literal> or <literal>false</literal>.</para>
<para lang="en">This is demonstrated in the drag_and_drop example.</para>
</sect2>

</sect1>

<sect1 id="sec-treeview-contextmenu">
<title>Contexto de menu popup</title>
<para lang="en">
Lots of people need to implement right-click context menus for
<classname>TreeView</classname>'s so we will explain how to do that  here to
save you some time. Apart from one or two points, it's  much the same as a
normal context menu, as described in the <link linkend="sec-menus-popup">menus
    chapter</link>.
</para>

<sect2 id="treeview-button-press-event">
<title lang="en">Handling <literal>button_press_event</literal></title>
<para lang="en">
To detect a click of the right mouse button, you need to handle the
<literal>button_press_event</literal> signal, and check exactly which button
was pressed. Because the <classname>TreeView</classname> normally handles this
signal completely, you need to either override the default signal handler in a
derived <classname>TreeView</classname> class, or use
<methodname>connect_notify()</methodname> instead of <methodname>connect()</methodname>.
You probably also want to call the default handler before doing anything else,
so that the right-click will cause the row to be selected first.
</para>
<para lang="en">This is demonstrated in the Popup Context Menu example.</para>
</sect2>

</sect1>

<sect1 id="sec-treeview-examples"><title lang="en">Examples</title>

<sect2 id="liststore-example"><title lang="en">ListStore</title>
<para lang="en">
This example has a <classname>Gtk::TreeView</classname> widget, with a
<classname>Gtk::ListStore</classname> model.
</para>


<figure id="figure-treeview-liststore">
  <title lang="en">TreeView - ListStore</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/treeview_list.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/treeview/list/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_quit();

  //Tree model columns:
  class ModelColumns : public Gtk::TreeModel::ColumnRecord
  {
  public:

    ModelColumns()
    { add(m_col_id); add(m_col_name); add(m_col_number); add(m_col_percentage);}

    Gtk::TreeModelColumn&lt;unsigned int&gt; m_col_id;
    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
    Gtk::TreeModelColumn&lt;short&gt; m_col_number;
    Gtk::TreeModelColumn&lt;int&gt; m_col_percentage;
  };

  ModelColumns m_Columns;

  //Child widgets:
  Gtk::Box m_VBox;

  Gtk::ScrolledWindow m_ScrolledWindow;
  Gtk::TreeView m_TreeView;
  Glib::RefPtr&lt;Gtk::ListStore&gt; m_refTreeModel;

  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Quit;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_Quit("Quit")
{
  set_title("Gtk::TreeView (ListStore) example");
  set_border_width(5);
  set_default_size(400, 200);

  add(m_VBox);

  //Add the TreeView, inside a ScrolledWindow, with the button underneath:
  m_ScrolledWindow.add(m_TreeView);

  //Only show the scrollbars when they are necessary:
  m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

  m_VBox.pack_start(m_ScrolledWindow);
  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);

  m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
  m_ButtonBox.set_border_width(5);
  m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
  m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_quit) );

  //Create the Tree model:
  m_refTreeModel = Gtk::ListStore::create(m_Columns);
  m_TreeView.set_model(m_refTreeModel);

  //Fill the TreeView's model
  Gtk::TreeModel::Row row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 1;
  row[m_Columns.m_col_name] = "Billy Bob";
  row[m_Columns.m_col_number] = 10;
  row[m_Columns.m_col_percentage] = 15;

  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 2;
  row[m_Columns.m_col_name] = "Joey Jojo";
  row[m_Columns.m_col_number] = 20;
  row[m_Columns.m_col_percentage] = 40;

  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 3;
  row[m_Columns.m_col_name] = "Rob McRoberts";
  row[m_Columns.m_col_number] = 30;
  row[m_Columns.m_col_percentage] = 70;

  //Add the TreeView's view columns:
  //This number will be shown with the default numeric formatting.
  m_TreeView.append_column("ID", m_Columns.m_col_id);
  m_TreeView.append_column("Name", m_Columns.m_col_name);

  m_TreeView.append_column_numeric("Formatted number", m_Columns.m_col_number,
          "%010d" /* 10 digits, using leading zeroes. */);

  //Display a progress bar instead of a decimal number:
  Gtk::CellRendererProgress* cell = Gtk::manage(new Gtk::CellRendererProgress);
  int cols_count = m_TreeView.append_column("Some percentage", *cell);
  Gtk::TreeViewColumn* pColumn = m_TreeView.get_column(cols_count - 1);
  if(pColumn)
  {
    pColumn-&gt;add_attribute(cell-&gt;property_value(), m_Columns.m_col_percentage);
  }

  //Make all the columns reorderable:
  //This is not necessary, but it's nice to show the feature.
  //You can use TreeView::set_column_drag_function() to more
  //finely control column drag and drop.
  for(guint i = 0; i &lt; 2; i++)
  {
    Gtk::TreeView::Column* pColumn = m_TreeView.get_column(i);
    pColumn-&gt;set_reorderable();
  }

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_quit()
{
  hide();
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

<sect2 id="treestore-example"><title lang="en">TreeStore</title>

<para lang="en">
This example is very similar to the <classname>ListStore</classname> example,
but uses a <classname>Gtk::TreeStore</classname> model instead, and adds
children to the rows.
</para>

<figure id="figure-treeview-treestore">
  <title>TreeView - TreeStore</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/treeview_tree.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/treeview/tree/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_quit();
  void on_treeview_row_activated(const Gtk::TreeModel::Path&amp; path, Gtk::TreeViewColumn* column);
   
  //Tree model columns:
  class ModelColumns : public Gtk::TreeModel::ColumnRecord
  {
  public:

    ModelColumns()
    { add(m_col_id); add(m_col_name); }

    Gtk::TreeModelColumn&lt;int&gt; m_col_id;
    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
  };

  ModelColumns m_Columns;

  //Child widgets:
  Gtk::Box m_VBox;

  Gtk::ScrolledWindow m_ScrolledWindow;
  Gtk::TreeView m_TreeView;
  Glib::RefPtr&lt;Gtk::TreeStore&gt; m_refTreeModel;

  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Quit;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_Quit("Quit")
{
  set_title("Gtk::TreeView (TreeStore) example");
  set_border_width(5);
  set_default_size(400, 200);

  add(m_VBox);

  //Add the TreeView, inside a ScrolledWindow, with the button underneath:
  m_ScrolledWindow.add(m_TreeView);

  //Only show the scrollbars when they are necessary:
  m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

  m_VBox.pack_start(m_ScrolledWindow);
  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);

  m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
  m_ButtonBox.set_border_width(5);
  m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
  m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_quit) );

  //Create the Tree model:
  m_refTreeModel = Gtk::TreeStore::create(m_Columns);
  m_TreeView.set_model(m_refTreeModel);

  //All the items to be reordered with drag-and-drop:
  m_TreeView.set_reorderable();

  //Fill the TreeView's model
  Gtk::TreeModel::Row row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 1;
  row[m_Columns.m_col_name] = "Billy Bob";

  Gtk::TreeModel::Row childrow = *(m_refTreeModel-&gt;append(row.children()));
  childrow[m_Columns.m_col_id] = 11;
  childrow[m_Columns.m_col_name] = "Billy Bob Junior";

  childrow = *(m_refTreeModel-&gt;append(row.children()));
  childrow[m_Columns.m_col_id] = 12;
  childrow[m_Columns.m_col_name] = "Sue Bob";

  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 2;
  row[m_Columns.m_col_name] = "Joey Jojo";


  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 3;
  row[m_Columns.m_col_name] = "Rob McRoberts";

  childrow = *(m_refTreeModel-&gt;append(row.children()));
  childrow[m_Columns.m_col_id] = 31;
  childrow[m_Columns.m_col_name] = "Xavier McRoberts";

  //Add the TreeView's view columns:
  m_TreeView.append_column("ID", m_Columns.m_col_id);
  m_TreeView.append_column("Name", m_Columns.m_col_name);

  //Connect signal:
  m_TreeView.signal_row_activated().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_treeview_row_activated) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_quit()
{
  hide();
}

void ExampleWindow::on_treeview_row_activated(const Gtk::TreeModel::Path&amp; path,
        Gtk::TreeViewColumn* /* column */)
{
  Gtk::TreeModel::iterator iter = m_refTreeModel-&gt;get_iter(path);
  if(iter)
  {
    Gtk::TreeModel::Row row = *iter;
    std::cout &lt;&lt; "Row activated: ID=" &lt;&lt; row[m_Columns.m_col_id] &lt;&lt; ", Name="
        &lt;&lt; row[m_Columns.m_col_name] &lt;&lt; std::endl;
  }
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

<sect2 id="sec-editable-cells-example"><title>Células editáveis</title>

<para lang="en">
This example is identical to the <classname>ListStore</classname> example, but
it uses <methodname>TreeView::append_column_editable()</methodname> instead of
<methodname>TreeView::append_column()</methodname>.
</para>

<figure id="figure-treeview-editablecells">
  <title>TreeView - Células editáveis</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/treeview_editablecells.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/treeview/editable_cells/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_quit();

  void treeviewcolumn_validated_on_cell_data(Gtk::CellRenderer* renderer, const Gtk::TreeModel::iterator&amp; iter);
  void cellrenderer_validated_on_editing_started(Gtk::CellEditable* cell_editable, const Glib::ustring&amp; path);
  void cellrenderer_validated_on_edited(const Glib::ustring&amp; path_string, const Glib::ustring&amp; new_text);

  //Tree model columns:
  class ModelColumns : public Gtk::TreeModel::ColumnRecord
  {
  public:

    ModelColumns()
    { add(m_col_id); add(m_col_name); add(m_col_foo); add(m_col_number); add(m_col_number_validated); }

    Gtk::TreeModelColumn&lt;unsigned int&gt; m_col_id;
    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
    Gtk::TreeModelColumn&lt;bool&gt; m_col_foo;
    Gtk::TreeModelColumn&lt;int&gt; m_col_number;
    Gtk::TreeModelColumn&lt;int&gt; m_col_number_validated;
  };

  ModelColumns m_Columns;

  //Child widgets:
  Gtk::Box m_VBox;

  Gtk::ScrolledWindow m_ScrolledWindow;
  Gtk::TreeView m_TreeView;
  Glib::RefPtr&lt;Gtk::ListStore&gt; m_refTreeModel;

  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Quit;

  //For the validated column:
  //You could also use a CellRendererSpin or a CellRendererProgress:
  Gtk::CellRendererText m_cellrenderer_validated;
  Gtk::TreeView::Column m_treeviewcolumn_validated;
  bool m_validate_retry;
  Glib::ustring m_invalid_text_for_retry;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include &lt;cstdio&gt;
#include &lt;cstdlib&gt;
#include "examplewindow.h"

using std::sprintf;
using std::strtol;

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_Quit("Quit"),
  m_validate_retry(false)
{
  set_title("Gtk::TreeView Editable Cells example");
  set_border_width(5);
  set_default_size(400, 200);


  add(m_VBox);

  //Add the TreeView, inside a ScrolledWindow, with the button underneath:
  m_ScrolledWindow.add(m_TreeView);

  //Only show the scrollbars when they are necessary:
  m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

  m_VBox.pack_start(m_ScrolledWindow);
  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);

  m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
  m_ButtonBox.set_border_width(5);
  m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
  m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_quit) );

  //Create the Tree model:
  m_refTreeModel = Gtk::ListStore::create(m_Columns);
  m_TreeView.set_model(m_refTreeModel);

  //Fill the TreeView's model
  Gtk::TreeModel::Row row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 1;
  row[m_Columns.m_col_name] = "Billy Bob";
  row[m_Columns.m_col_foo] = true;
  row[m_Columns.m_col_number] = 10;

  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 2;
  row[m_Columns.m_col_name] = "Joey Jojo";
  row[m_Columns.m_col_foo] = true;
  row[m_Columns.m_col_number] = 20;

  row = *(m_refTreeModel-&gt;append());

  row[m_Columns.m_col_id] = 3;
  row[m_Columns.m_col_name] = "Rob McRoberts";
  row[m_Columns.m_col_foo] = false;
  row[m_Columns.m_col_number] = 30;

  //Add the TreeView's view columns:
  //We use the *_editable convenience methods for most of these,
  //because the default functionality is enough:
  m_TreeView.append_column_editable("ID", m_Columns.m_col_id);
  m_TreeView.append_column_editable("Name", m_Columns.m_col_name);
  m_TreeView.append_column_editable("foo", m_Columns.m_col_foo);
  m_TreeView.append_column_numeric_editable("foo", m_Columns.m_col_number,
          "%010d");


  //For this column, we create the CellRenderer ourselves, and connect our own
  //signal handlers, so that we can validate the data that the user enters, and
  //control how it is displayed.
  m_treeviewcolumn_validated.set_title("validated (&lt;10)");
  m_treeviewcolumn_validated.pack_start(m_cellrenderer_validated);
  m_TreeView.append_column(m_treeviewcolumn_validated);

  //Tell the view column how to render the model values:
  m_treeviewcolumn_validated.set_cell_data_func(m_cellrenderer_validated,
          sigc::mem_fun(*this,
              &amp;ExampleWindow::treeviewcolumn_validated_on_cell_data) );

  //Make the CellRenderer editable, and handle its editing signals:
  m_cellrenderer_validated.property_editable() = true;

  m_cellrenderer_validated.signal_editing_started().connect(
          sigc::mem_fun(*this,
        &amp;ExampleWindow::cellrenderer_validated_on_editing_started) );

  m_cellrenderer_validated.signal_edited().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::cellrenderer_validated_on_edited) );

  //If this was a CellRendererSpin then you would have to set the adjustment:
  //m_cellrenderer_validated.property_adjustment() = m_spin_adjustment;

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_quit()
{
  hide();
}

void ExampleWindow::treeviewcolumn_validated_on_cell_data(
        Gtk::CellRenderer* /* renderer */,
        const Gtk::TreeModel::iterator&amp; iter)
{
  //Get the value from the model and show it appropriately in the view:
  if(iter)
  {
    Gtk::TreeModel::Row row = *iter;
    int model_value = row[m_Columns.m_col_number_validated];

    //This is just an example.
    //In this case, it would be easier to use append_column_editable() or
    //append_column_numeric_editable()
    char buffer[32];
    sprintf(buffer, "%d", model_value); 

    Glib::ustring view_text = buffer;
    m_cellrenderer_validated.property_text() = view_text;
  }
}

void ExampleWindow::cellrenderer_validated_on_editing_started(
        Gtk::CellEditable* cell_editable, const Glib::ustring&amp; /* path */)
{
  //Start editing with previously-entered (but invalid) text, 
  //if we are allowing the user to correct some invalid data. 
  if(m_validate_retry)
  {
    //This is the CellEditable inside the CellRenderer. 
    Gtk::CellEditable* celleditable_validated = cell_editable;

    //It's usually an Entry, at least for a CellRendererText:
    Gtk::Entry* pEntry = dynamic_cast&lt;Gtk::Entry*&gt;(celleditable_validated);
    if(pEntry)
    {
      pEntry-&gt;set_text(m_invalid_text_for_retry);
      m_validate_retry = false;
      m_invalid_text_for_retry.clear();
    }
  }

}

void ExampleWindow::cellrenderer_validated_on_edited(
        const Glib::ustring&amp; path_string,
        const Glib::ustring&amp; new_text)
{
  Gtk::TreePath path(path_string);

  //Convert the inputed text to an integer, as needed by our model column:
  char* pchEnd = 0;
  int new_value = strtol(new_text.c_str(), &amp;pchEnd, 10);

  if(new_value &gt; 10)
  {
    //Prevent entry of numbers higher than 10.

    //Tell the user:
    Gtk::MessageDialog dialog(*this,
            "The number must be less than 10. Please try again.",
            false, Gtk::MESSAGE_ERROR);
    dialog.run();

    //Start editing again, with the bad text, so that the user can correct it.
    //A real application should probably allow the user to revert to the
    //previous text.

    //Set the text to be used in the start_editing signal handler:
    m_invalid_text_for_retry = new_text;
    m_validate_retry = true;

    //Start editing again:
    m_TreeView.set_cursor(path, m_treeviewcolumn_validated,
            m_cellrenderer_validated, true /* start_editing */);
  }
  else
  {
    //Get the row from the path:
    Gtk::TreeModel::iterator iter = m_refTreeModel-&gt;get_iter(path);
    if(iter)
    {
      Gtk::TreeModel::Row row = *iter;

      //Put the new value in the model:
      row[m_Columns.m_col_number_validated] = new_value;
    }
  }
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

<sect2 id="treeview-dnd-example"><title>Arrastar e soltar</title>

<para lang="en">
This example is much like the <classname>TreeStore</classname> example, but has
2 extra columns to indicate whether the row can be dragged, and whether it can
receive drag-and-dropped rows. It uses a derived
<classname>Gtk::TreeStore</classname> which overrides the virtual functions as
described in the <link linkend="sec-treeview-draganddrop">TreeView Drag and
    Drop</link> section.
</para>

<figure id="figure-treeview-draganddrop">
  <title>TreeView - Arrastar e soltar</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/treeview_draganddrop.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/treeview/drag_and_drop/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;
#include "treemodel_dnd.h"


class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_quit();


  //Child widgets:
  Gtk::Box m_VBox;

  Gtk::ScrolledWindow m_ScrolledWindow;
  Gtk::TreeView m_TreeView;
  Glib::RefPtr&lt;TreeModel_Dnd&gt; m_refTreeModel;

  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Quit;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>treemodel_dnd.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_TREEMODEL_DND_H
#define GTKMM_EXAMPLE_TREEMODEL_DND_H

#include &lt;gtkmm.h&gt;

class TreeModel_Dnd : public Gtk::TreeStore
{
protected:
  TreeModel_Dnd();

public:

  //Tree model columns:
  class ModelColumns : public Gtk::TreeModel::ColumnRecord
  {
  public:

    ModelColumns()
    { add(m_col_id); add(m_col_name); add(m_col_draggable); add(m_col_receivesdrags); }

    Gtk::TreeModelColumn&lt;int&gt; m_col_id;
    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
    Gtk::TreeModelColumn&lt;bool&gt; m_col_draggable;
    Gtk::TreeModelColumn&lt;bool&gt; m_col_receivesdrags;
  };

  ModelColumns m_Columns;

  static Glib::RefPtr&lt;TreeModel_Dnd&gt; create();

protected:
  //Overridden virtual functions:
  virtual bool row_draggable_vfunc(const Gtk::TreeModel::Path&amp; path) const;
  virtual bool row_drop_possible_vfunc(const Gtk::TreeModel::Path&amp; dest, const Gtk::SelectionData&amp; selection_data) const;
  
};

#endif //GTKMM_EXAMPLE_TREEMODEL_DND_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_Quit("_Quit", true)
{
  set_title("Gtk::TreeView (Drag and Drop) example");
  set_border_width(5);
  set_default_size(400, 200);

  add(m_VBox);

  //Add the TreeView, inside a ScrolledWindow, with the button underneath:
  m_ScrolledWindow.add(m_TreeView);

  //Only show the scrollbars when they are necessary:
  m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

  m_VBox.pack_start(m_ScrolledWindow);
  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);

  m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
  m_ButtonBox.set_border_width(5);
  m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
  m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_quit) );

  //Create the Tree model:
  //Use our derived model, which overrides some Gtk::TreeDragDest and
  //Gtk::TreeDragSource virtual functions:
  //The columns are declared in the overridden TreeModel.
  m_refTreeModel = TreeModel_Dnd::create();
  m_TreeView.set_model(m_refTreeModel);

  //Enable Drag-and-Drop of TreeView rows:
  //See also the derived TreeModel's *_vfunc overrides.
  m_TreeView.enable_model_drag_source();
  m_TreeView.enable_model_drag_dest();

  //Fill the TreeView's model
  Gtk::TreeModel::Row row = *(m_refTreeModel-&gt;append());
  row[m_refTreeModel-&gt;m_Columns.m_col_id] = 1;
  row[m_refTreeModel-&gt;m_Columns.m_col_name] = "Billy Bob";
  row[m_refTreeModel-&gt;m_Columns.m_col_draggable] = true;
  row[m_refTreeModel-&gt;m_Columns.m_col_receivesdrags] = true;

  Gtk::TreeModel::Row childrow = *(m_refTreeModel-&gt;append(row.children()));
  childrow[m_refTreeModel-&gt;m_Columns.m_col_id] = 11;
  childrow[m_refTreeModel-&gt;m_Columns.m_col_name] = "Billy Bob Junior";
  childrow[m_refTreeModel-&gt;m_Columns.m_col_draggable] = true;
  childrow[m_refTreeModel-&gt;m_Columns.m_col_receivesdrags] = true;

  childrow = *(m_refTreeModel-&gt;append(row.children()));
  childrow[m_refTreeModel-&gt;m_Columns.m_col_id] = 12;
  childrow[m_refTreeModel-&gt;m_Columns.m_col_name] = "Sue Bob";
  childrow[m_refTreeModel-&gt;m_Columns.m_col_draggable] = true;
  childrow[m_refTreeModel-&gt;m_Columns.m_col_receivesdrags] = true;

  row = *(m_refTreeModel-&gt;append());
  row[m_refTreeModel-&gt;m_Columns.m_col_id] = 2;
  row[m_refTreeModel-&gt;m_Columns.m_col_name] = "Joey Jojo";
  row[m_refTreeModel-&gt;m_Columns.m_col_draggable] = true;
  row[m_refTreeModel-&gt;m_Columns.m_col_receivesdrags] = true;

  row = *(m_refTreeModel-&gt;append());
  row[m_refTreeModel-&gt;m_Columns.m_col_id] = 3;
  row[m_refTreeModel-&gt;m_Columns.m_col_name] = "Rob McRoberts";
  row[m_refTreeModel-&gt;m_Columns.m_col_draggable] = true;
  row[m_refTreeModel-&gt;m_Columns.m_col_receivesdrags] = true;

  childrow = *(m_refTreeModel-&gt;append(row.children()));
  childrow[m_refTreeModel-&gt;m_Columns.m_col_id] = 31;
  childrow[m_refTreeModel-&gt;m_Columns.m_col_name] = "Xavier McRoberts";
  childrow[m_refTreeModel-&gt;m_Columns.m_col_draggable] = true;
  childrow[m_refTreeModel-&gt;m_Columns.m_col_receivesdrags] = true;

  //Add the TreeView's view columns:
  m_TreeView.append_column("ID", m_refTreeModel-&gt;m_Columns.m_col_id);
  m_TreeView.append_column("Name", m_refTreeModel-&gt;m_Columns.m_col_name);
  m_TreeView.append_column_editable("Draggable",
          m_refTreeModel-&gt;m_Columns.m_col_draggable);
  m_TreeView.append_column_editable("Receives Drags",
          m_refTreeModel-&gt;m_Columns.m_col_receivesdrags);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_quit()
{
  hide();
}

</programlisting>
<para lang="en">File: <filename>treemodel_dnd.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "treemodel_dnd.h"
#include &lt;iostream&gt;

TreeModel_Dnd::TreeModel_Dnd()
{
  //We can't just call Gtk::TreeModel(m_Columns) in the initializer list
  //because m_Columns does not exist when the base class constructor runs.
  //And we can't have a static m_Columns instance, because that would be
  //instantiated before the gtkmm type system.
  //So, we use this method, which should only be used just after creation:
  set_column_types(m_Columns);
}

Glib::RefPtr&lt;TreeModel_Dnd&gt; TreeModel_Dnd::create()
{
  return Glib::RefPtr&lt;TreeModel_Dnd&gt;( new TreeModel_Dnd() );
}

bool
TreeModel_Dnd::row_draggable_vfunc(const Gtk::TreeModel::Path&amp; path) const
{
  // Make the value of the "draggable" column determine whether this row can
  // be dragged:

  //TODO: Add a const version of get_iter to TreeModel:
  TreeModel_Dnd* unconstThis = const_cast&lt;TreeModel_Dnd*&gt;(this);
  const_iterator iter = unconstThis-&gt;get_iter(path);
  //const_iterator iter = get_iter(path);
  if(iter)
  {
    Row row = *iter;
    bool is_draggable = row[m_Columns.m_col_draggable];
    return is_draggable;
  }

  return Gtk::TreeStore::row_draggable_vfunc(path);
}

bool
TreeModel_Dnd::row_drop_possible_vfunc(const Gtk::TreeModel::Path&amp; dest,
        const Gtk::SelectionData&amp; selection_data) const
{
  //Make the value of the "receives drags" column determine whether a row can be
  //dragged into it:

  //dest is the path that the row would have after it has been dropped:
  //But in this case we are more interested in the parent row:
  Gtk::TreeModel::Path dest_parent = dest;
  bool dest_is_not_top_level = dest_parent.up();
  if(!dest_is_not_top_level || dest_parent.empty())
  {
    //The user wants to move something to the top-level.
    //Let's always allow that.
  }
  else
  {
    //Get an iterator for the row at this path:
    //We must unconst this. This should not be necessary with a future version
    //of gtkmm.
    //TODO: Add a const version of get_iter to TreeModel:
    TreeModel_Dnd* unconstThis = const_cast&lt;TreeModel_Dnd*&gt;(this);
    const_iterator iter_dest_parent = unconstThis-&gt;get_iter(dest_parent);
    //const_iterator iter_dest_parent = get_iter(dest);
    if(iter_dest_parent)
    {
      Row row = *iter_dest_parent;
      bool receives_drags = row[m_Columns.m_col_receivesdrags];
      return receives_drags;
    }
  }

  //You could also examine the row being dragged (via selection_data)
  //if you must look at both rows to see whether a drop should be allowed.
  //You could use
  //TODO: Add const version of get_from_selection_data(): Glib::RefPtr&lt;const
  //Gtk::TreeModel&gt; refThis = Glib::RefPtr&lt;const Gtk::TreeModel&gt;(this);
  //
  //Glib::RefPtr&lt;Gtk::TreeModel&gt; refThis =
  //Glib::RefPtr&lt;Gtk::TreeModel&gt;(const_cast&lt;TreeModel_Dnd*&gt;(this));
  //refThis-&gt;reference(); //, true /* take_copy */)
  //Gtk::TreeModel::Path path_dragged_row;
  //Gtk::TreeModel::Path::get_from_selection_data(selection_data, refThis,
  //path_dragged_row);

  return Gtk::TreeStore::row_drop_possible_vfunc(dest, selection_data);
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

<sect2 id="treeview-popup-menu-example"><title>Contexto de menu popup</title>

<para lang="en">
This example is much like the <classname>ListStore</classname> example, but
derives a custom <classname>TreeView</classname> in order to override the
<literal>button_press_event</literal>, and also to encapsulate the tree model
code in our derived class. See the <link linkend="sec-treeview-contextmenu">TreeView Popup Context Menu</link>
section.
</para>

<figure id="figure-treeview-popup">
  <title>TreeView - Contexto de menu popup</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/treeview_popup.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/treeview/popup/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;
#include "treeview_withpopup.h"

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_quit();

 

  //Child widgets:
  Gtk::Box m_VBox;

  Gtk::ScrolledWindow m_ScrolledWindow;
  TreeView_WithPopup m_TreeView;

  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Quit;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>treeview_withpopup.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_TREEVIEW_WITHPOPUP_H
#define GTKMM_EXAMPLE_TREEVIEW_WITHPOPUP_H

#include &lt;gtkmm.h&gt;

class TreeView_WithPopup : public Gtk::TreeView
{
public:
  TreeView_WithPopup();
  virtual ~TreeView_WithPopup();

protected:
  // Override Signal handler:
  // Alternatively, use signal_button_press_event().connect_notify()
  virtual bool on_button_press_event(GdkEventButton *ev);

  //Signal handler for popup menu items:
  void on_menu_file_popup_generic();

  
  //Tree model columns:
  class ModelColumns : public Gtk::TreeModel::ColumnRecord
  {
  public:

    ModelColumns()
    { add(m_col_id); add(m_col_name); }

    Gtk::TreeModelColumn&lt;unsigned int&gt; m_col_id;
    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
  };
  
  ModelColumns m_Columns;

  //The Tree model:
  Glib::RefPtr&lt;Gtk::ListStore&gt; m_refTreeModel;

  Gtk::Menu m_Menu_Popup;
};

#endif //GTKMM_EXAMPLE_TREEVIEW_WITHPOPUP_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_Quit("Quit")
{
  set_title("Gtk::TreeView (ListStore) example");
  set_border_width(5);
  set_default_size(400, 200);

  add(m_VBox);

  //Add the TreeView, inside a ScrolledWindow, with the button underneath:
  m_ScrolledWindow.add(m_TreeView);

  //Only show the scrollbars when they are necessary:
  m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

  m_VBox.pack_start(m_ScrolledWindow);
  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);

  m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
  m_ButtonBox.set_border_width(5);
  m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
  m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_quit) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_quit()
{
  hide();
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<para lang="en">File: <filename>treeview_withpopup.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "treeview_withpopup.h"
#include &lt;iostream&gt;

TreeView_WithPopup::TreeView_WithPopup()
{
  //Create the Tree model:
  m_refTreeModel = Gtk::ListStore::create(m_Columns);
  set_model(m_refTreeModel);

  //Fill the TreeView's model
  Gtk::TreeModel::Row row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 1;
  row[m_Columns.m_col_name] = "right-click on this";

  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 2;
  row[m_Columns.m_col_name] = "or this";

  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 3;
  row[m_Columns.m_col_name] = "or this, for a popup context menu";

  //Add the TreeView's view columns:
  append_column("ID", m_Columns.m_col_id);
  append_column("Name", m_Columns.m_col_name);

  //Fill popup menu:
  Gtk::MenuItem* item = Gtk::manage(new Gtk::MenuItem("_Edit", true));
  item-&gt;signal_activate().connect(
    sigc::mem_fun(*this, &amp;TreeView_WithPopup::on_menu_file_popup_generic) );
  m_Menu_Popup.append(*item);
    
  item = Gtk::manage(new Gtk::MenuItem("_Process", true));
  item-&gt;signal_activate().connect(
    sigc::mem_fun(*this, &amp;TreeView_WithPopup::on_menu_file_popup_generic) );
  m_Menu_Popup.append(*item);
    
  item = Gtk::manage(new Gtk::MenuItem("_Remove", true));
  item-&gt;signal_activate().connect(
    sigc::mem_fun(*this, &amp;TreeView_WithPopup::on_menu_file_popup_generic) );
  m_Menu_Popup.append(*item);

  m_Menu_Popup.accelerate(*this);
  m_Menu_Popup.show_all(); //Show all menu items when the menu pops up

#ifndef GLIBMM_DEFAULT_SIGNAL_HANDLERS_ENABLED
  signal_button_press_event()
    .connect(sigc::mem_fun(*this, &amp;TreeView_WithPopup::on_button_press_event), false);
#endif
}

TreeView_WithPopup::~TreeView_WithPopup()
{
}

bool TreeView_WithPopup::on_button_press_event(GdkEventButton* event)
{
  bool return_value = false;

  //Call base class, to allow normal handling,
  //such as allowing the row to be selected by the right-click:
  return_value = TreeView::on_button_press_event(event);

  //Then do our custom stuff:
  if( (event-&gt;type == GDK_BUTTON_PRESS) &amp;&amp; (event-&gt;button == 3) )
  {
    m_Menu_Popup.popup(event-&gt;button, event-&gt;time);
  }

  return return_value;
}

void TreeView_WithPopup::on_menu_file_popup_generic()
{
  std::cout &lt;&lt; "A popup menu item was selected." &lt;&lt; std::endl;

  Glib::RefPtr&lt;Gtk::TreeView::Selection&gt; refSelection = get_selection();
  if(refSelection)
  {
    Gtk::TreeModel::iterator iter = refSelection-&gt;get_selected();
    if(iter)
    {
      int id = (*iter)[m_Columns.m_col_id];
      std::cout &lt;&lt; "  Selected ID=" &lt;&lt; id &lt;&lt; std::endl;
    }
  }
}
</programlisting>
<!-- end inserted example code -->

</sect2>


</sect1>

</chapter>


<chapter id="chapter-combobox">
<title>Caixa de combinação</title>

<para lang="en">The <classname>ComboBox</classname> widget offers a list (or tree) of choices in a dropdown menu. If appropriate, it can show extra information about each item, such as text, a picture, a checkbox, or a progress bar. The <classname>ComboBox</classname> widget usually restricts the user to the available choices, but it can optionally have an <classname>Entry</classname>, allowing the user to enter arbitrary text if none of the available choices are suitable.
</para>

<para lang="en">The list is provided via a <classname>TreeModel</classname>, and columns from this model are added to the ComboBox's view with the <methodname>ComboBox::pack_start()</methodname> method. This provides flexibility and compile-time type-safety, but the <classname>ComboBoxText</classname> class provides a simpler text-based specialization in case that flexibility is not required.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ComboBox.html">Reference</ulink></para>

<sect1 id="sec-combobox-model">
<title>O modelo</title>
<para lang="en">The model for a ComboBox can be defined and filled exactly as for a <classname>TreeView</classname>. For instance, you might derive a ComboBox class with one integer and one text column, like so:
</para>
<programlisting lang="en">ModelColumns()
{ add(m_col_id); add(m_col_name); }

  Gtk::TreeModelColumn&lt;int&gt; m_col_id;
  Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
};

ModelColumns m_columns;</programlisting>

<para lang="en">After appending rows to this model, you should provide the model to the <classname>ComboBox</classname> with the <methodname>set_model()</methodname> method. Then use the <methodname>pack_start()</methodname> or <methodname>pack_end()</methodname> methods to specify what columns will be displayed in the ComboBox. As with the TreeView you may either use the default cell renderer by passing the <classname>TreeModelColumn</classname> to the pack methods, or you may instantiate a specific <classname>CellRenderer</classname> and specify a particular mapping with either <methodname>add_attribute()</methodname> or <methodname>set_cell_data_func()</methodname>. Note that these methods are in the <classname>CellLayout</classname> base class.</para>
</sect1>

<sect1 id="sec-combobox-get">
<title>O item escolhido</title>
<para lang="en">To discover what item, if any, the user has chosen from the ComboBox, call <methodname>ComboBox::get_active()</methodname>. This returns a <classname>TreeModel::iterator</classname> that you can dereference to a <classname>Row</classname> in order to read the values in your columns. For instance, you might read an integer ID value from the model, even though you have chosen only to show the human-readable description in the ComboBox. For instance:
</para>
<programlisting lang="en">Gtk::TreeModel::iterator iter = m_Combo.get_active();
if(iter)
{
  Gtk::TreeModel::Row row = *iter;

  //Get the data for the selected row, using our knowledge
  //of the tree model:
  int id = row[m_Columns.m_col_id];
  set_something_id_chosen(id); //Your own function.
}
else
  set_nothing_chosen(); //Your own function.</programlisting>
</sect1>

<sect1 id="sec-combobox-changes">
<title>Respondendo as mudanças</title>
<para lang="en">
You might need to react to every change of selection in the ComboBox, for instance to update other widgets. To do so, you should handle the <literal>changed</literal> signal. For instance:
</para>
<programlisting lang="en">m_combo.signal_changed().connect( sigc::mem_fun(*this,
      &amp;ExampleWindow::on_combo_changed) );</programlisting>
</sect1>

<sect1 id="combobox-example-full"><title>Exemplo completo</title>

<figure id="figure-combobox-complex">
  <title>Caixa de combinação</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/combobox_complex.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/combobox/complex?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm/window.h&gt;
#include &lt;gtkmm/comboboxtext.h&gt;
#include &lt;gtkmm/liststore.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:  
  //Signal handlers:
  void on_combo_changed();

  //Tree model columns:
  class ModelColumns : public Gtk::TreeModel::ColumnRecord
  {
  public:

    ModelColumns()
    { add(m_col_id); add(m_col_name); }

    Gtk::TreeModelColumn&lt;int&gt; m_col_id;
    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
  };

  ModelColumns m_Columns;

  //Child widgets:
  Gtk::ComboBox m_Combo;
  Glib::RefPtr&lt;Gtk::ListStore&gt; m_refTreeModel;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
{
  set_title("ComboBox example");

  //Create the Tree model:
  //m_refTreeModel = Gtk::TreeStore::create(m_Columns);
  m_refTreeModel = Gtk::ListStore::create(m_Columns);
  m_Combo.set_model(m_refTreeModel);

  //Fill the ComboBox's Tree Model:
  Gtk::TreeModel::Row row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 1;
  row[m_Columns.m_col_name] = "Billy Bob";
  m_Combo.set_active(row);
  /*
  Gtk::TreeModel::Row childrow = *(m_refTreeModel-&gt;append(row.children()));
  childrow[m_Columns.m_col_id] = 11;
  childrow[m_Columns.m_col_name] = "Billy Bob Junior";

  childrow = *(m_refTreeModel-&gt;append(row.children()));
  childrow[m_Columns.m_col_id] = 12;
  childrow[m_Columns.m_col_name] = "Sue Bob";
  */

  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 2;
  row[m_Columns.m_col_name] = "Joey Jojo";


  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = 3;
  row[m_Columns.m_col_name] = "Rob McRoberts";

  /*
  childrow = *(m_refTreeModel-&gt;append(row.children()));
  childrow[m_Columns.m_col_id] = 31;
  childrow[m_Columns.m_col_name] = "Xavier McRoberts";
  */

  //Add the model columns to the Combo (which is a kind of view),
  //rendering them in the default way:
  m_Combo.pack_start(m_Columns.m_col_id);
  m_Combo.pack_start(m_Columns.m_col_name);

  //Add the ComboBox to the window.
  add(m_Combo);

  //Connect signal handler:
  m_Combo.signal_changed().connect( sigc::mem_fun(*this, &amp;ExampleWindow::on_combo_changed) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_combo_changed()
{
  Gtk::TreeModel::iterator iter = m_Combo.get_active();
  if(iter)
  {
    Gtk::TreeModel::Row row = *iter;
    if(row)
    {
      //Get the data for the selected row, using our knowledge of the tree
      //model:
      int id = row[m_Columns.m_col_id];
      Glib::ustring name = row[m_Columns.m_col_name];

      std::cout &lt;&lt; " ID=" &lt;&lt; id &lt;&lt; ", name=" &lt;&lt; name &lt;&lt; std::endl;
    }
  }
  else
    std::cout &lt;&lt; "invalid iter" &lt;&lt; std::endl;
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect1>

<sect1 id="combobox-example-simple"><title>Exemplo de texto simples</title>

<figure id="figure-combobox-text">
  <title lang="en">ComboBoxText</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/combobox_text.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/combobox/text?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm/window.h&gt;
#include &lt;gtkmm/comboboxtext.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_combo_changed();

  //Child widgets:
  Gtk::ComboBoxText m_Combo;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
{
  set_title("ComboBoxText example");

  //Fill the combo:
  m_Combo.append("something");
  m_Combo.append("something else");
  m_Combo.append("something or other");
  m_Combo.set_active(1);

  add(m_Combo);

  //Connect signal handler:
  m_Combo.signal_changed().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_combo_changed) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_combo_changed()
{
  Glib::ustring text = m_Combo.get_active_text();
  if(!(text.empty()))
    std::cout &lt;&lt; "Combo changed: " &lt;&lt; text &lt;&lt; std::endl;
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect1>

<sect1 id="sec-comboboxentry">
<title>ComboBox com uma entrada</title>

<para lang="en">A <classname>ComboBox</classname> may contain an <classname>Entry</classname> widget for entering of arbitrary text, by specifying <literal>true</literal> for the constructor's <literal>has_entry</literal> parameter.</para>

<sect2 id="sec-comboboxentry-text-column">
<title>A coluna de texto</title>
<para lang="en">So that the <classname>Entry</classname> can interact with the drop-down list of choices, you must specify which of your model columns is the text column, with <methodname>set_entry_text_column()</methodname>. For instance:
<programlisting lang="en">m_combo.set_entry_text_column(m_columns.m_col_name);</programlisting>
</para>
<para lang="en">
When you select a choice from the drop-down menu, the value from this column will be placed in the <classname>Entry</classname>.
</para>
</sect2>

<sect2 id="sec-comboboxentry-model">
<title>Entrada</title>
<para lang="en">Because the user may enter arbitrary text, an active model row isn't enough to tell us what text the user has entered. Therefore, you should retrieve the <classname>Entry</classname> widget with the <methodname>ComboBox::get_entry()</methodname> method and call <methodname>get_text()</methodname> on that.
</para>
</sect2>

<sect2 id="sec-comboboxentry-changes">
<title>Respondendo as mudanças</title>
<para lang="en">
When the user enters arbitrary text, it may not be enough to connect to the
<literal>changed</literal> signal, which is emitted for every typed character.
It is not emitted when the user presses the Enter key. Pressing the Enter key or
moving the keyboard focus to another widget may signal that the user has finished
entering text. To be notified of these events, connect to the
<classname>Entry</classname>'s <literal>activate</literal> and
<literal>focus_out_event</literal> signals, like so
<programlisting lang="en">Gtk::Entry* entry = m_Combo.get_entry();
if (entry)
{
  // The Entry shall receive focus-out events.
  entry-&gt;add_events(Gdk::FOCUS_CHANGE_MASK);

  // Alternatively you can connect to m_Combo.signal_changed().
  entry-&gt;signal_changed().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_entry_changed) );

  entry-&gt;signal_activate().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_entry_activate) );

  entry-&gt;signal_focus_out_event().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_entry_focus_out_event) );
}</programlisting>
The <literal>changed</literal> signals of <classname>ComboBox</classname> and
<classname>Entry</classname> are both emitted for every change. It doesn't matter
which one you connect to. But only <classname>Entry</classname>'s
<literal>focus_out_event</literal> signal is useful here.
</para>
<para lang="en">
X events are described in more detail in the
<link linkend="sec-xeventsignals">X Event signals</link> section in the appendix.
</para>
</sect2>

<sect2 id="comboboxentry-example-full"><title>Exemplo completo</title>

<figure id="figure-comboboxentry-complex">
  <title>Caixa de combinação com entrada</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/comboboxentry_complex.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/combobox/entry_complex?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm/window.h&gt;
#include &lt;gtkmm/combobox.h&gt;
#include &lt;gtkmm/liststore.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_entry_changed();
  void on_entry_activate();
  bool on_entry_focus_out_event(GdkEventFocus* event);

  //Signal connection:
  sigc::connection m_ConnectionFocusOut;

  //Tree model columns:
  class ModelColumns : public Gtk::TreeModel::ColumnRecord
  {
  public:

    ModelColumns()
    { add(m_col_id); add(m_col_name); }

    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_id; //The data to choose - this must be text.
    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
  };

  ModelColumns m_Columns;

  //Child widgets:
  Gtk::ComboBox m_Combo;
  Glib::RefPtr&lt;Gtk::ListStore&gt; m_refTreeModel;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_Combo(true /* has_entry */)
{
  set_title("ComboBox example");

  //Create the Tree model:
  //m_refTreeModel = Gtk::TreeStore::create(m_Columns);
  m_refTreeModel = Gtk::ListStore::create(m_Columns);
  m_Combo.set_model(m_refTreeModel);

  //Fill the ComboBox's Tree Model:
  Gtk::TreeModel::Row row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = "1";
  row[m_Columns.m_col_name] = "Billy Bob";
  /*
  Gtk::TreeModel::Row childrow = *(m_refTreeModel-&gt;append(row.children()));
  childrow[m_Columns.m_col_id] = 11;
  childrow[m_Columns.m_col_name] = "Billy Bob Junior";

  childrow = *(m_refTreeModel-&gt;append(row.children()));
  childrow[m_Columns.m_col_id] = 12;
  childrow[m_Columns.m_col_name] = "Sue Bob";
  */

  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = "2";
  row[m_Columns.m_col_name] = "Joey Jojo";

  row = *(m_refTreeModel-&gt;append());
  row[m_Columns.m_col_id] = "3";
  row[m_Columns.m_col_name] = "Rob McRoberts";

  /*
  childrow = *(m_refTreeModel-&gt;append(row.children()));
  childrow[m_Columns.m_col_id] = 31;
  childrow[m_Columns.m_col_name] = "Xavier McRoberts";
  */

  //Add the model columns to the Combo (which is a kind of view),
  //rendering them in the default way:
  //This is automatically rendered when we use set_entry_text_column().
  //m_Combo.pack_start(m_Columns.m_col_id);
  m_Combo.pack_start(m_Columns.m_col_name);

  m_Combo.set_entry_text_column(m_Columns.m_col_id);
  m_Combo.set_active(1);

  //Add the ComboBox to the window.
  add(m_Combo);

  //Connect signal handlers:
  Gtk::Entry* entry = m_Combo.get_entry();
  if (entry)
  {
    // The Entry shall receive focus-out events.
    entry-&gt;add_events(Gdk::FOCUS_CHANGE_MASK);
    // Alternatively you can connect to m_Combo.signal_changed().
    entry-&gt;signal_changed().connect(sigc::mem_fun(*this,
      &amp;ExampleWindow::on_entry_changed) );
    entry-&gt;signal_activate().connect(sigc::mem_fun(*this,
      &amp;ExampleWindow::on_entry_activate) );
    m_ConnectionFocusOut = entry-&gt;signal_focus_out_event().
      connect(sigc::mem_fun(*this, &amp;ExampleWindow::on_entry_focus_out_event) );
  }
  else
    std::cout &lt;&lt; "No Entry ???" &lt;&lt; std::endl;

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
  // The focus_out signal may be emitted while m_Combo is being destructed.
  // The signal handler can generate critical messages, if it's called when
  // m_Combo has been partly destructed.
  m_ConnectionFocusOut.disconnect();
}

void ExampleWindow::on_entry_changed()
{
  Gtk::Entry* entry = m_Combo.get_entry();
  if (entry)
  {
    std::cout &lt;&lt; "on_entry_changed(): Row=" &lt;&lt; m_Combo.get_active_row_number()
      &lt;&lt; ", ID=" &lt;&lt; entry-&gt;get_text() &lt;&lt; std::endl;
  }
}

void ExampleWindow::on_entry_activate()
{
  Gtk::Entry* entry = m_Combo.get_entry();
  if (entry)
  {
    std::cout &lt;&lt; "on_entry_activate(): Row=" &lt;&lt; m_Combo.get_active_row_number()
      &lt;&lt; ", ID=" &lt;&lt; entry-&gt;get_text() &lt;&lt; std::endl;
  }
}

bool ExampleWindow::on_entry_focus_out_event(GdkEventFocus* /* event */)
{
  Gtk::Entry* entry = m_Combo.get_entry();
  if (entry)
  {
    std::cout &lt;&lt; "on_entry_focus_out_event(): Row=" &lt;&lt; m_Combo.get_active_row_number()
      &lt;&lt; ", ID=" &lt;&lt; entry-&gt;get_text() &lt;&lt; std::endl;
    return true;
  }
  return false;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

<sect2 id="comboboxentry-example-simple"><title>Exemplo de texto simples</title>

<figure id="figure-comboboxentry-text">
  <title>ComboBoxText com uma entrada</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/comboboxentry_text.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/combobox/entry_text?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm/window.h&gt;
#include &lt;gtkmm/comboboxtext.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_combo_changed();
  void on_entry_activate();
  bool on_entry_focus_out_event(GdkEventFocus* event);

  //Signal connection:
  sigc::connection m_ConnectionFocusOut;

  //Child widgets:
  Gtk::ComboBoxText m_Combo;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_Combo(true /* has_entry */)
{
  set_title("ComboBoxText example");

  //Fill the combo:
  m_Combo.append("something");
  m_Combo.append("something else");
  m_Combo.append("something or other");
  m_Combo.set_active(0);

  add(m_Combo);

  //Connect signal handlers:
  Gtk::Entry* entry = m_Combo.get_entry();
  // Alternatively you can connect to entry-&gt;signal_changed().
  m_Combo.signal_changed().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_combo_changed) );
  if (entry)
  {
    // The Entry shall receive focus-out events.
    entry-&gt;add_events(Gdk::FOCUS_CHANGE_MASK);
    entry-&gt;signal_activate().connect(sigc::mem_fun(*this,
      &amp;ExampleWindow::on_entry_activate) );
    m_ConnectionFocusOut = entry-&gt;signal_focus_out_event().
      connect(sigc::mem_fun(*this, &amp;ExampleWindow::on_entry_focus_out_event) );
  }
  else
    std::cout &lt;&lt; "No Entry ???" &lt;&lt; std::endl;

  m_Combo.property_has_frame() = false;
  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
  // The focus_out signal may be emitted while m_Combo is being destructed.
  // The signal handler can generate critical messages, if it's called when
  // m_Combo has been partly destructed.
  m_ConnectionFocusOut.disconnect();
}

void ExampleWindow::on_combo_changed()
{
  std::cout &lt;&lt; "on_combo_changed(): Row=" &lt;&lt; m_Combo.get_active_row_number()
    &lt;&lt; ", Text=" &lt;&lt; m_Combo.get_active_text() &lt;&lt; std::endl;
}

void ExampleWindow::on_entry_activate()
{
  std::cout &lt;&lt; "on_entry_activate(): Row=" &lt;&lt; m_Combo.get_active_row_number()
    &lt;&lt; ", Text=" &lt;&lt; m_Combo.get_active_text() &lt;&lt; std::endl;
}

bool ExampleWindow::on_entry_focus_out_event(GdkEventFocus* /* event */)
{
  std::cout &lt;&lt; "on_entry_focus_out_event(): Row=" &lt;&lt; m_Combo.get_active_row_number()
    &lt;&lt; ", Text=" &lt;&lt; m_Combo.get_active_text() &lt;&lt; std::endl;
  return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>




</sect1>

</chapter>


<chapter id="chapter-textview">
<title lang="en">TextView</title>
<para lang="en">
The <classname>TextView</classname> widget can be used to display and edit
large amounts of formatted text. Like the <classname>TreeView</classname>, it
has a model/view design. In this case the <classname>TextBuffer</classname> is
the model.
</para>

<sect1 id="sec-textview-buffer">
<title>O Buffer</title>
<para lang="en">
<classname>Gtk::TextBuffer</classname> is a model containing the data for the
<classname>Gtk::TextView</classname>, like the
<classname>Gtk::TreeModel</classname> used by <classname>Gtk::TreeView</classname>.
This allows two or more <classname>Gtk::TextView</classname>s to share the same
<classname>TextBuffer</classname>, and allows those TextBuffers to be displayed
slightly differently. Or you could maintain several
<classname>Gtk::TextBuffer</classname>s and choose to display each one at different
times in the same <classname>Gtk::TextView</classname> widget.
</para>
<para lang="en">
The <classname>TextView</classname> creates its own default
<classname>TextBuffer</classname>, which you can access via the
<methodname>get_buffer()</methodname> method.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextBuffer.html">Reference</ulink></para>

<sect2 id="textview-iterators">
<title lang="en">Iterators</title>
<para>
</para>
</sect2>

<sect2 id="textview-formatting">
<title>Etiquetas e formatação</title>

<sect3 id="textview-formatting-tags">
<title>Etiquetas</title>
<para lang="en">
To specify that some text in the buffer should have specific formatting, you must define a tag to hold that formatting information, and then apply that tag to the region of text. For instance, to define the tag and its properties:
</para>
<programlisting lang="en">Glib::RefPtr&lt;Gtk::TextBuffer::Tag&gt; refTagMatch =
    Gtk::TextBuffer::Tag::create();
refTagMatch-&gt;property_background() = "orange";</programlisting>
<para lang="en">
You can specify a name for the <classname>Tag</classname> when using the
<methodname>create()</methodname> method, but it is not necessary.
</para>

<para lang="en">
The <classname>Tag</classname> class has many other properties.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextTag.html">Reference</ulink></para>

</sect3>

<sect3 id="textview-formatting-tagtable">
<title lang="en">TagTable</title>

<para lang="en">
Each <classname>Gtk::TextBuffer</classname> uses a
<classname>Gtk::TextBuffer::TagTable</classname>, which contains the
<classname>Tag</classname>s for that buffer. 2 or more
<classname>TextBuffer</classname>s may share the same
<classname>TagTable</classname>. When you create <classname>Tag</classname>s
you should add them to the <classname>TagTable</classname>. For instance:
</para>
<programlisting lang="en">Glib::RefPtr&lt;Gtk::TextBuffer::TagTable&gt; refTagTable =
    Gtk::TextBuffer::TagTable::create();
refTagTable-&gt;add(refTagMatch);
//Hopefully a future version of <application>gtkmm</application> will have a set_tag_table() method,
//for use after creation of the buffer.
Glib::RefPtr&lt;Gtk::TextBuffer&gt; refBuffer =
    Gtk::TextBuffer::create(refTagTable);</programlisting>

<para lang="en">
You can also use <methodname>get_tag_table()</methodname> to get, and maybe modify,
the <classname>TextBuffer</classname>'s default <classname>TagTable</classname>
instead of creating one explicitly.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextTagTable.html">Reference</ulink></para>

</sect3>

<sect3 id="textview-formatting-applying-tags">
<title>Aplicando etiquetas</title>
<para lang="en">
If you have created a <classname>Tag</classname> and added it to the
<classname>TagTable</classname>, you may apply that tag to part of the
<classname>TextBuffer</classname> so that some of the text is displayed with that
formatting. You define the start and end of the range of text by specifying
<classname>Gtk::TextBuffer::iterator</classname>s. For instance:
</para>
<programlisting lang="en">refBuffer-&gt;apply_tag(refTagMatch, iterRangeStart, iterRangeStop);</programlisting>
<para lang="en">
Or you could specify the tag when first inserting the text:
<programlisting lang="en">refBuffer-&gt;insert_with_tag(iter, "Some text", refTagMatch);</programlisting>
</para>

<para lang="en">
You can apply more than one <classname>Tag</classname> to the same text, by
using <methodname>apply_tag()</methodname> more than once, or by using
<methodname>insert_with_tags()</methodname>. The <classname>Tag</classname>s might
specify different values for the same properties, but you can resolve these
conflicts by using <methodname>Tag::set_priority()</methodname>.
</para>

</sect3>
</sect2>

<sect2 id="textview-marks">
<title>Marcas</title>
<para lang="en">
<classname>TextBuffer</classname> iterators are generally invalidated when the
text changes, but you can use a <classname>Gtk::TextBuffer::Mark</classname> to
remember a position in these situations. For instance,
</para>
<programlisting lang="en">Glib::RefPtr&lt;Gtk::TextBuffer::Mark&gt; refMark =
    refBuffer-&gt;create_mark(iter);</programlisting>

<para lang="en">
You can then use the <methodname>get_iter()</methodname> method later to create an
iterator for the <classname>Mark</classname>'s new position.
</para>

<para lang="en">
There are two built-in <classname>Mark</classname>s - <literal>insert</literal>
and <literal>selection_bound</literal>, which you can access with
<classname>TextBuffer</classname>'s <methodname>get_insert()</methodname> and
<methodname>get_selection_bound()</methodname> methods.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextMark.html">Reference</ulink></para>

</sect2>

<sect2 id="textview-view">
<title>Visualização</title>
<para lang="en">
As mentioned above, each <classname>TextView</classname> has a
<classname>TextBuffer</classname>, and one or more
<classname>TextView</classname>s can share the same
<classname>TextBuffer</classname>.
</para>

<para lang="en">
Like the <classname>TreeView</classname>, you should probably put your
<classname>TextView</classname> inside a <classname>ScrolledWindow</classname>
to allow the user to see and move around the whole text area with
scrollbars.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextView.html">Reference</ulink></para>

<sect3 id="textview-default-formatting">
<title>Formatação padrão</title>
<para lang="en">
<classname>TextView</classname> has various methods which allow you to change
the presentation of the buffer for this particular view. Some of these may be
overridden by the <classname>Gtk::TextTag</classname>s in the buffer, if they
specify the same things. For instance, <methodname>set_left_margin()</methodname>,
<methodname>set_right_margin()</methodname>, <methodname>set_indent()</methodname>,
etc.
</para>
</sect3>

<sect3 id="textview-scrolling">
<title>Deslocamento</title>
<para lang="en">
<classname>Gtk::TextView</classname> has various
<methodname>scroll_to_*()</methodname> methods. These allow you to ensure that a
particular part of the text buffer is visible. For instance, your application's
Find feature might use <methodname>Gtk::TextView::scroll_to_iter()</methodname> to
show the found text.
</para>
</sect3>

</sect2>


</sect1>

<sect1 id="sec-widgets-and-childanchors">
<title lang="en">Widgets and ChildAnchors</title>
<para lang="en">
You can embed widgets, such as <classname>Gtk::Button</classname>s, in the
text. Each such child widget needs a <classname>ChildAnchor</classname>.
ChildAnchors are associated with <classname>iterators</classname>. For
instance, to create a child anchor at a particular position, use
<methodname>Gtk::TextBuffer::create_child_anchor()</methodname>:
</para>
<programlisting lang="en">Glib::RefPtr&lt;Gtk::TextChildAnchor&gt; refAnchor =
    refBuffer-&gt;create_child_anchor(iter);</programlisting>

<para lang="en">
Then, to add a widget at that position, use
<methodname>Gtk::TextView::add_child_at_anchor()</methodname>:
</para>
<programlisting lang="en">m_TextView.add_child_at_anchor(m_Button, refAnchor);</programlisting>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1TextChildAnchor.html">Reference</ulink></para>

</sect1>

<sect1 id="sec-textview-examples"><title lang="en">Examples</title>

<sect2 id="textview-example-simple"><title>Exemplo simples</title>

<figure id="figure-textview">
  <title lang="en">TextView</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/textview.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/textview/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:

  void fill_buffers();
  
  //Signal handlers:
  void on_button_quit();
  void on_button_buffer1();
  void on_button_buffer2();

  //Child widgets:
  Gtk::Box m_VBox;

  Gtk::ScrolledWindow m_ScrolledWindow;
  Gtk::TextView m_TextView;
  
  Glib::RefPtr&lt;Gtk::TextBuffer&gt; m_refTextBuffer1, m_refTextBuffer2;

  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Quit, m_Button_Buffer1, m_Button_Buffer2;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_Quit("_Quit", true),
  m_Button_Buffer1("Use buffer 1"),
  m_Button_Buffer2("Use buffer 2")
{
  set_title("Gtk::TextView example");
  set_border_width(5);
  set_default_size(400, 200);

  add(m_VBox);

  //Add the TreeView, inside a ScrolledWindow, with the button underneath:
  m_ScrolledWindow.add(m_TextView);

  //Only show the scrollbars when they are necessary:
  m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

  m_VBox.pack_start(m_ScrolledWindow);

  //Add buttons:
  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);

  m_ButtonBox.pack_start(m_Button_Buffer1, Gtk::PACK_SHRINK);
  m_ButtonBox.pack_start(m_Button_Buffer2, Gtk::PACK_SHRINK);
  m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
  m_ButtonBox.set_border_width(5);
  m_ButtonBox.set_spacing(5);
  m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);

  //Connect signals:
  m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_quit) );
  m_Button_Buffer1.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_buffer1) );
  m_Button_Buffer2.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_buffer2) );

  fill_buffers();
  on_button_buffer1();

  show_all_children();
}

void ExampleWindow::fill_buffers()
{
  m_refTextBuffer1 = Gtk::TextBuffer::create();
  m_refTextBuffer1-&gt;set_text("This is the text from TextBuffer #1.");

  m_refTextBuffer2 = Gtk::TextBuffer::create();
  m_refTextBuffer2-&gt;set_text(
          "This is some alternative text, from TextBuffer #2.");

}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_quit()
{
  hide();
}

void ExampleWindow::on_button_buffer1()
{
  m_TextView.set_buffer(m_refTextBuffer1);
}

void ExampleWindow::on_button_buffer2()
{
  m_TextView.set_buffer(m_refTextBuffer2);
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

</sect1>

</chapter>

<chapter id="chapter-menus-and-toolbars">
<title>Menus e barras de ferramentas</title>

<para lang="en">
There are specific APIs for Menus and toolbars, but you should usually deal
with them together, using the <classname>UIManager</classname> to define
<classname>Action</classname>s which you can then arrange in menus and toolbars.
In this way you can handle activation of the action instead of responding to
the menu and toolbar items separately. And you can enable or disable both the
menu and toolbar item via the action.
</para>
<para lang="en">
This involves the use of the <classname>Gtk::ActionGroup</classname>,
<classname>Gtk::Action</classname>, and <classname>UIManager</classname>
classes, all of which should be instantiated via their
<methodname>create()</methodname> methods, which return
<classname>RefPtr</classname>s.
</para>
<note>
<para lang="en">
<classname>GtkAction</classname>, <classname>GtkActionGroup</classname> and
<classname>GtkUIManager</classname> are deprecated in GTK+ from version 3.10.
The corresponding classes in <application>gtkmm</application> will also be deprecated in the future.
The examples in this chapter use <classname>Gio::SimpleAction</classname>,
<classname>Gio::SimpleActionGroup</classname> and <classname>Gtk::Builder</classname> instead.
</para>
</note>

<sect1 id="sec-actions">
<title>Ações</title>
<para lang="en">
First create the <classname>Action</classname>s and add them to an
<classname>ActionGroup</classname>, with
<methodname>ActionGroup::add()</methodname>.
</para>

<para lang="en">
The arguments to <methodname>Action::create()</methodname> specify the action's
name and how it will appear in menus and toolbars.
</para>
<para lang="en">
You can also specify a signal handler when calling
<methodname>ActionGroup::add()</methodname>. This signal handler will be called
when the action is activated via either a menu item or a toolbar button.
</para>
<para lang="en">Note that you must specify actions for sub menus as well as menu items.</para>

<para>Por exemplo:</para>
<programlisting lang="en">m_refActionGroup = Gtk::ActionGroup::create();

m_refActionGroup-&gt;add( Gtk::Action::create("MenuFile", "_File") );
m_refActionGroup-&gt;add( Gtk::Action::create("New", "_New"),
  sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_new) );
m_refActionGroup-&gt;add( Gtk::Action::create("ExportData", "Export Data"),
  sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_open) );
m_refActionGroup-&gt;add( Gtk::Action::create("Quit", "_Quit"),
  sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_quit) );</programlisting>

<para lang="en">Note that this is where we specify the names of the actions as they will be seen by users in menus and toolbars. Therefore, this is where you should make strings translatable, by putting them inside the _() macro.</para>
</sect1>


<sect1 id="sec-uimanager">
<title lang="en">UIManager</title>
<para lang="en">
Next you should create a <classname>UIManager</classname> and add the
<classname>ActionGroup</classname> to the <classname>UIManager</classname> with
<methodname>insert_action_group()</methodname> At this point is also a good idea to
tell the parent window to respond to the specified keyboard shortcuts, by using
<methodname>add_accel_group()</methodname>.
</para>

<para>Por exemplo,</para>
<programlisting lang="en">Glib::RefPtr&lt;Gtk::UIManager&gt; m_refUIManager =
    Gtk::UIManager::create();
m_refUIManager-&gt;insert_action_group(m_refActionGroup);
add_accel_group(m_refUIManager-&gt;get_accel_group());</programlisting>
<para lang="en">
Then, you can define the actual visible layout of the menus and toolbars, and
add the UI layout to the <classname>UIManager</classname>. This "ui
string" uses an XML format, in which you should mention the names of the
actions that you have already created. For instance:
</para>
<programlisting lang="en">Glib::ustring ui_info =
    "&lt;ui&gt;"
    "  &lt;menubar name='MenuBar'&gt;"
    "    &lt;menu action='MenuFile'&gt;"
    "      &lt;menuitem action='New'/&gt;"
    "      &lt;menuitem action='Open'/&gt;"
    "      &lt;separator/&gt;"
    "      &lt;menuitem action='Quit'/&gt;"
    "    &lt;/menu&gt;"
    "    &lt;menu action='MenuEdit'&gt;"
    "      &lt;menuitem action='Cut'/&gt;"
    "      &lt;menuitem action='Copy'/&gt;"
    "      &lt;menuitem action='Paste'/&gt;"
    "    &lt;/menu&gt;"
    "  &lt;/menubar&gt;"
    "  &lt;toolbar  name='ToolBar'&gt;"
    "    &lt;toolitem action='Open'/&gt;"
    "    &lt;toolitem action='Quit'/&gt;"
    "  &lt;/toolbar&gt;"
    "&lt;/ui&gt;";

m_refUIManager-&gt;add_ui_from_string(ui_info);</programlisting>

<para lang="en">Remember that these names are just the identifiers that we used when creating the actions. They are not the text that the user will see in the menus and toolbars. We provided those human-readable names when we created the actions.</para>
<para lang="en">
To instantiate a <classname>Gtk::MenuBar</classname> or
<classname>Gtk::Toolbar</classname> which you can actually show, you should use
the <methodname>UIManager::get_widget()</methodname> method, and then add the widget
to a container. For instance:
</para>
<programlisting lang="en">Gtk::Widget* pMenubar = m_refUIManager-&gt;get_widget("/MenuBar");
pBox-&gt;add(*pMenuBar, Gtk::PACK_SHRINK);</programlisting>

</sect1>


<sect1 id="sec-menus-popup"><title>Menus popup</title>
<para lang="en">
<classname>Menus</classname> are normally just added to a window, but they can
also be displayed temporarily as the result of a mouse button click. For
instance, a context menu might be displayed when the user clicks their right
mouse button.
</para>

<para lang="en">The UI layout for a popup menu should use the <literal>popup</literal> node. For instance:
</para>
<programlisting lang="en">Glib::ustring ui_info =
    "&lt;ui&gt;"
    "  &lt;popup name='PopupMenu'&gt;"
    "    &lt;menuitem action='ContextEdit'/&gt;"
    "    &lt;menuitem action='ContextProcess'/&gt;"
    "    &lt;menuitem action='ContextRemove'/&gt;"
    "  &lt;/popup&gt;"
    "&lt;/ui&gt;";

m_refUIManager-&gt;add_ui_from_string(ui_info);</programlisting>

<para lang="en">
To show the popup menu, use <classname>Gtk::Menu</classname>'s
<methodname>popup()</methodname> method, providing the button identifier and the
time of activation, as provided by the <literal>button_press_event</literal>
signal, which you will need to handle anyway. For instance:
</para>
<programlisting lang="en">bool ExampleWindow::on_button_press_event(GdkEventButton* event)
{
  if( (event-&gt;type == GDK_BUTTON_PRESS) &amp;&amp;
      (event-&gt;button == 3) )
  {
    m_Menu_Popup-&gt;popup(event-&gt;button, event-&gt;time);
    return true; //It has been handled.
  }
  else
    return false;
}</programlisting>

</sect1>

<sect1 id="sec-gio-resource">
<title lang="en">Gio::Resource and glib-compile-resources</title>

<para lang="en">
Applications and libraries often contain binary or textual data that is
really part of the application, rather than user data. For instance
<classname>Gtk::Builder</classname> <filename class="extension">.glade</filename> files,
splashscreen images, <classname>Gio::Menu</classname> markup xml, CSS files,
icons, etc. These are often shipped as files in <filename class="directory">$datadir/appname</filename>,
or manually included as literal strings in the code.
</para>
<para lang="en">
The <classname>Gio::Resource</classname> API and the <application>glib-compile-resources</application>
program provide a convenient and efficient alternative to this, which has some nice properties. You
maintain the files as normal files, so it's easy to edit them, but during the build the files
are combined into a binary bundle that is linked into the executable. This means that loading
the resource files is efficient (as they are already in memory, shared with other instances) and
simple (no need to check for things like I/O errors or locate the files in the filesystem). It
also makes it easier to create relocatable applications.
</para>
<para lang="en">
Resource bundles are created by the <ulink url="https://developer.gnome.org/gio/stable/glib-compile-resources.html">glib-compile-resources</ulink>
program which takes an xml file that describes the bundle, and a set of files that the xml references.
These are combined into a binary resource bundle.
</para>
<para lang="en"><ulink url="http://developer.gnome.org/glibmm/unstable/classGio_1_1Resource.html">Gio::Resource Reference</ulink></para>
<para lang="en">
An example:
<programlisting lang="en">
<![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<gresources>
  <gresource prefix="/toolbar">
    <file preprocess="xml-stripblanks">toolbar.glade</file>
    <file>rain.png</file>
  </gresource>
</gresources>]]>
</programlisting>
This will create a resource bundle with the files
<itemizedlist>
  <listitem><para lang="en"><filename>/toolbar/toolbar.glade</filename></para></listitem>
  <listitem><para lang="en"><filename>/toolbar/rain.png</filename></para></listitem>
</itemizedlist>
</para>
<para lang="en">
You can then use <application>glib-compile-resources</application> to compile the xml to a binary bundle
that you can load with <methodname>Gio::Resource::create_from_file()</methodname>.
However, it's more common to use the <parameter class="command">--generate-source</parameter>
argument to create a C source file to link directly into your application. E.g.
<screen lang="en">$ glib-compile-resources --target=resources.c --generate-source toolbar.gresource.xml</screen>
</para>
<para lang="en">
Once a <classname>Gio::Resource</classname> has been created and registered all the data
in it can be accessed globally in the process by using API calls like
<methodname>Gio::Resource::open_stream_from_global_resources()</methodname>
to stream the data or <methodname>Gio::Resource::lookup_data_in_global_resources()</methodname>
to get a direct pointer to the data. You can also use URIs like <uri>resource:///toolbar/rain.png</uri>
with <classname>Gio::File</classname> to access the resource data.
</para>
<para lang="en">
Often you don't need a <classname>Gio::Resource</classname> instance,
because resource data can be loaded with methods such as
<methodname>Gdk::Pixbuf::create_from_resource()</methodname>,
<methodname>Gtk::Builder::add_from_resource()</methodname> and
<methodname>Gtk::Image::set_from_resource()</methodname>.
</para>

</sect1>

<sect1 id="sec-menus-examples">
    <title lang="en">Examples</title>

<sect2 id="menu-example-main"><title lang="en">Application Menu and Main Menu example</title>
<para lang="en">
This program contains an application menu, a menubar and a toolbar.
Classes are derived from <classname>Gtk::Application</classname> and
<classname>Gtk::ApplicationWindow</classname>.
</para>

<figure id="figure-menus-mainmenu">
  <title lang="en">App and Main Menu</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/main_menu.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/menus/main_menu/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::ApplicationWindow
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_menu_others();

  void on_menu_choices(const Glib::ustring&amp; parameter);
  void on_menu_choices_other(int parameter);
  void on_menu_toggle();

  //Child widgets:
  Gtk::Box m_Box;

  Glib::RefPtr&lt;Gtk::Builder&gt; m_refBuilder;

  //Two sets of choices:
  Glib::RefPtr&lt;Gio::SimpleAction&gt; m_refChoice;
  Glib::RefPtr&lt;Gio::SimpleAction&gt; m_refChoiceOther;

  Glib::RefPtr&lt;Gio::SimpleAction&gt; m_refToggle;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>exampleapplication.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEAPPLICATION_H
#define GTKMM_EXAMPLEAPPLICATION_H

#include &lt;gtkmm.h&gt;

class ExampleApplication : public Gtk::Application
{
protected:
  ExampleApplication();

public:
  static Glib::RefPtr&lt;ExampleApplication&gt; create();

protected:
  //Overrides of default signal handlers:
  virtual void on_startup();
  virtual void on_activate();

private:
  void create_window();

  void on_window_hide(Gtk::Window* window);
  void on_menu_file_new_generic();
  void on_menu_file_quit();
  void on_menu_help_about();

  Glib::RefPtr&lt;Gtk::Builder&gt; m_refBuilder;
};

#endif /* GTKMM_EXAMPLEAPPLICATION_H */
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: Gtk::ApplicationWindow(),
  m_Box(Gtk::ORIENTATION_VERTICAL)
{
  set_title("Main menu example");
  set_default_size(300, 100);

  // ExampleApplication displays the menubar. Other stuff, such as a toolbar,
  // is put into the box.
  add(m_Box);

  // Create actions for menus and toolbars.
  // We can use add_action() because Gtk::ApplicationWindow derives from Gio::ActionMap.
  // This Action Map uses a "win." prefix for the actions.
  // Therefore, for instance, "win.copy", is used in ExampleApplication::on_startup()
  // to layout the menu. 

  //Edit menu:
  add_action("copy", sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_others));
  add_action("paste", sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_others));
  add_action("something", sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_others));

  //Choices menus, to demonstrate Radio items,
  //using our convenience methods for string and int radio values:
  m_refChoice = add_action_radio_string("choice",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_choices), "a");

  m_refChoiceOther = add_action_radio_integer("choiceother",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_choices_other), 1);

  m_refToggle = add_action_bool("sometoggle",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_toggle), false);

  //Help menu:
  add_action("about", sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_others));

  //Create the toolbar and add it to a container widget:

  m_refBuilder = Gtk::Builder::create();

  Glib::ustring ui_info =
    "&lt;!-- Generated with glade 3.18.3 --&gt;"
    "&lt;interface&gt;"
    "  &lt;requires lib='gtk+' version='3.4'/&gt;"
    "  &lt;object class='GtkToolbar' id='toolbar'&gt;"
    "    &lt;property name='visible'&gt;True&lt;/property&gt;"
    "    &lt;property name='can_focus'&gt;False&lt;/property&gt;"
    "    &lt;child&gt;"
    "      &lt;object class='GtkToolButton' id='toolbutton_new'&gt;"
    "        &lt;property name='visible'&gt;True&lt;/property&gt;"
    "        &lt;property name='can_focus'&gt;False&lt;/property&gt;"
    "        &lt;property name='tooltip_text' translatable='yes'&gt;New Standard&lt;/property&gt;"
    "        &lt;property name='action_name'&gt;app.newstandard&lt;/property&gt;"
    "        &lt;property name='icon_name'&gt;document-new&lt;/property&gt;"
    "      &lt;/object&gt;"
    "      &lt;packing&gt;"
    "        &lt;property name='expand'&gt;False&lt;/property&gt;"
    "        &lt;property name='homogeneous'&gt;True&lt;/property&gt;"
    "      &lt;/packing&gt;"
    "    &lt;/child&gt;"
    "    &lt;child&gt;"
    "      &lt;object class='GtkToolButton' id='toolbutton_quit'&gt;"
    "        &lt;property name='visible'&gt;True&lt;/property&gt;"
    "        &lt;property name='can_focus'&gt;False&lt;/property&gt;"
    "        &lt;property name='tooltip_text' translatable='yes'&gt;Quit&lt;/property&gt;"
    "        &lt;property name='action_name'&gt;app.quit&lt;/property&gt;"
    "        &lt;property name='icon_name'&gt;application-exit&lt;/property&gt;"
    "      &lt;/object&gt;"
    "      &lt;packing&gt;"
    "        &lt;property name='expand'&gt;False&lt;/property&gt;"
    "        &lt;property name='homogeneous'&gt;True&lt;/property&gt;"
    "      &lt;/packing&gt;"
    "    &lt;/child&gt;"
    "  &lt;/object&gt;"
    "&lt;/interface&gt;";

  try
  {
    m_refBuilder-&gt;add_from_string(ui_info);
  }
  catch (const Glib::Error&amp; ex)
  {
    std::cerr &lt;&lt; "Building toolbar failed: " &lt;&lt;  ex.what();
  }

  Gtk::Toolbar* toolbar = 0;
  m_refBuilder-&gt;get_widget("toolbar", toolbar);
  if (!toolbar)
    g_warning("GtkToolbar not found");
  else
    m_Box.pack_start(*toolbar, Gtk::PACK_SHRINK);
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_menu_others()
{
  std::cout &lt;&lt; "A menu item was selected." &lt;&lt; std::endl;
}

void ExampleWindow::on_menu_choices(const Glib::ustring&amp; parameter)
{
  //The radio action's state does not change automatically:
  m_refChoice-&gt;change_state(parameter);

  Glib::ustring message;
  if (parameter == "a")
    message = "Choice a was selected.";
  else
    message = "Choice b was selected.";

  std::cout &lt;&lt; message &lt;&lt; std::endl;
}

void ExampleWindow::on_menu_choices_other(int parameter)
{
  //The radio action's state does not change automatically:
  m_refChoiceOther-&gt;change_state(parameter);

  Glib::ustring message;
  if (parameter == 1)
    message = "Choice 1 was selected.";
  else
    message = "Choice 2 was selected.";

  std::cout &lt;&lt; message &lt;&lt; std::endl;
}

void ExampleWindow::on_menu_toggle()
{
  bool active = false;
  m_refToggle-&gt;get_state(active);

  //The toggle action's state does not change automatically:
  active = !active;
  m_refToggle-&gt;change_state(active);

  Glib::ustring message;
  if (active)
    message = "Toggle is active.";
  else
    message = "Toggle is not active.";

  std::cout &lt;&lt; message &lt;&lt; std::endl;
}
</programlisting>
<para lang="en">File: <filename>exampleapplication.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "exampleapplication.h"
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleApplication::ExampleApplication()
: Gtk::Application("org.gtkmm.example.main_menu")
{
  Glib::set_application_name("Main Menu Example");
}

Glib::RefPtr&lt;ExampleApplication&gt; ExampleApplication::create()
{
  return Glib::RefPtr&lt;ExampleApplication&gt;(new ExampleApplication());
}

void ExampleApplication::on_startup()
{
  //Call the base class's implementation:
  Gtk::Application::on_startup();

  //Create actions for menus and toolbars.
  //We can use add_action() because Gtk::Application derives from Gio::ActionMap.

  //File|New sub menu:
  add_action("newstandard",
    sigc::mem_fun(*this, &amp;ExampleApplication::on_menu_file_new_generic));

  add_action("newfoo",
    sigc::mem_fun(*this, &amp;ExampleApplication::on_menu_file_new_generic));

  add_action("newgoo",
    sigc::mem_fun(*this, &amp;ExampleApplication::on_menu_file_new_generic));

  //File menu:
  add_action("quit", sigc::mem_fun(*this, &amp;ExampleApplication::on_menu_file_quit));

  //Help menu:
  add_action("about", sigc::mem_fun(*this, &amp;ExampleApplication::on_menu_help_about));

  m_refBuilder = Gtk::Builder::create();

  //Layout the actions in a menubar and an application menu:
  Glib::ustring ui_info =
    "&lt;interface&gt;"
    "  &lt;!-- menubar --&gt;"
    "  &lt;menu id='menu-example'&gt;"
    "    &lt;submenu&gt;"
    "      &lt;attribute name='label' translatable='yes'&gt;_File&lt;/attribute&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;New _Standard&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;app.newstandard&lt;/attribute&gt;"
    "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;n&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;New _Foo&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;app.newfoo&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;New _Goo&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;app.newgoo&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;_Quit&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;app.quit&lt;/attribute&gt;"
    "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;q&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "    &lt;/submenu&gt;"
    "    &lt;submenu&gt;"
    "      &lt;attribute name='label' translatable='yes'&gt;_Edit&lt;/attribute&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;_Copy&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;win.copy&lt;/attribute&gt;"
    "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;c&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;_Paste&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;win.paste&lt;/attribute&gt;"
    "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;v&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;_Something&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;win.something&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "    &lt;/submenu&gt;"
    "    &lt;submenu&gt;"
    "      &lt;attribute name='label' translatable='yes'&gt;_Choices&lt;/attribute&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;Choice _A&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;win.choice&lt;/attribute&gt;"
    "          &lt;attribute name='target'&gt;a&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;Choice _B&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;win.choice&lt;/attribute&gt;"
    "          &lt;attribute name='target'&gt;b&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "    &lt;/submenu&gt;"
    "    &lt;submenu&gt;"
    "      &lt;attribute name='label' translatable='yes'&gt;_Other Choices&lt;/attribute&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;Choice 1&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;win.choiceother&lt;/attribute&gt;"
    "          &lt;attribute name='target' type='i'&gt;1&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;Choice 2&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;win.choiceother&lt;/attribute&gt;"
    "          &lt;attribute name='target' type='i'&gt;2&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;Some Toggle&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;win.sometoggle&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "    &lt;/submenu&gt;"
    "    &lt;submenu&gt;"
    "      &lt;attribute name='label' translatable='yes'&gt;_Help&lt;/attribute&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;_About&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;win.about&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "    &lt;/submenu&gt;"
    "  &lt;/menu&gt;"
    ""
    "  &lt;!-- application menu --&gt;"
    "  &lt;menu id='appmenu'&gt;"
    "    &lt;submenu&gt;"
    "      &lt;attribute name='label' translatable='yes'&gt;_File&lt;/attribute&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;New _Standard&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;app.newstandard&lt;/attribute&gt;"
    "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;n&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;New _Foo&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;app.newfoo&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;New _Goo&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;app.newgoo&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;_Quit&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;app.quit&lt;/attribute&gt;"
    "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;q&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "    &lt;/submenu&gt;"
    "    &lt;submenu&gt;"
    "      &lt;attribute name='label' translatable='yes'&gt;_Help&lt;/attribute&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;_About&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;app.about&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "    &lt;/submenu&gt;"
    "  &lt;/menu&gt;"
    "&lt;/interface&gt;";

  try
  {
    m_refBuilder-&gt;add_from_string(ui_info);
  }
  catch (const Glib::Error&amp; ex)
  {
    std::cerr &lt;&lt; "Building menus failed: " &lt;&lt; ex.what();
  }

  //Get the menubar and the app menu, and add them to the application:
  Glib::RefPtr&lt;Glib::Object&gt; object = m_refBuilder-&gt;get_object("menu-example");
  Glib::RefPtr&lt;Gio::Menu&gt; gmenu = Glib::RefPtr&lt;Gio::Menu&gt;::cast_dynamic(object);
  object = m_refBuilder-&gt;get_object("appmenu");
  Glib::RefPtr&lt;Gio::Menu&gt; appMenu = Glib::RefPtr&lt;Gio::Menu&gt;::cast_dynamic(object);
  if (!(gmenu &amp;&amp; appMenu)) {
    g_warning("GMenu or AppMenu not found");
  }
  else
  {
    set_app_menu(appMenu);
    set_menubar(gmenu);
  }
}

void ExampleApplication::on_activate()
{
  //std::cout &lt;&lt; "debug1: " &lt;&lt; G_STRFUNC &lt;&lt; std::endl;
  // The application has been started, so let's show a window.
  // A real application might want to reuse this window in on_open(),
  // when asked to open a file, if no changes have been made yet.
  create_window();
}

void ExampleApplication::create_window()
{
  ExampleWindow* win = new ExampleWindow();

  //Make sure that the application runs for as long this window is still open:
  add_window(*win);

  //Delete the window when it is hidden.
  //That's enough for this simple example.
  win-&gt;signal_hide().connect(sigc::bind&lt;Gtk::Window*&gt;(
    sigc::mem_fun(*this, &amp;ExampleApplication::on_window_hide), win));

  win-&gt;show_all();
}

void ExampleApplication::on_window_hide(Gtk::Window* window)
{
  delete window;
}

void ExampleApplication::on_menu_file_new_generic()
{
  std::cout &lt;&lt; "A File|New menu item was selected." &lt;&lt; std::endl;
}

void ExampleApplication::on_menu_file_quit()
{
  std::cout &lt;&lt; G_STRFUNC &lt;&lt; std::endl;
  quit(); // Not really necessary, when Gtk::Widget::hide() is called.

  // Gio::Application::quit() will make Gio::Application::run() return,
  // but it's a crude way of ending the program. The window is not removed
  // from the application. Neither the window's nor the application's
  // destructors will be called, because there will be remaining reference
  // counts in both of them. If we want the destructors to be called, we
  // must remove the window from the application. One way of doing this
  // is to hide the window.
  std::vector&lt;Gtk::Window*&gt; windows = get_windows();
  if (windows.size() &gt; 0)
    windows[0]-&gt;hide(); // In this simple case, we know there is only one window.
}

void ExampleApplication::on_menu_help_about()
{
  std::cout &lt;&lt; "App|Help|About was selected." &lt;&lt; std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "exampleapplication.h"

int main(int argc, char* argv[])
{
  Glib::RefPtr&lt;ExampleApplication&gt; application = ExampleApplication::create();

  // Start the application, showing the initial window,
  // and opening extra windows for any files that it is asked to open,
  // for instance as a command-line parameter.
  // run() will return when the last window has been closed by the user.
  const int status = application-&gt;run(argc, argv);
  return status;
}
</programlisting>
<!-- end inserted example code -->

</sect2>

<sect2 id="menu-example-main2"><title>Exemplo de menu principal</title>
<para lang="en">
This program contains a menubar and a toolbar.
A class is derived from <classname>Gtk::Window</classname>.
</para>

<figure id="figure-menus-mainmenu2">
  <title>Menu principal</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/menus_and_toolbars.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/menus_and_toolbars?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow(const Glib::RefPtr&lt;Gtk::Application&gt;&amp; app);
  virtual ~ExampleWindow();

private:
  //Signal handlers:
  void on_action_file_new();
  void on_action_file_quit();
  void on_action_others();
  void on_action_toggle();

  //Child widgets:
  Gtk::Box m_Box;

  Glib::RefPtr&lt;Gtk::Builder&gt; m_refBuilder;
  Glib::RefPtr&lt;Gio::SimpleActionGroup&gt; m_refActionGroup;
  Glib::RefPtr&lt;Gio::SimpleAction&gt; m_refActionRain;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm.h&gt;
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow(const Glib::RefPtr&lt;Gtk::Application&gt;&amp; app)
: m_Box(Gtk::ORIENTATION_VERTICAL)
{
  set_title("main_menu example");
  set_default_size(200, 200);

  add(m_Box); //We can put a MenuBar at the top of the box and other stuff below it.

  //Define the actions:
  m_refActionGroup = Gio::SimpleActionGroup::create();

  m_refActionGroup-&gt;add_action("new",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_new) );
  m_refActionGroup-&gt;add_action("open",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_action_others) );


  m_refActionRain = m_refActionGroup-&gt;add_action_bool("rain",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_action_toggle),
    false);

  m_refActionGroup-&gt;add_action("quit",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_action_file_quit) );

  m_refActionGroup-&gt;add_action("cut",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_action_others) );
  m_refActionGroup-&gt;add_action("copy",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_action_others) );
  m_refActionGroup-&gt;add_action("paste",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_action_others) );

  insert_action_group("example", m_refActionGroup);

  //Define how the actions are presented in the menus and toolbars:
  Glib::RefPtr&lt;Gtk::Builder&gt; m_refBuilder = Gtk::Builder::create();

  //Layout the actions in a menubar and toolbar:
  const char* ui_info =
    "&lt;interface&gt;"
    "  &lt;menu id='menubar'&gt;"
    "    &lt;submenu&gt;"
    "      &lt;attribute name='label' translatable='yes'&gt;_File&lt;/attribute&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;_New&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;example.new&lt;/attribute&gt;"
    "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;n&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;_Open&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;example.open&lt;/attribute&gt;"
    "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;o&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;Rain&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;example.rain&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;_Quit&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;example.quit&lt;/attribute&gt;"
    "          &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;q&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "    &lt;/submenu&gt;"
    "    &lt;submenu&gt;"
    "      &lt;attribute name='label' translatable='yes'&gt;_Edit&lt;/attribute&gt;"
    "      &lt;item&gt;"
    "        &lt;attribute name='label' translatable='yes'&gt;_Cut&lt;/attribute&gt;"
    "        &lt;attribute name='action'&gt;example.cut&lt;/attribute&gt;"
    "        &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;x&lt;/attribute&gt;"
    "      &lt;/item&gt;"
    "      &lt;item&gt;"
    "        &lt;attribute name='label' translatable='yes'&gt;_Copy&lt;/attribute&gt;"
    "        &lt;attribute name='action'&gt;example.copy&lt;/attribute&gt;"
    "        &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;c&lt;/attribute&gt;"
    "      &lt;/item&gt;"
    "      &lt;item&gt;"
    "        &lt;attribute name='label' translatable='yes'&gt;_Paste&lt;/attribute&gt;"
    "        &lt;attribute name='action'&gt;example.paste&lt;/attribute&gt;"
    "        &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;v&lt;/attribute&gt;"
    "      &lt;/item&gt;"
    "    &lt;/submenu&gt;"
    "  &lt;/menu&gt;"
    "&lt;/interface&gt;";

  // When the menubar is a child of a Gtk::Window, keyboard accelerators are not
  // automatically fetched from the Gio::Menu.
  // See the examples/book/menus/main_menu example for an alternative way of
  // adding the menubar when using Gtk::ApplicationWindow.
  // Gtk::Application::set_accel_for_action() is new in gtkmm 3.11.9.
  app-&gt;set_accel_for_action("example.new", "&lt;Primary&gt;n");
  app-&gt;set_accel_for_action("example.open", "&lt;Primary&gt;o");
  app-&gt;set_accel_for_action("example.quit", "&lt;Primary&gt;q");
  app-&gt;set_accel_for_action("example.cut", "&lt;Primary&gt;x");
  app-&gt;set_accel_for_action("example.copy", "&lt;Primary&gt;c");
  app-&gt;set_accel_for_action("example.paste", "&lt;Primary&gt;v");

  try
  {
    m_refBuilder-&gt;add_from_string(ui_info);
    m_refBuilder-&gt;add_from_resource("/toolbar/toolbar.glade");
  }
  catch(const Glib::Error&amp; ex)
  {
    std::cerr &lt;&lt; "Building menus and toolbar failed: " &lt;&lt;  ex.what();
  }

  //Get the menubar:
  Glib::RefPtr&lt;Glib::Object&gt; object = m_refBuilder-&gt;get_object("menubar");
  Glib::RefPtr&lt;Gio::Menu&gt; gmenu = Glib::RefPtr&lt;Gio::Menu&gt;::cast_dynamic(object);
  if (!gmenu)
    g_warning("GMenu not found");
  else
  {
    Gtk::MenuBar* pMenuBar = Gtk::manage(new Gtk::MenuBar(gmenu));

    //Add the MenuBar to the window:
    m_Box.pack_start(*pMenuBar, Gtk::PACK_SHRINK);
  }

  //Get the toolbar and add it to a container widget:
  Gtk::Toolbar* toolbar = 0;
  m_refBuilder-&gt;get_widget("toolbar", toolbar);
  if (!toolbar)
    g_warning("GtkToolbar not found");
  else
    m_Box.pack_start(*toolbar, Gtk::PACK_SHRINK);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_action_file_quit()
{
  hide(); //Closes the main window to stop the app-&gt;run().
}

void ExampleWindow::on_action_file_new()
{
   std::cout &lt;&lt; "A File|New menu item was selected." &lt;&lt; std::endl;
}

void ExampleWindow::on_action_others()
{
  std::cout &lt;&lt; "A menu item was selected." &lt;&lt; std::endl;
}

void ExampleWindow::on_action_toggle()
{
  std::cout &lt;&lt; "The toggle menu item was selected." &lt;&lt; std::endl;

  bool active = false;
  m_refActionRain-&gt;get_state(active);

  //The toggle action's state does not change automatically:
  active = !active;
  m_refActionRain-&gt;change_state(active);

  Glib::ustring message;
  if(active)
    message = "Toggle is active.";
  else
    message = "Toggle is not active";

  std::cout &lt;&lt; message &lt;&lt; std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;gtkmm.h&gt;
#include "examplewindow.h"

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window(app);

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<para lang="en">File: <filename>toolbar.gresource.xml</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;gresources&gt;
  &lt;gresource prefix="/toolbar"&gt;
    &lt;file preprocess="xml-stripblanks"&gt;toolbar.glade&lt;/file&gt;
    &lt;file&gt;rain.png&lt;/file&gt;
  &lt;/gresource&gt;
&lt;/gresources&gt;
</programlisting>
<!-- end inserted example code -->

</sect2>

<sect2 id="menu-example-popup"><title>Exemplo de menu popup</title>

<figure id="figure-menus-popup">
  <title>Menu popup</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/menu_popup.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/menus/popup/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  virtual bool on_button_press_event(GdkEventButton* event);
  void on_menu_file_popup_generic();

  //Child widgets:
  Gtk::Box m_Box;
  Gtk::EventBox m_EventBox;
  Gtk::Label m_Label;

  Glib::RefPtr&lt;Gtk::Builder&gt; m_refBuilder;

  Gtk::Menu* m_pMenuPopup;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_Box(Gtk::ORIENTATION_VERTICAL),
  m_Label("Right-click to see the popup menu."),
  m_pMenuPopup(0)
{
  set_title("popup example");
  set_default_size(200, 200);

  add(m_Box);

  //Add an event box that can catch button_press events:
  m_Box.pack_start(m_EventBox);
  m_EventBox.signal_button_press_event().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_press_event) );

  m_EventBox.add(m_Label);

  //Create actions:

  //Fill menu:

  Glib::RefPtr&lt;Gio::SimpleActionGroup&gt; refActionGroup =
    Gio::SimpleActionGroup::create();

  //File|New sub menu:
  //These menu actions would normally already exist for a main menu, because a
  //context menu should not normally contain menu items that are only available
  //via a context menu.

  refActionGroup-&gt;add_action("edit",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_file_popup_generic));

  refActionGroup-&gt;add_action("process", //TODO: How to specify "&lt;control&gt;P" as an accelerator. 
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_file_popup_generic));

  refActionGroup-&gt;add_action("remove",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_file_popup_generic));

  insert_action_group("examplepopup", refActionGroup);


  m_refBuilder = Gtk::Builder::create();

  //Layout the actions in a menubar and toolbar:
  Glib::ustring ui_info =
    "&lt;interface&gt;"
    "  &lt;menu id='menu-examplepopup'&gt;"
    "    &lt;section&gt;"
    "      &lt;item&gt;"
    "        &lt;attribute name='label' translatable='yes'&gt;Edit&lt;/attribute&gt;"
    "        &lt;attribute name='action'&gt;examplepopup.edit&lt;/attribute&gt;"
    "      &lt;/item&gt;"
    "      &lt;item&gt;"
    "        &lt;attribute name='label' translatable='yes'&gt;Process&lt;/attribute&gt;"
    "        &lt;attribute name='action'&gt;examplepopup.process&lt;/attribute&gt;"
    "      &lt;/item&gt;"
    "      &lt;item&gt;"
    "        &lt;attribute name='label' translatable='yes'&gt;Remove&lt;/attribute&gt;"
    "        &lt;attribute name='action'&gt;examplepopup.remove&lt;/attribute&gt;"
    "      &lt;/item&gt;"
    "    &lt;/section&gt;"
    "  &lt;/menu&gt;"
    "&lt;/interface&gt;";

  try
  {
    m_refBuilder-&gt;add_from_string(ui_info);
  }
  catch(const Glib::Error&amp; ex)
  {
    std::cerr &lt;&lt; "building menus failed: " &lt;&lt;  ex.what();
  }

  //Get the menu:
  Glib::RefPtr&lt;Glib::Object&gt; object =
    m_refBuilder-&gt;get_object("menu-examplepopup");
  Glib::RefPtr&lt;Gio::Menu&gt; gmenu =
    Glib::RefPtr&lt;Gio::Menu&gt;::cast_dynamic(object);
  if(!gmenu)
    g_warning("GMenu not found");

  m_pMenuPopup = new Gtk::Menu(gmenu);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_menu_file_popup_generic()
{
   std::cout &lt;&lt; "A popup menu item was selected." &lt;&lt; std::endl;
}

bool ExampleWindow::on_button_press_event(GdkEventButton* event)
{
  if( (event-&gt;type == GDK_BUTTON_PRESS) &amp;&amp; (event-&gt;button == 3) )
  {
    if(!m_pMenuPopup-&gt;get_attach_widget())
    {
      m_pMenuPopup-&gt;attach_to_widget(*this);
    }

    if(m_pMenuPopup)
      m_pMenuPopup-&gt;popup(event-&gt;button, event-&gt;time);


    return true; //It has been handled.
  }
  else
    return false;
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

</sect1>

</chapter>

<chapter id="chapter-toolpalette">
<title lang="en">ToolPalette</title>

<para lang="en">A <classname>ToolPalette</classname> is similar to a <classname>Toolbar</classname> but can contain a grid of items, categorized into groups. The user may hide or expand each group. As in a toolbar, the items may be displayed as only icons, as only text, or as icons with text.
</para>
<para lang="en">The <classname>ToolPalette</classname>'s items might be dragged or simply activated. For instance, the user might drag objects to a canvas to create new items there. Or the user might click an item to activate a certain brush size in a drawing application.</para>
<para lang="en"><classname>ToolItemGroup</classname>s should be added to the tool palette via the base class's <function>Gtk::Container::add()</function> method, for instance like so:
</para>
<para>
<programlisting lang="en">
Gtk::ToolItemGroup* group_brushes =
  Gtk::manage(new Gtk::ToolItemGroup("Brushes"));
m_ToolPalette.add(*group_brushes);
</programlisting>
</para>
<para lang="en">
<classname>Gtk::ToolItem</classname>s can then be added to the group. For instance, like so:
</para>
<para>
<programlisting lang="en">
Gtk::ToolButton* button = Gtk::manage(new Gtk::ToolButton(icon, "Big"));
button-&gt;set_tooltip_text("Big Brush);
group_brushes-&gt;insert(*button);
</programlisting>
</para>
<para lang="en">You might then handle the <classname>ToolButton</classname>'s <literal>clicked</literal> signal. Alternatively, you could allow the item to be dragged to another widget, by calling <methodname>Gtk::ToolPalette::add_drag_dest()</methodname> and then using <methodname>Gtk::ToolPalette::get_drag_item()</methodname> in the other widget's <literal>drag_data_received</literal> signal handler.</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToolPalette.html">ToolPalette Reference</ulink></para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToolItemGroup.html">ToolItemGroup Reference</ulink></para>
<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ToolItem.html">ToolItem Reference</ulink></para>

<sect1 id="toolpallete-dranganddrop">
<title>Arrastar e soltar</title>
<para lang="en">Call <methodname>add_drag_dest()</methodname> to allow items or groups to be dragged from the tool palette to a particular destination widget. You can then use <methodname>get_drag_item()</methodname> to discover which ToolItem or ToolItemGroup is being dragged. You can use <literal>dynamic_cast</literal> to discover whether it is an item or a group. For instance, you might use this in your <literal>drag_data_received</literal> signal handler, to add a dropped item, or to show a suitable icon while dragging.</para>
<para lang="en">See the <link linkend="chapter-draganddrop">Drag and Drop</link> chapter for general advice about Drag and Drop with gtkmm.</para>
</sect1>

<sect1 id="toolpalette-example"><title lang="en">ToolPalette Example</title>

<para lang="en">This example adds a <classname>ToolPalette</classname> and a <classname>DrawingArea</classname> to a window and allows the user to drag icons from the tool palette to the drawing area. The tool palette contains several groups of items. The combo boxes allow the user to change the style and orientation of the tool palette.</para>

<figure id="figure-toolpalette">
  <title lang="en">ToolPalette</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/toolpalette.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/toolpalette/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>canvas.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_CANVAS_H
#define GTKMM_EXAMPLE_CANVAS_H

#include &lt;gtkmm.h&gt;

// This little canvas class is only here 
// because gtkmm does not have a canvas class yet.
// Applications should probably use GooCanvas::Canvas (goocanvasmm) instead.
class Canvas : public Gtk::DrawingArea
{
public:
  Canvas();
  virtual ~Canvas();

private:

  class CanvasItem
  {
  public:
    CanvasItem(Gtk::Widget* canvas, Gtk::ToolButton* button, double x, double y)
    {
      Glib::ustring icon_name(button-&gt;get_icon_name());
      if (icon_name.empty())
        icon_name = button-&gt;get_label();

      Glib::RefPtr&lt;Gtk::IconTheme&gt; icon_theme = Gtk::IconTheme::get_for_screen(canvas-&gt;get_screen());
      int width = 0;
      int height = 0; //ignored
      Gtk::IconSize::lookup(Gtk::ICON_SIZE_DIALOG, width, height);
      this-&gt;pixbuf = icon_theme-&gt;load_icon(icon_name, width, Gtk::ICON_LOOKUP_GENERIC_FALLBACK);
      this-&gt;x = x;
      this-&gt;y = y;
    }

    Glib::RefPtr&lt;Gdk::Pixbuf&gt; pixbuf;
    double x, y;
  };

  void item_draw(const CanvasItem *item,
    const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr,
    bool preview);

  virtual bool on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr);
  virtual void on_drag_data_received(const Glib::RefPtr&lt;Gdk::DragContext&gt;&amp; context, 
    int x, int y, const Gtk::SelectionData&amp; selection_data, guint info, guint time);
  virtual bool on_drag_motion(const Glib::RefPtr&lt;Gdk::DragContext&gt;&amp; context, int x, int y, guint time);
  virtual bool on_drag_drop(const Glib::RefPtr&lt;Gdk::DragContext&gt;&amp; context, int x, int y, guint time);
  virtual void on_drag_leave(const Glib::RefPtr&lt;Gdk::DragContext&gt;&amp; context, guint time);

  bool m_drag_data_requested_for_drop; //So we know what to do in on_drag_data_received().
  CanvasItem* m_drop_item;
  
  typedef std::vector&lt;CanvasItem*&gt; type_vec_items;
  type_vec_items m_canvas_items;
};

#endif //GTKMM_EXAMPLE_CANVAS_H
</programlisting>
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;
#include "canvas.h"

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

private:

  void load_icon_items();
  void load_toggle_items();
  void load_special_items();

  //Signal handlers:
  void on_combo_orientation_changed();
  void on_combo_style_changed();

  //Tree model columns:
  class ModelColumnsOrientation : public Gtk::TreeModel::ColumnRecord
  {
  public:

    ModelColumnsOrientation()
    { add(m_col_value); add(m_col_name); }

    Gtk::TreeModelColumn&lt;Gtk::Orientation&gt; m_col_value;
    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
  };

  ModelColumnsOrientation m_ColumnsOrientation;

  //Tree model columns:
  class ModelColumnsStyle : public Gtk::TreeModel::ColumnRecord
  {
  public:

    ModelColumnsStyle()
    { add(m_col_value); add(m_col_name); }

    Gtk::TreeModelColumn&lt;int&gt; m_col_value; //We use int to also allow -1
    Gtk::TreeModelColumn&lt;Glib::ustring&gt; m_col_name;
  };

  ModelColumnsStyle m_ColumnsStyle;


  //Child widgets:
  Gtk::Box m_VBox;
  Gtk::Box m_HBox;
  Gtk::ComboBox m_ComboOrientation;
  Glib::RefPtr&lt;Gtk::ListStore&gt; m_refTreeModelOrientation;
  Gtk::ComboBox m_ComboStyle;
  Glib::RefPtr&lt;Gtk::ListStore&gt; m_refTreeModelStyle;
  Gtk::ToolPalette m_ToolPalette;
  Gtk::ScrolledWindow m_ScrolledWindowPalette;
  Gtk::ScrolledWindow m_ScrolledWindowCanvas;
  Canvas m_Canvas;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"


void ExampleWindow::load_icon_items()
{
  Glib::RefPtr&lt;Gtk::IconTheme&gt; icon_theme = Gtk::IconTheme::get_for_screen(get_screen());

  typedef std::vector&lt;Glib::ustring&gt; type_stringvec;
  type_stringvec icon_names = icon_theme-&gt;list_icons();

  // Obtain the names of all contexts, and the icon names per context.
  type_stringvec contexts = icon_theme-&gt;list_contexts();
  std::sort(contexts.begin(), contexts.end());

  int requested_icon_size = 0;
  int requested_icon_height = 0; //ignored
  Gtk::IconSize::lookup(Gtk::ICON_SIZE_BUTTON, requested_icon_size, requested_icon_height);
  const guint max_icons_per_group = 10;

  for (type_stringvec::const_iterator iter = contexts.begin(); iter != contexts.end(); ++iter)
  {
    const Glib::ustring context_name = *iter;
    Gtk::ToolItemGroup* group =
      Gtk::manage(new Gtk::ToolItemGroup(context_name));
    m_ToolPalette.add(*group);

    // Iterate through the icon names, populating the ToolItemGroup as appropriate.
    type_stringvec icon_names = icon_theme-&gt;list_icons(context_name);
    std::sort(icon_names.begin(), icon_names.end());
    guint icons_count = 0;
    for (type_stringvec::const_iterator iconiter = icon_names.begin(); iconiter != icon_names.end(); ++iconiter)
    {
      const Glib::ustring icon_name = *iconiter;
      Glib::RefPtr&lt;Gdk::Pixbuf&gt; pixbuf;
      try
      {
        pixbuf = icon_theme-&gt;load_icon(icon_name, requested_icon_size, Gtk::ICON_LOOKUP_GENERIC_FALLBACK);
      }
      catch (const Gtk::IconThemeError&amp; /* ex */)
      {
        // Gtk::IconTheme::list_icons() may return some names of icons
        // that can't be loaded.
        continue;
      }

      // Skip large icons, just to make the ToolPalette look better.
      if (pixbuf-&gt;get_width() &gt; 2*requested_icon_size ||
          pixbuf-&gt;get_height() &gt; 2*requested_icon_size)
        continue;

      Gtk::Image* image = Gtk::manage(new Gtk::Image(pixbuf));
      Gtk::ToolButton* button = Gtk::manage(new Gtk::ToolButton(*image, icon_name));
      button-&gt;set_tooltip_text(icon_name);
      button-&gt;set_is_important();
      group-&gt;insert(*button);

      // Prevent us having an insane number of icons:
      ++icons_count;
      if(icons_count &gt;= max_icons_per_group)
        break;
    }
  }
}


void ExampleWindow::load_toggle_items()
{
  Gtk::ToolItemGroup* group = 
    Gtk::manage(new Gtk::ToolItemGroup("Radio Item"));
  m_ToolPalette.add(*group);

  Gtk::RadioToolButton::Group radio_group;

  for(int i = 1; i &lt;= 10; ++i)
  {
    const Glib::ustring label = Glib::ustring::compose("#%1", i);
    Gtk::RadioToolButton* button = Gtk::manage(new Gtk::RadioToolButton());
    button-&gt;set_group(radio_group);
    button-&gt;set_label(label);
   
    group-&gt;insert(*button);
  }
}


static Gtk::ToolItem* create_entry_item(const Glib::ustring&amp; text)
{
  Gtk::Entry* entry = Gtk::manage(new Gtk::Entry());
  entry-&gt;set_text(text);
  entry-&gt;set_width_chars(5);

  Gtk::ToolItem* item = Gtk::manage(new Gtk::ToolItem());
  item-&gt;add(*entry);

  return item;
}

void ExampleWindow::load_special_items()
{
  Gtk::ToolItemGroup* group = Gtk::manage(new Gtk::ToolItemGroup());

  Gtk::Button *label_button = Gtk::manage(new Gtk::Button("Advanced Features"));
  label_button-&gt;show();
  group-&gt;set_label_widget(*label_button);
  m_ToolPalette.add(*group);

  Gtk::ToolItem* item = create_entry_item ("homogeneous=false");
  group-&gt;insert(*item);
  //TODO: Add Gtk::Container::set_child_property().
  gtk_container_child_set (GTK_CONTAINER (group-&gt;gobj()), GTK_WIDGET (item-&gt;gobj()),
                           "homogeneous", FALSE, NULL);

  item = create_entry_item ("homogeneous=FALSE, expand=TRUE");
  group-&gt;insert(*item);
  gtk_container_child_set (GTK_CONTAINER (group-&gt;gobj()), GTK_WIDGET (item-&gt;gobj()),
                           "homogeneous", FALSE, "expand", TRUE,
                           NULL);

  item = create_entry_item ("homogeneous=FALSE, expand=TRUE, fill=FALSE");
  group-&gt;insert(*item);
  gtk_container_child_set (GTK_CONTAINER (group-&gt;gobj()), GTK_WIDGET (item-&gt;gobj()),
                           "homogeneous", FALSE, "expand", TRUE,
                           "fill", FALSE, NULL);

  item = create_entry_item ("homogeneous=FALSE, expand=TRUE, new-row=TRUE");
  group-&gt;insert(*item);
  gtk_container_child_set (GTK_CONTAINER (group-&gt;gobj()), GTK_WIDGET (item-&gt;gobj()),
                           "homogeneous", FALSE, "expand", TRUE,
                           "new-row", TRUE, NULL);

  Gtk::ToolButton *button = Gtk::manage(new Gtk::ToolButton());
  button-&gt;set_icon_name("go-up");
  button-&gt;set_tooltip_text("Show on vertical palettes only");
  group-&gt;insert(*button);
  button-&gt;set_visible_horizontal(false);

  button = Gtk::manage(new Gtk::ToolButton());
  button-&gt;set_icon_name("go-next");
  button-&gt;set_tooltip_text("Show on horizontal palettes only");
  group-&gt;insert(*button);
  button-&gt;set_visible_vertical(false);

  button = Gtk::manage(new Gtk::ToolButton());
  button-&gt;set_icon_name("edit-delete");
  button-&gt;set_tooltip_text("Do not show at all");
  button-&gt;set_no_show_all();
  group-&gt;insert(*button);
  button-&gt;set_visible_vertical(false);

  button = Gtk::manage(new Gtk::ToolButton());
  button-&gt;set_icon_name("view-fullscreen");
  button-&gt;set_tooltip_text("Expanded this item");
  group-&gt;insert(*button);
  gtk_container_child_set (GTK_CONTAINER (group-&gt;gobj()), GTK_WIDGET (button-&gt;gobj()),
                           "homogeneous", FALSE,
                           "expand", TRUE,
                           NULL);

  button = Gtk::manage(new Gtk::ToolButton());
  button-&gt;set_icon_name("help-contents");
  button-&gt;set_tooltip_text("A regular item");
  group-&gt;insert(*button);
}

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL, 6),
  m_HBox(Gtk::ORIENTATION_HORIZONTAL, 6)
{
  set_title("Gtk::ToolPalette example");
  set_size_request(600, 600);
  set_border_width(6);

  add(m_VBox);

  //The Orientation ComboBox:
  m_refTreeModelOrientation = Gtk::ListStore::create(m_ColumnsOrientation);
  Gtk::TreeModel::Row row = *(m_refTreeModelOrientation-&gt;append());
  row[m_ColumnsOrientation.m_col_value] = Gtk::ORIENTATION_HORIZONTAL;
  row[m_ColumnsOrientation.m_col_name] = "Horizontal";\
  row = *(m_refTreeModelOrientation-&gt;append());
  row[m_ColumnsOrientation.m_col_value] = Gtk::ORIENTATION_VERTICAL;
  row[m_ColumnsOrientation.m_col_name] = "Vertical";
  m_ComboOrientation.set_model(m_refTreeModelOrientation);
  m_VBox.pack_start(m_ComboOrientation, Gtk::PACK_SHRINK);
  m_ComboOrientation.pack_start(m_ColumnsOrientation.m_col_name);
  m_ComboOrientation.signal_changed().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::on_combo_orientation_changed) );
  m_ComboOrientation.set_active(row);

  //The Style ComboBox:
  m_refTreeModelStyle = Gtk::ListStore::create(m_ColumnsStyle);
  row = *(m_refTreeModelStyle-&gt;append());
  row[m_ColumnsStyle.m_col_value] = Gtk::TOOLBAR_TEXT;
  row[m_ColumnsStyle.m_col_name] = "Text";\
  row = *(m_refTreeModelStyle-&gt;append());
  row[m_ColumnsStyle.m_col_value] = Gtk::TOOLBAR_BOTH;
  row[m_ColumnsStyle.m_col_name] = "Both";
  row = *(m_refTreeModelStyle-&gt;append());
  row[m_ColumnsStyle.m_col_value] = Gtk::TOOLBAR_BOTH_HORIZ;
  row[m_ColumnsStyle.m_col_name] = "Both: Horizontal";
  row = *(m_refTreeModelStyle-&gt;append());
  row[m_ColumnsStyle.m_col_value] = Gtk::TOOLBAR_ICONS;
  row[m_ColumnsStyle.m_col_name] = "Icons";
  row = *(m_refTreeModelStyle-&gt;append());
  row[m_ColumnsStyle.m_col_value] = -1; // A custom meaning for this demo.
  row[m_ColumnsStyle.m_col_name] = "Default";
  m_ComboStyle.set_model(m_refTreeModelStyle);
  m_VBox.pack_start(m_ComboStyle, Gtk::PACK_SHRINK);
  m_ComboStyle.pack_start(m_ColumnsStyle.m_col_name);
  m_ComboStyle.signal_changed().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::on_combo_style_changed) );
  m_ComboStyle.set_active(row);

  //Add and fill the ToolPalette:
  load_icon_items();
  load_toggle_items();
  load_special_items();

  m_VBox.pack_start(m_HBox, Gtk::PACK_EXPAND_WIDGET);

  m_ScrolledWindowPalette.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
  m_ScrolledWindowPalette.set_border_width(6);
  m_ScrolledWindowPalette.add(m_ToolPalette);
  m_HBox.pack_start(m_ScrolledWindowPalette);

  on_combo_orientation_changed();

  m_ScrolledWindowCanvas.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS);
  m_ScrolledWindowCanvas.set_border_width(6);
  m_ScrolledWindowCanvas.add(m_Canvas);
  m_ScrolledWindowCanvas.set_size_request(200, -1);
  m_HBox.pack_start(m_ScrolledWindowCanvas);

  m_ToolPalette.add_drag_dest(m_Canvas,
    Gtk::DEST_DEFAULT_HIGHLIGHT, Gtk::TOOL_PALETTE_DRAG_ITEMS, Gdk::ACTION_COPY);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_combo_orientation_changed()
{
  Gtk::TreeModel::iterator iter = m_ComboOrientation.get_active();
  if(!iter)
    return;

  Gtk::TreeModel::Row row = *iter;
  const Gtk::Orientation value = row[m_ColumnsOrientation.m_col_value];
 
  m_ToolPalette.set_orientation(value);

  if(value == Gtk::ORIENTATION_HORIZONTAL)
    m_ScrolledWindowPalette.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_NEVER);
  else
    m_ScrolledWindowPalette.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
}

void ExampleWindow::on_combo_style_changed()
{
  Gtk::TreeModel::iterator iter = m_ComboStyle.get_active();
  if(!iter)
    return;

  Gtk::TreeModel::Row row = *iter;
  const int value = row[m_ColumnsStyle.m_col_value];
 
  if(value == -1)
    m_ToolPalette.unset_style();
  else
    m_ToolPalette.set_style((Gtk::ToolbarStyle)value);
}

</programlisting>
<para lang="en">File: <filename>canvas.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "canvas.h"
#include &lt;iostream&gt;

Canvas::Canvas()
: m_drag_data_requested_for_drop(false),
  m_drop_item(0)
{
  set_app_paintable();
}

Canvas::~Canvas()
{
  while(!m_canvas_items.empty())
  {
    type_vec_items::iterator iter = m_canvas_items.begin();
    CanvasItem* item = *iter;
    delete item;
    m_canvas_items.erase(iter);
  }

  delete m_drop_item;
}

void Canvas::item_draw(const CanvasItem *item,
  const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr,
  bool preview)
{
  if(!item || !item-&gt;pixbuf)
    return;

  const double cx = item-&gt;pixbuf-&gt;get_width();
  const double cy = item-&gt;pixbuf-&gt;get_height();

  Gdk::Cairo::set_source_pixbuf(cr,
    item-&gt;pixbuf,
    item-&gt;x - cx * 0.5, item-&gt;y - cy * 0.5);

  if(preview)
    cr-&gt;paint_with_alpha(0.6);
  else
    cr-&gt;paint();
}

bool Canvas::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  cr-&gt;set_source_rgb(1.0, 1.0, 1.0);
  const Gtk::Allocation allocation = get_allocation();
  cr-&gt;rectangle(0, 0, allocation.get_width(), allocation.get_height());
  cr-&gt;fill();

  for(type_vec_items::iterator iter = m_canvas_items.begin();
    iter != m_canvas_items.end(); ++iter )
  {
    item_draw(*iter, cr, false);
  }

  if(m_drop_item)
    item_draw (m_drop_item, cr, true);

  return true;
}


bool Canvas::on_drag_motion(const Glib::RefPtr&lt;Gdk::DragContext&gt;&amp; context,
  int x, int y, guint time)
{
  m_drag_data_requested_for_drop = false; //It's for drag-motion instead.

  if(m_drop_item)
  {
    // We already have a drop indicator so just update its position.

    m_drop_item-&gt;x = x;
    m_drop_item-&gt;y = y;

    queue_draw();
    context-&gt;drag_status(Gdk::ACTION_COPY, time);
  }
  else
  {
    // Request DnD data for creating a drop indicator.
    // This will cause on_drag_data_received() to be called.
    const Glib::ustring target = drag_dest_find_target(context);

    if (target.empty())
      return false;

    drag_get_data(context, target, time);
  }

  Gtk::DrawingArea::on_drag_motion(context, x, y, time);
  return true;
}


void Canvas::on_drag_data_received(const Glib::RefPtr&lt;Gdk::DragContext&gt;&amp; context,
  int x, int y, const Gtk::SelectionData&amp; selection_data, guint info, guint time)
{
  // Find the tool button which is the source of this DnD operation.
  Gtk::Widget* widget = drag_get_source_widget(context);

  Gtk::ToolPalette* drag_palette = dynamic_cast&lt;Gtk::ToolPalette*&gt;(widget);
  while(widget &amp;&amp; !drag_palette)
  {
    widget = widget-&gt;get_parent();
    drag_palette = dynamic_cast&lt;Gtk::ToolPalette*&gt;(widget);
  }

  Gtk::ToolItem* drag_item = 0;
  if(drag_palette)
    drag_item = drag_palette-&gt;get_drag_item(selection_data);

  // Create a drop indicator when a tool button was found:
  Gtk::ToolButton* button = dynamic_cast&lt;Gtk::ToolButton*&gt;(drag_item);
  if(!button)
    return;

  delete m_drop_item;
  m_drop_item = 0;

  try
  {
    CanvasItem* item = new CanvasItem(this, button, x, y);

    if(m_drag_data_requested_for_drop)
    {
      m_canvas_items.push_back(item);

      // Signal that the item was accepted and then redraw.
      context-&gt;drag_finish(true /* success */, false /* del */, time);
    }
    else
    {
      m_drop_item = item;

      // We are getting this data due to a request in drag_motion,
      // rather than due to a request in drag_drop, so we are just
      // supposed to call gdk_drag_status (), not actually paste in
      // the data.
      context-&gt;drag_status(Gdk::ACTION_COPY, time);
    }

    queue_draw();
  }
  catch (const Gtk::IconThemeError&amp; ex)
  {
    std::cerr &lt;&lt; "IconThemeError: " &lt;&lt; ex.what() &lt;&lt; std::endl;
  }

  Gtk::DrawingArea::on_drag_data_received(context, x, y, selection_data, info, time);
}


bool Canvas::on_drag_drop(const Glib::RefPtr&lt;Gdk::DragContext&gt;&amp; context, int /* x */, int /* y */, guint time)
{
  // Request DnD data for creating a dopped item.
  // This will cause on_drag_data_received() to be called.
  const Glib::ustring target = drag_dest_find_target(context);

  if (target.empty())
    return false;

  m_drag_data_requested_for_drop = true;
  drag_get_data(context, target, time);

  return true;
}

void Canvas::on_drag_leave(const Glib::RefPtr&lt;Gdk::DragContext&gt;&amp; context, guint time)
{
  //This signal is emitted to clean up the item used for drag-motion,
  //either when the cursor moves out of the widget or when we drop.

  if(!m_drop_item)
    return;

  delete m_drop_item;
  m_drop_item = 0;

  queue_draw();

  Gtk::DrawingArea::on_drag_leave(context, time);
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect1>

</chapter>

<chapter id="chapter-adjustment">
<title>Ajustes</title>

<para lang="en">
<application>gtkmm</application> has various widgets that can be visually adjusted using the mouse or
the keyboard, such as the <classname>Range</classname> widgets (described in
the <link linkend="chapter-range-widgets">Range Widgets</link> section). There are
also a few widgets that display some adjustable part of a larger area, such as
the <classname>Viewport</classname> widget. These widgets have
<classname>Gtk::Adjustment</classname> objects that express this common part of
their API.
</para>

<para lang="en">
So that applications can react to changes, for instance when a user moves a
scrollbar, <classname>Gtk::Adjustment</classname> has a
<literal>value_changed</literal> signal. You can then use the
<methodname>get_value()</methodname> method to discover the new value.
</para>

<sect1 id="sec-creating-adjustment">
<title>Criando um ajuste</title>

<para lang="en">
The <classname>Gtk::Adjustment</classname> is created by its
<methodname>create()</methodname> method which is as follows:
</para>

<programlisting lang="en">Glib::RefPtr&lt;Gtk::Adjustment&gt; Gtk::Adjustment::create(
  double value,
  double lower,
  double upper,
  double step_increment = 1,
  double page_increment = 10,
  double page_size = 0);</programlisting>

<para lang="en">
The <parameter>value</parameter> argument is the initial value of the
adjustment, usually corresponding to the topmost or leftmost position of an
adjustable widget. The <parameter>lower</parameter> and
<parameter>upper</parameter> arguments specify the possible range of values
which the adjustment can hold. The
<parameter>step_increment</parameter> argument specifies the smaller of
the two increments by which the user can change the value, while the
<parameter>page_increment</parameter> is the larger one. The
<parameter>page_size</parameter> argument usually corresponds somehow to
the visible area of a panning widget. The <parameter>upper</parameter> argument
is used to represent the bottommost or rightmost coordinate in a panning
widget's child.
<!-- TODO: Investigate the upper argument properly. There was some unclear stuff about it not always being the upper value. -->
</para>

</sect1>

<sect1 id="sec-adjustments-easy">
<title>Usando ajustes o caminho fácil</title>

<para>Os widgets ajustáveis ​​podem ser grosseiramente divididos naqueles que usam e requerem unidades específicas para estes valores, e aqueles que tratá-los como números arbitrários.</para>
<para lang="en">
The group which treats the values as arbitrary numbers includes the
<classname>Range</classname> widgets (<classname>Scrollbar</classname> and
<classname>Scale</classname>), the <classname>ScaleButton</classname> widget,
and the <classname>SpinButton</classname> widget. These widgets  are typically
"adjusted" directly by the user with the mouse or keyboard. They will treat the
<parameter>lower</parameter> and <parameter>upper</parameter> values of an
adjustment as a range within which the user can manipulate the adjustment's
<parameter>value</parameter>. By default, they will only modify the
<parameter>value</parameter> of an adjustment.
</para>

<para lang="en">
The other group includes the <classname>Viewport</classname> widget and the
<classname>ScrolledWindow</classname> widget. All of these widgets use pixel
values for their adjustments. These are also typically adjusted indirectly
using scrollbars. While all widgets which use adjustments can either create
their own adjustments or use ones you supply, you'll generally want to let this
particular category of widgets create its own adjustments.
</para>

<para lang="en">
If you share an adjustment object between a Scrollbar and a TextView
widget, manipulating the scrollbar will automagically adjust the TextView
widget. You can set it up like this:
</para>
<programlisting>// cria seus próprios ajustes
Gtk::TextView textview;
// usa o ajuste recém-criado para a barra de rolagem assim
Gtk::Scrollbar vscrollbar (textview.get_vadjustment(), Gtk::ORIENTATION_VERTICAL);</programlisting>

</sect1>

<sect1 id="sec-adjustment-internals">
<title>Ajustamento interno</title>

<para lang="en">
OK, you say, that's nice, but what if I want to create my own handlers to
respond when the user adjusts a <classname>Range</classname> widget or a
<classname>SpinButton</classname>. To access the value of a
<classname>Gtk::Adjustment</classname>, you can use the
<methodname>get_value()</methodname> and <methodname>set_value()</methodname> methods:
</para>

<para lang="en">
As mentioned earlier, <classname>Gtk::Adjustment</classname> can emit signals.
This is, of course, how updates happen automatically when you share an
<classname>Adjustment</classname> object between a
<classname>Scrollbar</classname> and another adjustable widget; all adjustable
widgets connect signal handlers to their adjustment's
<literal>value_changed</literal> signal, as can your program.
</para>

<para lang="en">
So, for example, if you have a <classname>Scale</classname> widget, and you
want to change the rotation of a picture whenever its value changes, you would
create a signal handler like this:
</para>
<programlisting lang="en">void cb_rotate_picture (MyPicture* picture)
{
  picture-&gt;set_rotation(adj-&gt;get_value());
...</programlisting>
<para lang="en">
and connect it to the scale widget's adjustment like this:
</para>
<programlisting lang="en">adj-&gt;signal_value_changed().connect(sigc::bind&lt;MyPicture*&gt;(sigc::mem_fun(*this,
    &amp;cb_rotate_picture), picture));</programlisting>

<para lang="en">
What if a widget reconfigures the <parameter>upper</parameter> or
<parameter>lower</parameter> fields of its <classname>Adjustment</classname>,
such as when a user adds more text to a text widget?  In this case, it emits
the <literal>changed</literal> signal.
</para>

<para lang="en">
<classname>Range</classname> widgets typically connect a handler to this
signal, which changes their appearance to reflect the change - for example, the
size of the slider in a scrollbar will grow or shrink in inverse proportion to
the difference between the <parameter>lower</parameter> and
<parameter>upper</parameter> values of its
<classname>Adjustment</classname>.
</para>

<para lang="en">
You probably won't ever need to attach a handler to this signal, unless you're
writing a new type of range widget.
</para>
<programlisting lang="en">adjustment-&gt;signal_changed();</programlisting>

</sect1>

</chapter>

<chapter id="chapter-widgets-without-xwindows">
<title>Widgets sem X-Windows</title>

<para lang="en">
Some Widgets do not have an associated X-Window, so they therefore do not
receive X events. This means that the signals described in the  <link linkend="sec-xeventsignals">X event signals</link> section will not be
emitted. If you want to capture events for these widgets you can use a special
container called <classname>Gtk::EventBox</classname>, which is described in
the <link linkend="sec-eventbox">EventBox</link> section.
</para>

<para>Aqui está uma lista de alguns desses Widgets:</para>
<programlisting lang="en">Gtk::Alignment (deprecated from <application>gtkmm</application> version 3.14)
Gtk::Arrow (deprecated from <application>gtkmm</application> version 3.14)
Gtk::AspectFrame
Gtk::Bin
Gtk::Box
Gtk::Button
Gtk::CheckButton
Gtk::Fixed
Gtk::Frame
Gtk::Grid
Gtk::Image
Gtk::Label
Gtk::MenuItem
Gtk::Notebook
Gtk::Paned
Gtk::RadioButton
Gtk::Range
Gtk::ScrolledWindow
Gtk::Separator
Gtk::Table (deprecated from <application>gtkmm</application> version 3.4)
Gtk::Toolbar</programlisting>

<para lang="en">
These widgets are mainly used for decoration or layout, so you won't often need
to capture events on them. They are intended to have no X-Window in order to improve performance.
</para>

<sect1 id="sec-eventbox">
<title>EventBox</title>

<para lang="en">
Some <application>gtkmm</application> widgets don't have associated X windows; they draw on
their parents' windows. Because of this, they cannot receive events.
Also, if they are incorrectly sized, they don't clip, so you can get
messy overwriting etc. To receive events on one of these widgets, you can place it
inside an <classname>EventBox</classname> widget and then call
<methodname>Gtk::Widget::set_events()</methodname> on the EventBox before showing it.</para>

<para lang="en">Although the name
<classname>EventBox</classname> emphasises the event-handling method, the
widget can also be used for clipping (and more; see the example below).
</para>
<!--
<para>TODO: Why don't they have X Windows - explain clipping.
Also, how does this affect platform such as Windows and MacOS that don't use X.
</para>
-->

<para>O construtor para <classname>Gtk::EventBox</classname> é:</para>

<programlisting>Gtk::EventBox();</programlisting>

<para>Um elemento filho pode ser adicionado a <classname>Caixa de Evento</classname> usando:</para>

<programlisting>event_box.add(child_widget);</programlisting>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1EventBox.html">Reference</ulink></para>

<sect2 id="eventbox-example">
<title>Exemplo</title>
<para lang="en">
The following example demonstrates both uses of an
<classname>EventBox</classname> - a label is created that is clipped to a small
box, and set up so that a mouse-click on the label causes the program to exit.
Resizing the window reveals varying amounts of the label.
</para>

<figure id="figure-eventbox">
  <title>EventBox</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/eventbox.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/eventbox?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  virtual bool on_eventbox_button_press(GdkEventButton* event);

  //Child widgets:
  Gtk::EventBox m_EventBox;
  Gtk::Label m_Label;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_Label("Click here to quit, quit, quit, quit, quit")
{
  set_title ("EventBox");
  set_border_width(10);

  add(m_EventBox);

  m_EventBox.add(m_Label);

  //Clip the label short:
  set_default_size(110, 20);
  m_Label.set_size_request(110, 20);
  m_Label.set_ellipsize(Pango::ELLIPSIZE_END);

  //And bind an action to it:
  m_EventBox.set_events(Gdk::BUTTON_PRESS_MASK);
  m_EventBox.signal_button_press_event().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::on_eventbox_button_press) );

  m_EventBox.set_tooltip_text("Click me!");

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

bool ExampleWindow::on_eventbox_button_press(GdkEventButton*)
{
  hide();
  return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>

</sect1>

</chapter>

<chapter id="chapter-dialogs">
<title>Caixas de diálogo</title>

<para lang="en">
Dialogs are used as secondary windows, to provide specific information or to
ask questions. <classname>Gtk::Dialog</classname> windows contain a few pre-packed
widgets to ensure consistency, and a <methodname>run()</methodname> method which
blocks until the user dismisses the dialog.
</para>

<para lang="en">
There are several derived <classname>Dialog</classname> classes which you might
find useful. <classname>Gtk::MessageDialog</classname> is used for most simple
notifications. But at other times you might need to derive your own dialog
class to provide more complex functionality.
</para>

<para lang="en">
To pack widgets into a custom dialog, you should pack them into the
<classname>Gtk::Box</classname>, available via
<methodname>get_content_area()</methodname>. To just add a <classname>Button</classname>
to the bottom of the <classname>Dialog</classname>, you could use the
<methodname>add_button()</methodname> method.
</para>

<para lang="en">
The <methodname>run()</methodname> method returns an <literal>int</literal>. This
may be a value from the <literal>Gtk::ResponseType</literal> if the user
closed the dialog by clicking a standard button, or it could be the custom
response value that you specified when using <methodname>add_button()</methodname>.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Dialog.html">Reference</ulink></para>

<sect1 id="sec-dialogs-messagedialog"><title lang="en">MessageDialog</title>
<para lang="en">
<classname>MessageDialog</classname> is a convenience class, used to create
simple, standard message dialogs, with a message, an icon, and buttons for user
response. You can specify the type of message and the text in the constructor,
as well as specifying standard buttons via the
<literal>Gtk::ButtonsType</literal> enum.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1MessageDialog.html">Reference</ulink></para>

<sect2 id="messagedialog-example">
<title>Exemplo</title>

<figure id="figure-dialogs-messagedialog">
  <title lang="en">MessageDialog</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/dialogs_messagedialog.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/dialogs/messagedialog?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_info_clicked();
  void on_button_question_clicked();

  //Child widgets:
  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Info, m_Button_Question;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/messagedialog.h&gt;
#include &lt;iostream&gt;


ExampleWindow::ExampleWindow()
: m_ButtonBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_Info("Show Info MessageDialog"),
  m_Button_Question("Show Question MessageDialog")
{
  set_title("Gtk::MessageDialog example");

  add(m_ButtonBox);

  m_ButtonBox.pack_start(m_Button_Info);
  m_Button_Info.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_info_clicked) );

  m_ButtonBox.pack_start(m_Button_Question);
  m_Button_Question.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_question_clicked) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_info_clicked()
{
  Gtk::MessageDialog dialog(*this, "This is an INFO MessageDialog");
  dialog.set_secondary_text(
          "And this is the secondary text that explains things.");

  dialog.run();
}

void ExampleWindow::on_button_question_clicked()
{
  Gtk::MessageDialog dialog(*this, "This is a QUESTION MessageDialog",
          false /* use_markup */, Gtk::MESSAGE_QUESTION,
          Gtk::BUTTONS_OK_CANCEL);
  dialog.set_secondary_text(
          "And this is the secondary text that explains things.");

  int result = dialog.run();

  //Handle the response:
  switch(result)
  {
    case(Gtk::RESPONSE_OK):
    {
      std::cout &lt;&lt; "OK clicked." &lt;&lt; std::endl;
      break;
    }
    case(Gtk::RESPONSE_CANCEL):
    {
      std::cout &lt;&lt; "Cancel clicked." &lt;&lt; std::endl;
      break;
    }
    default:
    {
      std::cout &lt;&lt; "Unexpected button clicked." &lt;&lt; std::endl;
      break;
    }
  }
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>

</sect1>

<sect1 id="sec-dialogs-filechooserdialog"><title lang="en">FileChooserDialog</title>
<para lang="en">
The <classname>FileChooserDialog</classname> is suitable for use with
"Open" or "Save" menu items.
</para>
<para lang="en">
Most of the useful member methods for this class are actually in the
<classname>Gtk::FileChooser</classname> base class.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1FileChooserDialog.html">Reference</ulink></para>

<sect2 id="filechooserdialog-example">
<title>Exemplo</title>

<figure id="figure-dialogs-filechooser">
  <title>Seletor de arquivos</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/dialogs_filechooser.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/dialogs/filechooserdialog?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_file_clicked();
  void on_button_folder_clicked();

  //Child widgets:
  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_File, m_Button_Folder;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;


ExampleWindow::ExampleWindow()
: m_ButtonBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_File("Choose File"),
  m_Button_Folder("Choose Folder")
{
  set_title("Gtk::FileSelection example");

  add(m_ButtonBox);

  m_ButtonBox.pack_start(m_Button_File);
  m_Button_File.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_file_clicked) );

  m_ButtonBox.pack_start(m_Button_Folder);
  m_Button_Folder.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_folder_clicked) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_folder_clicked()
{
  Gtk::FileChooserDialog dialog("Please choose a folder",
          Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
  dialog.set_transient_for(*this);

  //Add response buttons the the dialog:
  dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL);
  dialog.add_button("Select", Gtk::RESPONSE_OK);

  int result = dialog.run();

  //Handle the response:
  switch(result)
  {
    case(Gtk::RESPONSE_OK):
    {
      std::cout &lt;&lt; "Select clicked." &lt;&lt; std::endl;
      std::cout &lt;&lt; "Folder selected: " &lt;&lt; dialog.get_filename()
          &lt;&lt; std::endl;
      break;
    }
    case(Gtk::RESPONSE_CANCEL):
    {
      std::cout &lt;&lt; "Cancel clicked." &lt;&lt; std::endl;
      break;
    }
    default:
    {
      std::cout &lt;&lt; "Unexpected button clicked." &lt;&lt; std::endl;
      break;
    }
  }
}

void ExampleWindow::on_button_file_clicked()
{
  Gtk::FileChooserDialog dialog("Please choose a file",
          Gtk::FILE_CHOOSER_ACTION_OPEN);
  dialog.set_transient_for(*this);

  //Add response buttons the the dialog:
  dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL);
  dialog.add_button("_Open", Gtk::RESPONSE_OK);

  //Add filters, so that only certain file types can be selected:

  Glib::RefPtr&lt;Gtk::FileFilter&gt; filter_text = Gtk::FileFilter::create();
  filter_text-&gt;set_name("Text files");
  filter_text-&gt;add_mime_type("text/plain");
  dialog.add_filter(filter_text);

  Glib::RefPtr&lt;Gtk::FileFilter&gt; filter_cpp = Gtk::FileFilter::create();
  filter_cpp-&gt;set_name("C/C++ files");
  filter_cpp-&gt;add_mime_type("text/x-c");
  filter_cpp-&gt;add_mime_type("text/x-c++");
  filter_cpp-&gt;add_mime_type("text/x-c-header");
  dialog.add_filter(filter_cpp);

  Glib::RefPtr&lt;Gtk::FileFilter&gt; filter_any = Gtk::FileFilter::create();
  filter_any-&gt;set_name("Any files");
  filter_any-&gt;add_pattern("*");
  dialog.add_filter(filter_any);

  //Show the dialog and wait for a user response:
  int result = dialog.run();

  //Handle the response:
  switch(result)
  {
    case(Gtk::RESPONSE_OK):
    {
      std::cout &lt;&lt; "Open clicked." &lt;&lt; std::endl;

      //Notice that this is a std::string, not a Glib::ustring.
      std::string filename = dialog.get_filename();
      std::cout &lt;&lt; "File selected: " &lt;&lt;  filename &lt;&lt; std::endl;
      break;
    }
    case(Gtk::RESPONSE_CANCEL):
    {
      std::cout &lt;&lt; "Cancel clicked." &lt;&lt; std::endl;
      break;
    }
    default:
    {
      std::cout &lt;&lt; "Unexpected button clicked." &lt;&lt; std::endl;
      break;
    }
  }
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>
</sect1>

<sect1 id="sec-color-selection-dialog"><title lang="en">ColorChooserDialog</title>
<para lang="en">
The <classname>ColorChooserDialog</classname> allows the user to choose a
color. The <classname>ColorButton</classname> opens a color selection dialog
when it is clicked.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1ColorChooserDialog.html">Reference</ulink></para>

<sect2 id="colorchooserdialog-example">
<title>Exemplo</title>

<figure id="figure-dialogs-colorchooserdialog">
  <title lang="en">ColorChooserDialog</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/dialogs_colorchooserdialog.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/dialogs/colorchooserdialog?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_color_button_color_set();
  void on_button_dialog_clicked();
  bool on_drawing_area_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr);

  //Child widgets:
  Gtk::Box m_VBox;
  Gtk::ColorButton m_ColorButton;
  Gtk::Button m_Button_Dialog;
  Gtk::DrawingArea m_DrawingArea; //To show the color.

  Gdk::RGBA m_Color;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL, 5),
  m_Button_Dialog("Choose Color")
{
  set_title("Gtk::ColorChooserDialog example");
  set_default_size(200, 200);

  add(m_VBox);

  m_VBox.pack_start(m_ColorButton, Gtk::PACK_SHRINK);
  m_ColorButton.signal_color_set().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_color_button_color_set) );

  m_VBox.pack_start(m_Button_Dialog, Gtk::PACK_SHRINK);
  m_Button_Dialog.signal_clicked().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_button_dialog_clicked) );

  //Set start color:
  m_Color.set_red(0.0);
  m_Color.set_green(0.0);
  m_Color.set_blue(1.0);
  m_Color.set_alpha(1.0); //opaque
  m_ColorButton.set_rgba(m_Color);

  m_VBox.pack_start(m_DrawingArea);
  m_DrawingArea.signal_draw().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_drawing_area_draw));

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_color_button_color_set()
{
  //Store the chosen color:
  m_Color = m_ColorButton.get_rgba();
}

void ExampleWindow::on_button_dialog_clicked()
{
  Gtk::ColorChooserDialog dialog("Please choose a color");
  dialog.set_transient_for(*this);

  //Get the previously selected color:
  dialog.set_rgba(m_Color);

  const int result = dialog.run();

  //Handle the response:
  switch(result)
  {
    case Gtk::RESPONSE_OK:
    {
      //Store the chosen color:
      m_Color = dialog.get_rgba();
      m_ColorButton.set_rgba(m_Color);
      break;
    }
    case Gtk::RESPONSE_CANCEL:
    {
      std::cout &lt;&lt; "Cancel clicked." &lt;&lt; std::endl;
      break;
    }
    default:
    {
      std::cout &lt;&lt; "Unexpected button clicked: " &lt;&lt; result &lt;&lt; std::endl;
      break;
    }
  }
}

bool ExampleWindow::on_drawing_area_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  Gdk::Cairo::set_source_rgba(cr, m_Color);
  cr-&gt;paint();

  return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>

</sect1>

<sect1 id="sec-font-chooser-dialog"><title lang="en">FontChooserDialog</title>
<para lang="en">
The <classname>FontChooserDialog</classname> allows the user to choose a
font. The <classname>FontButton</classname> opens a font chooser dialog
when it is clicked.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1FontChooserDialog.html">Reference</ulink></para>

<sect2 id="fontchooserdialog-example">
<title>Exemplo</title>

<figure id="figure-dialogs-fontchooserdialog">
  <title lang="en">FontChooserDialog</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/dialogs_fontchooserdialog.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/dialogs/fontchooserdialog?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_font_button_font_set();
  void on_button_dialog_clicked();

  //Child widgets:
  Gtk::ButtonBox m_ButtonBox;
  Gtk::FontButton m_FontButton;
  Gtk::Button m_Button_Dialog;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_ButtonBox(Gtk::ORIENTATION_VERTICAL),
  m_FontButton("Sans 10"),
  m_Button_Dialog("Choose Font")
{
  set_title("Gtk::FontChooserDialog example");

  add(m_ButtonBox);

  m_ButtonBox.pack_start(m_FontButton);
  m_FontButton.set_use_font(true);
  m_FontButton.set_use_size(true);
  m_FontButton.signal_font_set().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_font_button_font_set) );

  m_ButtonBox.pack_start(m_Button_Dialog);
  m_Button_Dialog.signal_clicked().connect(sigc::mem_fun(*this,
    &amp;ExampleWindow::on_button_dialog_clicked) );
  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_font_button_font_set()
{
  Glib::ustring font_name = m_FontButton.get_font_name();
  std::cout &lt;&lt; "Font chosen: " &lt;&lt; font_name &lt;&lt; std::endl;
}

void ExampleWindow::on_button_dialog_clicked()
{
  Gtk::FontChooserDialog dialog("Please choose a font", *this);

  //Get the previously selected font name from the FontButton:
  dialog.set_font(m_FontButton.get_font_name());

  int result = dialog.run();

  //Handle the response:
  switch(result)
  {
    case Gtk::RESPONSE_OK:
    {
      Glib::ustring font_name = dialog.get_font();
      std::cout &lt;&lt; "Font chosen: " &lt;&lt; font_name &lt;&lt; std::endl;
      m_FontButton.set_font_name(font_name);
      break;
    }
    case Gtk::RESPONSE_CANCEL:
    {
      std::cout &lt;&lt; "Cancel clicked." &lt;&lt; std::endl;
      break;
    }
    default:
    {
      std::cout &lt;&lt; "Unexpected button clicked: " &lt;&lt; result &lt;&lt; std::endl;
      break;
    }
  }
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>

</sect1>

<sect1 id="sec-about-dialog"><title lang="en">Non-modal AboutDialog</title>
<para lang="en">
The <classname>AboutDialog</classname> offers a simple way to display information
about a program, like its logo, name, copyright, website and license.
</para>
<para lang="en">
Most dialogs in this chapter are modal, that is, they freeze the rest of
the application while they are shown. It's also possible to create a non-modal
dialog, which does not freeze other windows in the application.
The following example shows a non-modal <classname>AboutDialog</classname>. This is
perhaps not the kind of dialog you would normally make non-modal, but non-modal
dialogs can be useful in other cases. E.g. <application>gedit</application>'s
search-and-replace dialog is non-modal.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1AboutDialog.html">Reference</ulink></para>

<sect2 id="aboutdialog-example">
<title>Exemplo</title>

<figure id="figure-dialogs-about">
  <title lang="en">AboutDialog</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/dialogs_about.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/dialogs/aboutdialog?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_clicked();
  void on_about_dialog_response(int response_id);

  //Child widgets:
  Gtk::Box m_VBox;
  Gtk::Label m_Label;
  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button;
  Gtk::AboutDialog m_Dialog;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Label("The AboutDialog is non-modal. "
    "You can select parts of this text while the AboutDialog is shown."),
  m_ButtonBox(Gtk::ORIENTATION_VERTICAL),
  m_Button("Show AboutDialog")
{
  set_title("Gtk::AboutDialog example");

  add(m_VBox);

  m_VBox.pack_start(m_Label);
  m_Label.set_line_wrap(true);
  m_Label.set_selectable(true);

  m_VBox.pack_start(m_ButtonBox);
  m_ButtonBox.pack_start(m_Button);
  m_Button.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_clicked) );

  m_Dialog.set_transient_for(*this);

  m_Dialog.set_program_name("Example application");
  m_Dialog.set_version("1.0.0");
  m_Dialog.set_copyright("Murray Cumming");
  m_Dialog.set_comments("This is just an example application.");
  m_Dialog.set_license("LGPL");

  m_Dialog.set_website("http://www.gtkmm.org");
  m_Dialog.set_website_label("gtkmm website");

  std::vector&lt;Glib::ustring&gt; list_authors;
  list_authors.push_back("Murray Cumming");
  list_authors.push_back("Somebody Else");
  list_authors.push_back("AN Other");
  m_Dialog.set_authors(list_authors);

  m_Dialog.signal_response().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::on_about_dialog_response) );

  show_all_children();

  // The widget must be realized and mapped before grab_focus() is called.
  // That's why it's called after show_all_children().
  m_Button.grab_focus();
}

ExampleWindow::~ExampleWindow()
{
 
}

void ExampleWindow::on_about_dialog_response(int response_id)
{
  std::cout &lt;&lt; response_id
    &lt;&lt; ", close=" &lt;&lt; Gtk::RESPONSE_CLOSE
    &lt;&lt; ", cancel=" &lt;&lt; Gtk::RESPONSE_CANCEL
    &lt;&lt; ", delete_event=" &lt;&lt; Gtk::RESPONSE_DELETE_EVENT
    &lt;&lt; std::endl;

  if((response_id == Gtk::RESPONSE_CLOSE) ||
     (response_id == Gtk::RESPONSE_CANCEL) )
  {
    m_Dialog.hide();
  }
}

void ExampleWindow::on_button_clicked()
{
  m_Dialog.show();

  //Bring it to the front, in case it was already shown:
  m_Dialog.present();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
</sect2>

</sect1>

</chapter>

<chapter id="chapter-drawingarea">
  <title>O widget área de desenho</title>
  <para lang="en">
    The <classname>DrawingArea</classname> widget is a blank window that gives
    you the freedom to create any graphic you desire. Along with that freedom
    comes the responsibility to handle draw signals on the widget. When a
    widget is first shown, or when it is covered and then uncovered again it
    needs to redraw itself. Most widgets have code to do this, but the
    DrawingArea does not, allowing you to write your own draw signal
    handler to determine how the contents of the widget will be drawn. This is
    most often done by overriding the virtual
    <methodname>on_draw()</methodname> member function.
  </para>

  <para lang="en">
      GTK+ uses the <ulink url="http://cairographics.org">Cairo</ulink> drawing API.
      With <application>gtkmm</application>, you may use the <ulink url="http://www.cairographics.org/cairomm/">cairomm</ulink> C++ API for cairo.
  </para>

  <para lang="en">
      You can draw very sophisticated shapes using Cairo, but the methods to do
      so are quite basic. Cairo provides methods for drawing straight lines,
      curved lines, and arcs (including circles). These basic shapes can be
      combined to create more complex shapes and paths which can be filled with
      solid colors, gradients, patterns, and other things. In addition, Cairo
      can perform complex transformations, do compositing of images, and render
      antialiased text.
  </para>
  <note>
      <title>Cairo e pango</title>
      <para lang="en">Although Cairo can render text, it's not meant to be a replacement for
      Pango. Pango is a better choice if you need to perform more advanced
      text rendering such as wrapping or ellipsizing text. Drawing text with
      Cairo should only be done if the text is part of a graphic.</para>
  </note>
  <para lang="en">
      In this section of the tutorial, we'll cover the basic Cairo drawing
      model, describe each of the basic drawing elements in some detail (with
      examples), and then present a simple application that uses Cairo to draw
      a custom clock widget.
  </para>
  <sect1 id="sec-cairo-drawing-model">
    <title>Modelo de desenho com cairo</title>
    <para lang="en">
        The basic concept of drawing in Cairo involves defining 'invisible'
        paths and then stroking or filling them to make them visible.
    </para>
    <para lang="en">
        To do any drawing in <application>gtkmm</application> with Cairo, you must first create a
        <classname>Cairo::Context</classname> object. This class holds all of the graphics state parameters that
        describe how drawing is to be done. This includes information such as
        line width, color, the surface to draw to, and many other things. This
        allows the actual drawing functions to take fewer arguments to simplify
        the interface. In <application>gtkmm</application>, a <classname>Cairo::Context</classname> is
        created by calling the
        <methodname>Gdk::Window::create_cairo_context()</methodname> function.
        Since Cairo contexts are reference-counted objects, this function
        returns a <classname>Cairo::RefPtr&lt;Cairo::Context&gt;</classname>
        object.
    </para>
    <para lang="en">
        The following example shows  how to set up a Cairo context with a
        foreground color of red and a width of 2. Any drawing functions that
        use this context will use these settings.
    </para>
    <programlisting lang="en">Gtk::DrawingArea myArea;
Cairo::RefPtr&lt;Cairo::Context&gt; myContext = myArea.get_window()-&gt;create_cairo_context();
myContext-&gt;set_source_rgb(1.0, 0.0, 0.0);
myContext-&gt;set_line_width(2.0);</programlisting>
    <para lang="en">
        Each <classname>Cairo::Context</classname> is associated with a
        particular <classname>Gdk::Window</classname>, so the first line of the
        above example creates a <classname>Gtk::DrawingArea</classname> widget
        and the second line uses its associated
        <classname>Gdk::Window</classname> to create a
        <classname>Cairo::Context</classname> object. The final two lines
        change the graphics state of the context.
    </para>
    <para lang="en">
        There are a number of graphics state variables that can be set for a
        Cairo context. The most common context attributes are color (using
        <methodname>set_source_rgb()</methodname> or
        <methodname>set_source_rgba()</methodname> for translucent colors), line
        width (using <methodname>set_line_width()</methodname>), line dash pattern
        (using <methodname>set_dash()</methodname>), line cap style (using
        <methodname>set_line_cap()</methodname>), and line join style (using
        <methodname>set_line_join()</methodname>), and font styles (using
        <methodname>set_font_size()</methodname>,
        <methodname>set_font_face()</methodname> and others).
        There are many other settings as well, such as transformation matrices,
        fill rules, whether to perform antialiasing, and others. For further
        information, see the <ulink url="http://www.cairographics.org/cairomm/">cairomm</ulink> API documentation.
    </para>
    <para lang="en">
        The current state of a <classname>Cairo::Context</classname> can be
        saved to an internal stack of saved states and later be restored to the
        state it was in when you saved it. To do this, use the
        <methodname>save()</methodname>
        method and the <methodname>restore()</methodname> method. This can be
        useful if you need to temporarily change the line width and color (or
        any other graphics setting) in order to draw something and then return
        to the previous settings. In this situation, you could call
        <methodname>Cairo::Context::save()</methodname>, change the graphics
        settings, draw the lines, and then call
        <methodname>Cairo::Context::restore()</methodname> to restore the original
        graphics state. Multiple calls to <methodname>save()</methodname> and
        <methodname>restore()</methodname> can be nested; each call to
        <methodname>restore()</methodname> restores the state from the
        matching paired <methodname>save()</methodname>.
        <tip>
            <para lang="en">It is good practice to put all modifications to the graphics state
            between <methodname>save()</methodname>/<methodname>restore()</methodname>
            function calls. For example, if you have a function that takes a
            <classname>Cairo::Context</classname> reference as an argument, you
            might implement it as follows:
          </para>
          <programlisting lang="en">void doSomething(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; context, int x)
{
    context-&gt;save();
    // change graphics state
    // perform drawing operations
    context-&gt;restore();
}</programlisting>
        </tip>
    </para>
    <para lang="en">
        The virtual <methodname>on_draw()</methodname> method provides a
        Cairo context that you shall use for drawing in the
        <classname>Gtk::DrawingArea</classname> widget. It is not necessary to
        save and restore this Cairo context in <methodname>on_draw()</methodname>.
    </para>
  </sect1>
  <sect1 id="sec-cairo-drawing-lines">
    <title>Desenho de linhas retas</title>
    <para lang="en">
        Now that we understand the basics of the Cairo graphics library, we're
        almost ready to start drawing. We'll start with the simplest of
        drawing elements: the straight line. But first you need to know a
        little bit about Cairo's coordinate system. The origin of the Cairo
        coordinate system is located in the upper-left corner of the window
        with positive x values to the right and positive y values going down.
        <tip>
            <para lang="en">Since the Cairo graphics library was written with support for
            multiple output targets (the X window system, PNG images, OpenGL,
            etc), there is a distinction between user-space and device-space
            coordinates. The mapping between these two coordinate systems
            defaults to one-to-one so that integer values map roughly to pixels
            on the screen, but this setting can be adjusted if desired.
            Sometimes it may be useful to scale the coordinates so that the
            full width and height of a window both range from 0 to 1 (the 'unit
            square') or some other mapping that works for your application.
            This can be done with the
            <methodname>Cairo::Context::scale()</methodname> function.</para>
        </tip>
    </para>

    <sect2 id="cairo-example-lines"><title>Exemplo</title>
    <para lang="en">
        In this example, we'll construct a small but fully functional <application>gtkmm</application>
        program and draw some lines into the window. The lines are drawn by
        creating a path and then stroking it. A path is created using the
        functions <methodname>Cairo::Context::move_to()</methodname> and
        <methodname>Cairo::Context::line_to()</methodname>. The function
        <methodname>move_to()</methodname> is similar to the act of lifting your
        pen off of the paper and placing it somewhere else -- no line is drawn
        between the point you were at and the point you moved to. To draw a
        line between two points, use the <methodname>line_to()</methodname>
        function.
    </para>
    <para lang="en">
        After you've finished creating your path, you still haven't
        drawn anything visible yet. To make the path visible, you must use the
        function <methodname>stroke()</methodname> which will stroke the current
        path with the line width and style specified in your
        <classname>Cairo::Context</classname> object. After stroking, the
        current path will be cleared so that you can start on your next path.
    </para>
        <tip>
            <para lang="en">Many Cairo drawing functions have a <methodname>_preserve()</methodname>
            variant. Normally drawing functions such as
            <methodname>clip()</methodname>, <methodname>fill()</methodname>, or
            <methodname>stroke()</methodname> will clear the current path. If you
            use the <methodname>_preserve()</methodname> variant, the current path
            will be retained so that you can use the same path with the next
            drawing function.</para>
        </tip>

    <figure id="figure-drawingarea-lines">
      <title>Área de desenho - Linhas</title>
      <screenshot>
        <graphic format="PNG" fileref="figures/drawingarea_lines.png"/>
      </screenshot>
    </figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/simple?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>myarea.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H

#include &lt;gtkmm/drawingarea.h&gt;

class MyArea : public Gtk::DrawingArea
{
public:
  MyArea();
  virtual ~MyArea();

protected:
  //Override default signal handler:
  virtual bool on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr);
};

#endif // GTKMM_EXAMPLE_MYAREA_H
</programlisting>
<para lang="en">File: <filename>myarea.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include &lt;cairomm/context.h&gt;

MyArea::MyArea()
{
}

MyArea::~MyArea()
{
}

bool MyArea::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  Gtk::Allocation allocation = get_allocation();
  const int width = allocation.get_width();
  const int height = allocation.get_height();

  // coordinates for the center of the window
  int xc, yc;
  xc = width / 2;
  yc = height / 2;

  cr-&gt;set_line_width(10.0);

  // draw red lines out from the center of the window
  cr-&gt;set_source_rgb(0.8, 0.0, 0.0);
  cr-&gt;move_to(0, 0);
  cr-&gt;line_to(xc, yc);
  cr-&gt;line_to(0, height);
  cr-&gt;move_to(xc, yc);
  cr-&gt;line_to(width, yc);
  cr-&gt;stroke();

  return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include &lt;gtkmm/application.h&gt;
#include &lt;gtkmm/window.h&gt;

int main(int argc, char** argv)
{
   Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

   Gtk::Window win;
   win.set_title("DrawingArea");

   MyArea area;
   win.add(area);
   area.show();

   return app-&gt;run(win);
}
</programlisting>
<!-- end inserted example code -->

    <para lang="en">
        This program contains a single class, <classname>MyArea</classname>,
        which is a subclass of <classname>Gtk::DrawingArea</classname> and
        contains an <methodname>on_draw()</methodname> member function.
        This function is called whenever the image in the drawing area needs to
        be redrawn. It is passed a <classname>Cairo::RefPtr</classname>
        pointer to a <classname>Cairo::Context</classname> that we use
        for the drawing.
        The actual drawing code sets the color we want to use for drawing by
        using <methodname>set_source_rgb()</methodname> which takes arguments
        defining the Red, Green, and Blue components of the desired color
        (valid values are between 0 and 1). After setting the color, we
        created a new path using the functions <methodname>move_to()</methodname>
        and <methodname>line_to()</methodname>, and then stroked this path with
        <methodname>stroke()</methodname>.
    </para>
    <tip>
        <title>Desenho com coordenadas relativas</title>
        <para lang="en">In the example above we drew everything using absolute coordinates. You can also draw using
        relative coordinates. For a straight line, this is done with the
        function <methodname>Cairo::Context::rel_line_to()</methodname>.</para>
    </tip>
    </sect2>
    <sect2 id="cairo-line-styles">
        <title>Estilos de linha</title>
        <para lang="en">
            In addition to drawing basic straight lines, there are a number of
            things that you can customize about a line. You've already seen
            examples of setting a line's color and width, but there are others
            as well.
        </para>
        <para lang="en">
            If you've drawn a series of lines that form a path, you may
            want them to join together in a certain way. Cairo offers
            three different ways to join lines together: Miter, Bevel, and
            Round. These are show below:
        </para>
        <figure id="figure-cairo-joins">
            <title lang="en">Different join types in Cairo</title>
            <screenshot>
                <graphic format="PNG" fileref="figures/cairo_joins.png"/>
            </screenshot>
        </figure>
        <para lang="en">
            The line join style is set using the function
            <methodname>Cairo::Context::set_line_join()</methodname>.
        </para>
        <para lang="en">
            Line ends can have different styles as well. The default style
            is for the line to start and stop exactly at the destination
            points of the line. This is called a Butt cap. The other
            options are Round (uses a round ending, with the center of the
            circle at the end point) or Square (uses a squared ending, with
            the center of the square at the end point). This setting is set
            using the function
            <methodname>Cairo::Context::set_line_cap()</methodname>.
        </para>
        <para lang="en">
            There are other things you can customize as well, including
            creating dashed lines and other things. For more information, see
            the Cairo API documentation.
        </para>
    </sect2>
    <sect2 id="sec-cairo-thin-lines">
      <title>Desenhando linhas finas</title>
      <para lang="en">
        If you try to draw one pixel wide lines, you may notice that the line
        sometimes comes up blurred and wider than it ought to be.
        This happens because Cairo will try to draw from the selected position,
        to both sides (half to each), so if you're positioned right on the
        intersection of the pixels, and want a one pixel wide line, Cairo will try
        to use half of each adjacent pixel, which isn't possible (a pixel is the
        smallest unit possible). This happens when the width of the line is an
        odd number of pixels (not just one pixel).
      </para>
      <para lang="en">
        The trick is to position in the middle of the pixel where you want the
        line to be drawn, and thus guaranteeing you get the desired results.
        See <ulink url="http://cairographics.org/FAQ/#sharp_lines">Cairo FAQ</ulink>.
      </para>

      <figure id="figure-drawingarea-thin-lines">
        <title lang="en">Drawing Area - Thin Lines</title>
        <screenshot>
          <graphic format="PNG" fileref="figures/drawingarea_thin_lines.png"/>
        </screenshot>
      </figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/thin_lines?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm/window.h&gt;
#include &lt;gtkmm/grid.h&gt;
#include &lt;gtkmm/checkbutton.h&gt;
#include "myarea.h"

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_toggled();

private:
  Gtk::Grid m_Container;
  MyArea m_Area_Lines;
  Gtk::CheckButton m_Button_FixLines;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>myarea.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H

#include &lt;gtkmm/drawingarea.h&gt;

class MyArea : public Gtk::DrawingArea
{
public:
  MyArea();
  virtual ~MyArea();

  void fix_lines(bool fix = true);
  void force_redraw();

protected:
  //Override default signal handler:
  virtual bool on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr);

private:
  double m_fix;
};

#endif // GTKMM_EXAMPLE_MYAREA_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_Button_FixLines("Fix lines")
{
  set_title("Thin lines example");

  m_Container.set_orientation(Gtk::ORIENTATION_HORIZONTAL);

  m_Container.add(m_Area_Lines);
  m_Container.add(m_Button_FixLines);

  add(m_Container);

  m_Button_FixLines.signal_toggled().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::on_button_toggled));

  // Synchonize the drawing in m_Area_Lines with the state of the toggle button.
  on_button_toggled();

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_toggled()
{
  m_Area_Lines.fix_lines(m_Button_FixLines.get_active());
}
</programlisting>
<para lang="en">File: <filename>myarea.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"

MyArea::MyArea()
: m_fix (0)
{
  set_size_request (200, 100);
}

MyArea::~MyArea()
{
}

bool MyArea::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  Gtk::Allocation allocation = get_allocation();
  const int width = allocation.get_width();
  const int height = allocation.get_height();

  cr-&gt;set_line_width(1.0);

  // draw one line, every two pixels
  // without the 'fix', you won't notice any space between the lines,
  // since each one will occupy two pixels (width)
  for (int i = 0; i &lt; width; i += 2)
  {
    cr-&gt;move_to(i + m_fix, 0);
    cr-&gt;line_to(i + m_fix, height);
  }

  cr-&gt;stroke();

  return true;
}

// Toogle between both values (0 or 0.5)
void MyArea::fix_lines(bool fix)
{
  // to get the width right, we have to draw in the middle of the pixel
  m_fix = fix ? 0.5 : 0.0;

  force_redraw();
}

// force the redraw of the image
void MyArea::force_redraw()
{
  Glib::RefPtr&lt;Gdk::Window&gt; win = get_window();
  if (win)
  {
    Gdk::Rectangle r(0, 0, get_allocation().get_width(), get_allocation().get_height());
    win-&gt;invalidate_rect(r, false);
  }
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char* argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
    </sect2>
  </sect1>

    <sect1 id="sec-cairo-curved-lines">
        <title>Desenhando linhas curvadas</title>
        <para lang="en">
            In addition to drawing straight lines Cairo allows you to easily
            draw curved lines (technically a cubic Bézier spline) using the
            <methodname>Cairo::Context::curve_to()</methodname> and
            <methodname>Cairo::Context::rel_curve_to()</methodname> functions.
            These functions take coordinates for a destination point as well as
            coordinates for two 'control' points. This is best explained using
            an example, so let's dive in.
        </para>
        <sect2 id="cairo-example-curves">
            <title>Exemplo</title>
            <para lang="en">
                This simple application draws a curve with Cairo and displays
                the control points for each end of the curve.
            </para>
        <figure id="figure-drawingarea-curve">
            <title>Área de desenho - Linhas</title>
            <screenshot>
                <graphic format="PNG" fileref="figures/drawingarea_curve.png"/>
            </screenshot>
        </figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/curve?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>myarea.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H

#include &lt;gtkmm/drawingarea.h&gt;

class MyArea : public Gtk::DrawingArea
{
public:
  MyArea();
  virtual ~MyArea();

protected:
  //Override default signal handler:
  virtual bool on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr);
};

#endif // GTKMM_EXAMPLE_MYAREA_H
</programlisting>
<para lang="en">File: <filename>myarea.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include &lt;cairomm/context.h&gt;

MyArea::MyArea()
{
}

MyArea::~MyArea()
{
}

bool MyArea::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  Gtk::Allocation allocation = get_allocation();
  const int width = allocation.get_width();
  const int height = allocation.get_height();

  double x0=0.1, y0=0.5, // start point
         x1=0.4, y1=0.9,  // control point #1
         x2=0.6, y2=0.1,  // control point #2
         x3=0.9, y3=0.5;  // end point

  // scale to unit square (0 to 1 width and height)
  cr-&gt;scale(width, height);

  cr-&gt;set_line_width(0.05);
  // draw curve
  cr-&gt;move_to(x0, y0);
  cr-&gt;curve_to(x1, y1, x2, y2, x3, y3);
  cr-&gt;stroke();
  // show control points
  cr-&gt;set_source_rgba(1, 0.2, 0.2, 0.6);
  cr-&gt;move_to(x0, y0);
  cr-&gt;line_to (x1, y1);
  cr-&gt;move_to(x2, y2);
  cr-&gt;line_to (x3, y3);
  cr-&gt;stroke();

  return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include &lt;gtkmm/application.h&gt;
#include &lt;gtkmm/window.h&gt;

int main(int argc, char** argv)
{
   Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

   Gtk::Window win;
   win.set_title("DrawingArea");

   MyArea area;
   win.add(area);
   area.show();

   return app-&gt;run(win);
}
</programlisting>
<!-- end inserted example code -->
        <para lang="en">
            The only difference between this example and the straight line
            example is in the <methodname>on_draw()</methodname> function,
            but there are a few new concepts and functions introduced here, so
            let's examine them briefly.
        </para>
        <para lang="en">
            We make a call to
            <methodname>Cairo::Context::scale()</methodname>, passing in the width
            and height of the drawing area. This scales the user-space
            coordinate system such that the width and height of the widget
            are both equal to 1.0 'units'. There's no particular reason to
            scale the coordinate system in this case, but sometimes it can make
            drawing operations easier.
        </para>
        <para lang="en">
            The call to <methodname>Cairo::Context::curve_to()</methodname> should
            be fairly self-explanatory. The first pair of coordinates define
            the control point for the beginning of the curve. The second set
            of coordinates define the control point for the end of the curve,
            and the last set of coordinates define the destination point. To
            make the concept of control points a bit easier to visualize, a
            line has been drawn from each control point to the end-point on the
            curve that it is associated with. Note that these control point
            lines are both translucent. This is achieved with a variant of
            <methodname>set_source_rgb()</methodname> called
            <methodname>set_source_rgba()</methodname>. This function takes a
            fourth argument specifying the alpha value of the color (valid
            values are between 0 and 1).
        </para>
        </sect2>
  </sect1>
  <sect1 id="sec-cairo-drawing-arcs">
      <title lang="en">Drawing Arcs and Circles</title>
      <para lang="en">
          With Cairo, the same function is used to draw arcs, circles, or
          ellipses: <methodname>Cairo::Context::arc()</methodname>. This function
          takes five arguments. The first two are the coordinates of the
          center point of the arc, the third argument is the radius of the arc,
          and the final two arguments define the start and end angle of the
          arc. All angles are defined in radians, so drawing a circle is the
          same as drawing an arc from 0 to 2 * M_PI radians.
          An angle of 0 is in the direction of the positive X axis (in user-space). An
          angle of M_PI/2 radians (90 degrees) is in the direction of the positive Y axis
          (in user-space). Angles increase in the direction from the positive X axis
          toward the positive Y axis. So with the default transformation matrix, angles
          increase in a clockwise direction. (Remember that the positive Y axis
          points downwards.)
      </para>
      <para lang="en">
          To draw an ellipse, you can scale the current transformation matrix
          by different amounts in the X and Y directions. For example, to draw
          an ellipse with center at <varname>x</varname>, <varname>y</varname>
          and size <varname>width</varname>, <varname>height</varname>:

          <programlisting lang="en">context-&gt;save();
context-&gt;translate(x, y);
context-&gt;scale(width / 2.0, height / 2.0);
context-&gt;arc(0.0, 0.0, 1.0, 0.0, 2 * M_PI);
context-&gt;restore();</programlisting>
      </para>
      <sect2 id="cairo-example-arcs">
          <title>Exemplo</title>
          <para lang="en">
              Here's an example of a simple program that draws an arc, a circle
              and an ellipse into a drawing area.
          </para>
          <figure id="figure-drawingarea-arc">
              <title>Área de desenho - Arcos</title>
              <screenshot>
                  <graphic format="PNG" fileref="figures/drawingarea_arcs.png"/>
              </screenshot>
          </figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/arcs?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>myarea.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H

#include &lt;gtkmm/drawingarea.h&gt;

class MyArea : public Gtk::DrawingArea
{
public:
  MyArea();
  virtual ~MyArea();

protected:
  //Override default signal handler:
  virtual bool on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr);
};

#endif // GTKMM_EXAMPLE_MYAREA_H
</programlisting>
<para lang="en">File: <filename>myarea.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include &lt;cairomm/context.h&gt;
#include &lt;cmath&gt;

MyArea::MyArea()
{
}

MyArea::~MyArea()
{
}

bool MyArea::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  // This is where we draw on the window
  Gtk::Allocation allocation = get_allocation();
  const int width = allocation.get_width();
  const int height = allocation.get_height();
  const int lesser = MIN(width, height);

  // coordinates for the center of the window
  int xc, yc;
  xc = width / 2;
  yc = height / 2;

  cr-&gt;set_line_width(lesser * 0.02);  // outline thickness changes
                                      // with window size

  // first draw a simple unclosed arc
  cr-&gt;save();
  cr-&gt;arc(width / 3.0, height / 4.0, lesser / 4.0, -(M_PI / 5.0), M_PI);
  cr-&gt;close_path();   // line back to start point
  cr-&gt;set_source_rgb(0.0, 0.8, 0.0);
  cr-&gt;fill_preserve();
  cr-&gt;restore();  // back to opaque black
  cr-&gt;stroke();   // outline it

  // now draw a circle
  cr-&gt;save();
  cr-&gt;arc(xc, yc, lesser / 4.0, 0.0, 2.0 * M_PI); // full circle
  cr-&gt;set_source_rgba(0.0, 0.0, 0.8, 0.6);    // partially translucent
  cr-&gt;fill_preserve();
  cr-&gt;restore();  // back to opaque black
  cr-&gt;stroke();

  // and finally an ellipse
  double ex, ey, ew, eh;
  // center of ellipse
  ex = xc;
  ey = 3.0 * height / 4.0;
  // ellipse dimensions
  ew = 3.0 * width / 4.0;
  eh = height / 3.0;

  cr-&gt;save();

  cr-&gt;translate(ex, ey);  // make (ex, ey) == (0, 0)
  cr-&gt;scale(ew / 2.0, eh / 2.0);  // for width: ew / 2.0 == 1.0
                                  // for height: eh / 2.0 == 1.0

  cr-&gt;arc(0.0, 0.0, 1.0, 0.0, 2 * M_PI);  // 'circle' centered at (0, 0)
                                          // with 'radius' of 1.0

  cr-&gt;set_source_rgba(0.8, 0.0, 0.0, 0.7);
  cr-&gt;fill_preserve();
  cr-&gt;restore();  // back to opaque black
  cr-&gt;stroke();

  return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include &lt;gtkmm/application.h&gt;
#include &lt;gtkmm/window.h&gt;

int main(int argc, char** argv)
{
   Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

   Gtk::Window win;
   win.set_title("DrawingArea");

   MyArea area;
   win.add(area);
   area.show();

   return app-&gt;run(win);
}
</programlisting>
<!-- end inserted example code -->

          <para lang="en">
              There are a couple of things to note about this example code.
              Again, the only real difference between this example and the
              previous ones is the <methodname>on_draw()</methodname>
              function, so we'll limit our focus to that function. In
              addition, the first part of the function is nearly identical to
              the previous examples, so we'll skip that portion.
          </para>
          <para lang="en">
              Note that in this case, we've expressed nearly everything in
              terms of the height and width of the window, including the width
              of the lines. Because of this, when you resize the window,
              everything scales with the window. Also note that there are
              three drawing sections in the function and each is wrapped with a
              <methodname>save()</methodname>/<methodname>restore()</methodname> pair
              so that we're back at a known state after each drawing.
          </para>
          <para lang="en">
              The section for drawing an arc introduces one new function,
              <methodname>close_path()</methodname>. This function will in effect
              draw a straight line from the current point back to the first
              point in the path. There is a significant difference between
              calling <methodname>close_path()</methodname> and manually drawing a
              line back to the starting point, however. If you use
              <methodname>close_path()</methodname>, the lines will be nicely
              joined together. If you use <methodname>line_to()</methodname>
              instead, the lines will end at the same point, but Cairo won't do
              any special joining.
          </para>
          <note>
              <title>Desenhando no sentido anti-horário</title>
              <para lang="en">
                  The function
                  <methodname>Cairo::Context::arc_negative()</methodname> is
                  exactly the same as
                  <methodname>Cairo::Context::arc()</methodname> but the angles go
                  the opposite direction.
              </para>
          </note>

      </sect2>
  </sect1>
  <sect1 id="sec-drawing-text">
      <title>Desenhando texto</title>
      <sect2 id="drawing-text-pango">
          <title>Desenhando texto com pango</title>
          <para lang="en">
              Text is drawn via Pango Layouts. The easiest way to create a
              <classname>Pango::Layout</classname> is to use
              <methodname>Gtk::Widget::create_pango_layout()</methodname>.
              Once created, the layout can be manipulated in various ways,
              including changing the text, font, etc. Finally, the layout can
              be rendered using the
              <methodname>Pango::Layout::show_in_cairo_context()</methodname> method.
          </para>
      </sect2>
      <sect2 id="pango-text-example">
        <title>Exemplo</title>
        <para lang="en">
           Here is an example of a program that draws some text, some of it
           upside-down. The Printing chapter contains another
           <link linkend="sec-printing-example">example</link> of drawing text.
        </para>
        <figure id="figure-drawingarea-pango-text">
            <title>Área de desenho - Texto</title>
            <screenshot>
                <graphic format="PNG" fileref="figures/drawingarea_pango_text.png"/>
            </screenshot>
        </figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/pango_text?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>myarea.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H

#include &lt;gtkmm/drawingarea.h&gt;

class MyArea : public Gtk::DrawingArea
{
public:
  MyArea();
  virtual ~MyArea();

protected:
  //Override default signal handler:
  virtual bool on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr);

private:
  void draw_rectangle(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr, int width, int height);
  void draw_text(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr, int rectangle_width, int rectangle_height);

};

#endif // GTKMM_EXAMPLE_MYAREA_H
</programlisting>
<para lang="en">File: <filename>myarea.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"

MyArea::MyArea()
{
}

MyArea::~MyArea()
{
}

bool MyArea::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  Gtk::Allocation allocation = get_allocation();
  const int width = allocation.get_width();
  const int height = allocation.get_height();

  const int rectangle_width = width;
  const int rectangle_height = height / 2;

  // Draw a black rectangle
  cr-&gt;set_source_rgb(0.0, 0.0, 0.0);
  draw_rectangle(cr, rectangle_width, rectangle_height);

  // and some white text
  cr-&gt;set_source_rgb(1.0, 1.0, 1.0);
  draw_text(cr, rectangle_width, rectangle_height);

  // flip the image vertically
  // see http://www.cairographics.org/documentation/cairomm/reference/classCairo_1_1Matrix.html
  // the -1 corresponds to the yy part (the flipping part)
  // the height part is a translation (we could have just called cr-&gt;translate(0, height) instead)
  // it's height and not height / 2, since we want this to be on the second part of our drawing
  // (otherwise, it would draw over the previous part)
  Cairo::Matrix matrix(1.0, 0.0, 0.0, -1.0, 0.0, height);

  // apply the matrix
  cr-&gt;transform(matrix);

  // white rectangle
  cr-&gt;set_source_rgb(1.0, 1.0, 1.0);
  draw_rectangle(cr, rectangle_width, rectangle_height);

  // black text
  cr-&gt;set_source_rgb(0.0, 0.0, 0.0);
  draw_text(cr, rectangle_width, rectangle_height);

  return true;
}

void MyArea::draw_rectangle(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr,
                            int width, int height)
{
  cr-&gt;rectangle(0, 0, width, height);
  cr-&gt;fill();
}

void MyArea::draw_text(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr,
                       int rectangle_width, int rectangle_height)
{
  // http://developer.gnome.org/pangomm/unstable/classPango_1_1FontDescription.html
  Pango::FontDescription font;

  font.set_family("Monospace");
  font.set_weight(Pango::WEIGHT_BOLD);

  // http://developer.gnome.org/pangomm/unstable/classPango_1_1Layout.html
  Glib::RefPtr&lt;Pango::Layout&gt; layout = create_pango_layout("Hi there!");

  layout-&gt;set_font_description(font);

  int text_width;
  int text_height;

  //get the text dimensions (it updates the variables -- by reference)
  layout-&gt;get_pixel_size(text_width, text_height);

  // Position the text in the middle
  cr-&gt;move_to((rectangle_width-text_width)/2, (rectangle_height-text_height)/2);

  layout-&gt;show_in_cairo_context(cr);
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include &lt;gtkmm/application.h&gt;
#include &lt;gtkmm/window.h&gt;

int main(int argc, char* argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  Gtk::Window window;
  window.set_title("Drawing text example");

  MyArea area;
  window.add(area);
  area.show();

  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
      </sect2>

      <!--
      <sect2 id="drawing-text-cairo">
          <title>Drawing Text with Cairo</title>
          <warning>TODO: Add Cairo content.</warning>
      </sect2>
      -->
  </sect1>
  <sect1 id="sec-draw-images">
      <title>Desenhando imagens</title>
          <para lang="en">
              There is a method for drawing from a
              <classname>Gdk::Pixbuf</classname> to a <classname>Cairo::Context</classname>.
              A <classname>Gdk::Pixbuf</classname> buffer is a useful wrapper
              around a collection of pixels, which can be read from files, and
              manipulated in various ways.
          </para>
          <para lang="en">
              Probably the most common way of creating
              <classname>Gdk::Pixbuf</classname>s is to use
              <methodname>Gdk::Pixbuf::create_from_file()</methodname> or
              <methodname>Gdk::Pixbuf::create_from_resource()</methodname>,
              which can read an image file, such as a png file into a pixbuf
              ready for rendering.
          </para>
          <para lang="en">
              The <classname>Gdk::Pixbuf</classname> can be rendered by setting
              it as the source pattern of the Cairo context with
              <methodname>Gdk::Cairo::set_source_pixbuf()</methodname>.
              Then draw the image with either <methodname>Cairo::Context::paint()</methodname>
              (to draw the whole image), or <methodname>Cairo::Context::rectangle()</methodname>
              and <methodname>Cairo::Context::fill()</methodname> (to fill the
              specified rectangle). <methodname>set_source_pixbuf()</methodname>
              is not a member of <classname>Cairo::Context</classname>. It takes
              a <classname>Cairo::Context</classname> as its first parameter.
          </para>
          <para lang="en">
              Here is a small bit of code to tie it all together: (Note that
              usually you wouldn't load the image every time in the draw
              signal handler! It's just shown here to keep it all together.)
          </para>
          <programlisting lang="en">bool MyArea::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  Glib::RefPtr&lt;Gdk::Pixbuf&gt; image = Gdk::Pixbuf::create_from_file("myimage.png");
  // Draw the image at 110, 90, except for the outermost 10 pixels.
  Gdk::Cairo::set_source_pixbuf(cr, image, 100, 80);
  cr-&gt;rectangle(110, 90, image-&gt;get_width()-20, image-&gt;get_height()-20);
  cr-&gt;fill();
  return true;
}</programlisting>
        <sect2 id="cairo-example-image">
            <title>Exemplo</title>
            <para lang="en">
                Here is an example of a simple program that draws an image.
                The program loads the image from a resource file. See the <link linkend="sec-gio-resource">Gio::Resource and glib-compile-resources</link>
                section. Use <application>glib-compile-resources</application> to compile
                the resources into a C source file that can be compiled and
                linked with the C++ code. E.g.
                <screen lang="en">$ glib-compile-resources --target=resources.c --generate-source image.gresource.xml</screen>
            </para>
        <figure id="figure-drawingarea-image">
            <title>Área de desenho - Imagens</title>
            <screenshot>
                <graphic format="PNG" fileref="figures/drawingarea_image.png"/>
            </screenshot>
        </figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/image?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>myarea.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H

#include &lt;gtkmm/drawingarea.h&gt;
#include &lt;gdkmm/pixbuf.h&gt;

class MyArea : public Gtk::DrawingArea
{
public:
  MyArea();
  virtual ~MyArea();

protected:
  //Override default signal handler:
  virtual bool on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr);

  Glib::RefPtr&lt;Gdk::Pixbuf&gt; m_image;
};

#endif // GTKMM_EXAMPLE_MYAREA_H
</programlisting>
<para lang="en">File: <filename>myarea.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include &lt;cairomm/context.h&gt;
#include &lt;giomm/resource.h&gt;
#include &lt;gdkmm/general.h&gt; // set_source_pixbuf()
#include &lt;glibmm/fileutils.h&gt;
#include &lt;iostream&gt;

MyArea::MyArea()
{
  try
  {
    // The fractal image has been created by the XaoS program.
    // http://xaos.sourceforge.net
    m_image = Gdk::Pixbuf::create_from_resource("/image/fractal_image.png");
  }
  catch(const Gio::ResourceError&amp; ex)
  {
    std::cerr &lt;&lt; "ResourceError: " &lt;&lt; ex.what() &lt;&lt; std::endl;
  }
  catch(const Gdk::PixbufError&amp; ex)
  {
    std::cerr &lt;&lt; "PixbufError: " &lt;&lt; ex.what() &lt;&lt; std::endl;
  }

  // Show at least a quarter of the image.
  if (m_image)
    set_size_request(m_image-&gt;get_width()/2, m_image-&gt;get_height()/2);
}

MyArea::~MyArea()
{
}

bool MyArea::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  if (!m_image)
    return false;

  Gtk::Allocation allocation = get_allocation();
  const int width = allocation.get_width();
  const int height = allocation.get_height();

  // Draw the image in the middle of the drawing area, or (if the image is
  // larger than the drawing area) draw the middle part of the image.
  Gdk::Cairo::set_source_pixbuf(cr, m_image,
    (width - m_image-&gt;get_width())/2, (height - m_image-&gt;get_height())/2);
  cr-&gt;paint();

  return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "myarea.h"
#include &lt;gtkmm/application.h&gt;
#include &lt;gtkmm/window.h&gt;

int main(int argc, char** argv)
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  Gtk::Window win;
  win.set_title("DrawingArea");
  win.set_default_size(300, 200);

  MyArea area;
  win.add(area);
  area.show();

  return app-&gt;run(win);
}
</programlisting>
<para lang="en">File: <filename>image.gresource.xml</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;gresources&gt;
  &lt;gresource prefix="/image"&gt;
    &lt;file&gt;fractal_image.png&lt;/file&gt;
  &lt;/gresource&gt;
&lt;/gresources&gt;
</programlisting>
<!-- end inserted example code -->
        </sect2>
  </sect1>
  <!--
  <sect1 id="sec-drawing-fill">
      <title>Gradients and other fill techniques</title>
      <warning>TODO: Add content.</warning>
  </sect1>
  <sect1 id="sec-drawing-transformations">
      <title>Transformations with Cairo</title>
      <warning>TODO: Add content.</warning>
  </sect1>
  -->
  <sect1 id="sec-drawing-clock-example">
      <title lang="en">Example Application: Creating a Clock with Cairo</title>
      <para lang="en">
          Now that we've covered the basics of drawing with Cairo, let's try to
          put it all together and create a simple application that actually
          does something. The following example uses Cairo to create a custom
          <classname>Clock</classname> widget. The clock has a second hand, a
          minute hand, and an hour hand, and updates itself every second.
      </para>
      <screenshot>
          <graphic format="PNG" fileref="figures/cairo_clock.png"/>
      </screenshot>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drawingarea/clock?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>clock.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_CLOCK_H
#define GTKMM_EXAMPLE_CLOCK_H

#include &lt;gtkmm/drawingarea.h&gt;

class Clock : public Gtk::DrawingArea
{
public:
  Clock();
  virtual ~Clock();

protected:
  //Override default signal handler:
  virtual bool on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr);

  bool on_timeout();

  double m_radius;
  double m_line_width;

};

#endif // GTKMM_EXAMPLE_CLOCK_H
</programlisting>
<para lang="en">File: <filename>clock.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;ctime&gt;
#include &lt;cmath&gt;
#include &lt;cairomm/context.h&gt;
#include &lt;glibmm/main.h&gt;
#include "clock.h"

Clock::Clock()
: m_radius(0.42), m_line_width(0.05)
{
  Glib::signal_timeout().connect( sigc::mem_fun(*this, &amp;Clock::on_timeout), 1000 );

  #ifndef GLIBMM_DEFAULT_SIGNAL_HANDLERS_ENABLED
  //Connect the signal handler if it isn't already a virtual method override:
  signal_draw().connect(sigc::mem_fun(*this, &amp;Clock::on_draw), false);
  #endif //GLIBMM_DEFAULT_SIGNAL_HANDLERS_ENABLED
}

Clock::~Clock()
{
}

bool Clock::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  Gtk::Allocation allocation = get_allocation();
  const int width = allocation.get_width();
  const int height = allocation.get_height();

  // scale to unit square and translate (0, 0) to be (0.5, 0.5), i.e.
  // the center of the window
  cr-&gt;scale(width, height);
  cr-&gt;translate(0.5, 0.5);
  cr-&gt;set_line_width(m_line_width);

  cr-&gt;save();
  cr-&gt;set_source_rgba(0.337, 0.612, 0.117, 0.9);   // green
  cr-&gt;paint();
  cr-&gt;restore();
  cr-&gt;arc(0, 0, m_radius, 0, 2 * M_PI);
  cr-&gt;save();
  cr-&gt;set_source_rgba(1.0, 1.0, 1.0, 0.8);
  cr-&gt;fill_preserve();
  cr-&gt;restore();
  cr-&gt;stroke_preserve();
  cr-&gt;clip();

  //clock ticks
  for (int i = 0; i &lt; 12; i++)
  {
    double inset = 0.05;

    cr-&gt;save();
    cr-&gt;set_line_cap(Cairo::LINE_CAP_ROUND);

    if(i % 3 != 0)
    {
      inset *= 0.8;
      cr-&gt;set_line_width(0.03);
    }

    cr-&gt;move_to(
      (m_radius - inset) * cos (i * M_PI / 6),
      (m_radius - inset) * sin (i * M_PI / 6));
    cr-&gt;line_to (
      m_radius * cos (i * M_PI / 6),
      m_radius * sin (i * M_PI / 6));
    cr-&gt;stroke();
    cr-&gt;restore(); /* stack-pen-size */
  }

  // store the current time
  time_t rawtime;
  time(&amp;rawtime);
  struct tm * timeinfo = localtime (&amp;rawtime);

  // compute the angles of the indicators of our clock
  double minutes = timeinfo-&gt;tm_min * M_PI / 30;
  double hours = timeinfo-&gt;tm_hour * M_PI / 6;
  double seconds= timeinfo-&gt;tm_sec * M_PI / 30;

  cr-&gt;save();
  cr-&gt;set_line_cap(Cairo::LINE_CAP_ROUND);

  // draw the seconds hand
  cr-&gt;save();
  cr-&gt;set_line_width(m_line_width / 3);
  cr-&gt;set_source_rgba(0.7, 0.7, 0.7, 0.8); // gray
  cr-&gt;move_to(0, 0);
  cr-&gt;line_to(sin(seconds) * (m_radius * 0.9),
    -cos(seconds) * (m_radius * 0.9));
  cr-&gt;stroke();
  cr-&gt;restore();

  // draw the minutes hand
  cr-&gt;set_source_rgba(0.117, 0.337, 0.612, 0.9);   // blue
  cr-&gt;move_to(0, 0);
  cr-&gt;line_to(sin(minutes + seconds / 60) * (m_radius * 0.8),
    -cos(minutes + seconds / 60) * (m_radius * 0.8));
  cr-&gt;stroke();

  // draw the hours hand
  cr-&gt;set_source_rgba(0.337, 0.612, 0.117, 0.9);   // green
  cr-&gt;move_to(0, 0);
  cr-&gt;line_to(sin(hours + minutes / 12.0) * (m_radius * 0.5),
    -cos(hours + minutes / 12.0) * (m_radius * 0.5));
  cr-&gt;stroke();
  cr-&gt;restore();

  // draw a little dot in the middle
  cr-&gt;arc(0, 0, m_line_width / 3.0, 0, 2 * M_PI);
  cr-&gt;fill();

  return true;
}


bool Clock::on_timeout()
{
    // force our program to redraw the entire clock.
    Glib::RefPtr&lt;Gdk::Window&gt; win = get_window();
    if (win)
    {
        Gdk::Rectangle r(0, 0, get_allocation().get_width(),
                get_allocation().get_height());
        win-&gt;invalidate_rect(r, false);
    }
    return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "clock.h"
#include &lt;gtkmm/application.h&gt;
#include &lt;gtkmm/window.h&gt;

int main(int argc, char** argv)
{
   Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

   Gtk::Window win;
   win.set_title("Cairomm Clock");

   Clock c;
   win.add(c);
   c.show();

   return app-&gt;run(win);
}
</programlisting>
<!-- end inserted example code -->
      <para lang="en">
          As before, almost all of the interesting stuff is done in the draw
          signal handler <methodname>on_draw()</methodname>. Before we dig
          into the draw signal handler, notice that the constructor for the
          <classname>Clock</classname> widget connects a handler function
          <methodname>on_timeout()</methodname> to a timer with a timeout
          period of 1000 milliseconds (1 second). This means that
          <methodname>on_timeout()</methodname> will get called once per
          second. The sole responsibility of this function is to invalidate
          the window so that <application>gtkmm</application> will be forced to redraw it.
      </para>
      <para lang="en">
          Now let's take a look at the code that performs the actual drawing.
          The first section of <methodname>on_draw()</methodname> should be
          pretty familiar by now. This example again scales the coordinate system
          to be a unit square so that it's easier to draw the clock as a
          percentage of window size so that it will automatically scale when
          the window size is adjusted. Furthermore, the coordinate system is
          scaled over and down so that the (0, 0) coordinate is in the very
          center of the window.
      </para>
      <para lang="en">
          The function <methodname>Cairo::Context::paint()</methodname> is used here
          to set the background color of the window. This function takes no
          arguments and fills the current surface (or the clipped portion of
          the surface) with the source color currently active. After setting
          the background color of the window, we draw a circle for the clock
          outline, fill it with white, and then stroke the outline in black.
          Notice that both of these actions use the
          <methodname>_preserve</methodname> variant to preserve the current path,
          and then this same path is clipped to make sure that our next lines
          don't go outside the outline of the clock.
      </para>
      <para lang="en">
          After drawing the outline, we go around the clock and draw ticks for
          every hour, with a larger tick at 12, 3, 6, and 9. Now we're finally
          ready to implement the time-keeping functionality of the clock, which
          simply involves getting the current values for hours, minutes and
          seconds, and drawing the hands at the correct angles.
      </para>
  </sect1>
</chapter>

<chapter id="chapter-draganddrop">
<title>Arrastar e soltar</title>
<para lang="en">
<classname>Gtk::Widget</classname> has several methods and signals which are
prefixed with "drag_". These are used for Drag and Drop.
</para>
<sect1 id="sec-dnd-sources-destinations">
<title>Origens e destinos</title>
<para lang="en">
Things are dragged from <literal>sources</literal> to be dropped on
<literal>destinations</literal>. Each source and destination has infomation
about the data formats that it can send or receive, provided by
<classname>Gtk::TargetEntry</classname> items. A drop destination will only
accept a dragged item if they both share a compatible
<classname>Gtk::TargetEntry</classname> item. Appropriate signals will then be
emitted, telling the signal handlers which
<classname>Gtk::TargetEntry</classname> was used.
</para>
<para lang="en">
<classname>Gtk::TargetEntry</classname> objects contain this information:
<itemizedlist>
<listitem><para lang="en">target: A name, such as "STRING"</para></listitem>
<listitem><para lang="en">info: An identifier which will be sent to your signals to tell you which TargetEntry was used.</para></listitem>
<listitem><para lang="en">flags: Used only for drag and drop, this specifies whether the data may be dragged to other widgets and applications, or only to the same ones.</para></listitem>
</itemizedlist>
</para>

</sect1>

<sect1 id="sec-dnd-methods">
<title>Métodos</title>
<para lang="en">
<classname>Widget</classname>s can be identified as sources or destinations
using these <classname>Gtk::Widget</classname> methods:
</para>
<programlisting lang="en">void drag_source_set(const std::vector&lt;Gtk::TargetEntry&gt;&amp; targets,
      Gdk::ModifierType start_button_mask, Gdk::DragAction actions);</programlisting>

<itemizedlist>
<listitem>
    <para lang="en">
        <literal>targets</literal> is a vector of
        <classname>Gtk::TargetEntry</classname> elements.
    </para>
</listitem>
<listitem>
    <para lang="en">
        <literal>start_button_mask</literal> is an ORed combination of values,
        which specify which modifier key or mouse button must be pressed to
        start the drag.
    </para>
</listitem>
<listitem>
    <para lang="en">
        <literal>actions</literal> is an ORed combination of values, which
        specified which Drag and Drop operations will be possible from this
        source - for instance, copy, move, or link. The user can choose between
        the actions by using modifier keys, such as <keycap>Shift</keycap> to
        change from <literal>copy</literal> to <literal>move</literal>, and
        this will be shown by a different cursor.
    </para>
</listitem>
</itemizedlist>

<programlisting lang="en">void drag_dest_set(const std::vector&lt;Gtk::TargetEntry&gt;&amp; targets,
    Gtk::DestDefaults flags, Gdk::DragAction actions);</programlisting>

<itemizedlist>
<listitem>
    <para lang="en">
        <literal>flags</literal> is an ORed combination of values which
        indicates how the widget will respond visually to Drag and Drop items.
    </para>
</listitem>
<listitem>
    <para lang="en">
        <literal>actions</literal> indicates the Drag and Drop actions which
        this destination can receive - see the description above.
    </para>
</listitem>
</itemizedlist>
</sect1>

<sect1 id="sec-dnd-signals">
<title>Sinais</title>
<para lang="en">
When a drop destination has accepted a dragged item, certain signals will be
emitted, depending on what action has been selected. For instance, the user
might have held down the <keycap>Shift</keycap> key to specify a
<literal>move</literal> rather than a <literal>copy</literal>. Remember that
the user can only select the actions which you have specified in your calls to
<methodname>drag_dest_set()</methodname> and
<methodname>drag_source_set()</methodname>.
</para>

<sect2 id="sec-dnd-signals-copy">
<title>Copiar</title>
<para lang="en">
The source widget will emit these signals, in this order:
<itemizedlist>
<listitem><para lang="en"><literal>drag_begin</literal>: Provides DragContext.</para></listitem>
<listitem><para lang="en"><literal>drag_data_get</literal>: Provides <literal>info</literal> about the dragged data format, and a <literal>Gtk::SelectionData</literal> structure, in which you should put the requested data.</para></listitem>
<listitem><para lang="en"><literal>drag_end</literal>: Provides DragContext.</para></listitem>
</itemizedlist>
</para>
<para lang="en">
The destination widget will emit these signals, in this order:
<itemizedlist>
<listitem><para lang="en"><literal>drag_motion</literal>: Provides DragContext and coordinates.
  You can call the <methodname>drag_status()</methodname> method of the DragContext
  to indicate which action will be accepted.</para></listitem>
<listitem><para lang="en"><literal>drag_drop</literal>: Provides DragContext and coordinates.
  You can call <methodname>drag_get_data()</methodname>, which triggers the
  <literal>drag_data_get</literal> signal in the source widget, and then the
  <literal>drag_data_received</literal> signal in the destination widget.</para></listitem>
<listitem>
    <para lang="en">
        <literal>drag_data_received</literal>: Provides <literal>info</literal>
        about the dragged data format, and a
        <literal>Gtk::SelectionData</literal> structure which contains the
        dropped data. You should  call the <methodname>drag_finish()</methodname>
        method of the <literal>DragContext</literal> to indicate whether the
        operation was successful.
    </para>
</listitem>
</itemizedlist>
</para>

</sect2>

<sect2 id="dnd-signal-move">
<title>Mover</title>
<para lang="en">During a <literal>move</literal>, the source widget will also emit this signal:
<itemizedlist>
<listitem><para lang="en"><literal>drag_data_delete</literal>: Gives the source the opportunity to delete the original data if that's appropriate.</para></listitem>
</itemizedlist>
</para>
</sect2>

<!--
<sect2 id="dnd-signal-link">
<title>Link</title>
<para>TODO: Find an example or documentation.</para>
</sect2>
-->
</sect1>

<sect1 id="sec-dragcontext">
<title lang="en">DragContext</title>
<para lang="en">
The drag and drop signals provide a DragContext, which contains some
information about the drag and drop operation and can be used to influence the
process. For instance, you can discover the source widget, or  change the drag
and drop icon, by using the <methodname>set_icon()</methodname> methods. More
importantly, you should call the <methodname>drag_finish()</methodname> method from
your <literal>drag_data_received</literal> signal handler to indicate whether
the drop was successful.
</para>
</sect1>

<sect1 id="sec-dnd-example">
<title>Exemplo</title>
<para lang="en">Here is a very simple example, demonstrating a drag and drop <literal>Copy</literal> operation:</para>

<figure id="figure-drag-and-drop">
  <title>Arrastar e soltar</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/drag_and_drop.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/drag_and_drop?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>dndwindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_DNDWINDOW_H
#define GTKMM_EXAMPLE_DNDWINDOW_H

#include &lt;gtkmm/box.h&gt;
#include &lt;gtkmm/label.h&gt;
#include &lt;gtkmm/window.h&gt;
#include &lt;gtkmm/button.h&gt;

class DnDWindow : public Gtk::Window
{

public:
  DnDWindow();
  virtual ~DnDWindow();

protected:
  //Signal handlers:
  void on_button_drag_data_get(
          const Glib::RefPtr&lt;Gdk::DragContext&gt;&amp; context,
          Gtk::SelectionData&amp; selection_data, guint info, guint time);
  void on_label_drop_drag_data_received(
          const Glib::RefPtr&lt;Gdk::DragContext&gt;&amp; context, int x, int y,
          const Gtk::SelectionData&amp; selection_data, guint info, guint time);

  //Member widgets:
  Gtk::Box m_HBox;
  Gtk::Button m_Button_Drag;
  Gtk::Label m_Label_Drop;
};

#endif // GTKMM_EXAMPLE_DNDWINDOW_H
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "dndwindow.h"
#include &lt;gtkmm/application.h&gt;

int main (int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  DnDWindow dndWindow;

  //Shows the window and returns when it is closed.
  return app-&gt;run(dndWindow);
}
</programlisting>
<para lang="en">File: <filename>dndwindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "dndwindow.h"
#include &lt;iostream&gt;

DnDWindow::DnDWindow()
: m_Button_Drag("Drag Here\n"),
  m_Label_Drop("Drop here\n")
{
  set_title("DnD example");

  add(m_HBox);

  //Targets:
  std::vector&lt;Gtk::TargetEntry&gt; listTargets;
  listTargets.push_back( Gtk::TargetEntry("STRING") );
  listTargets.push_back( Gtk::TargetEntry("text/plain") );

  //Drag site:

  //Make m_Button_Drag a DnD drag source:
  m_Button_Drag.drag_source_set(listTargets);

  //Connect signals:
  m_Button_Drag.signal_drag_data_get().connect(sigc::mem_fun(*this,
              &amp;DnDWindow::on_button_drag_data_get));

  m_HBox.pack_start(m_Button_Drag);

  //Drop site:

  //Make m_Label_Drop a DnD drop destination:
  m_Label_Drop.drag_dest_set(listTargets);

  //Connect signals:
  m_Label_Drop.signal_drag_data_received().connect(sigc::mem_fun(*this,
              &amp;DnDWindow::on_label_drop_drag_data_received) );

  m_HBox.pack_start(m_Label_Drop);

  show_all();
}

DnDWindow::~DnDWindow()
{
}

void DnDWindow::on_button_drag_data_get(
        const Glib::RefPtr&lt;Gdk::DragContext&gt;&amp;,
        Gtk::SelectionData&amp; selection_data, guint, guint)
{
  selection_data.set(selection_data.get_target(), 8 /* 8 bits format */,
          (const guchar*)"I'm Data!",
          9 /* the length of I'm Data! in bytes */);
}

void DnDWindow::on_label_drop_drag_data_received(
        const Glib::RefPtr&lt;Gdk::DragContext&gt;&amp; context, int, int,
        const Gtk::SelectionData&amp; selection_data, guint, guint time)
{
  const int length = selection_data.get_length();
  if((length &gt;= 0) &amp;&amp; (selection_data.get_format() == 8))
  {
    std::cout &lt;&lt; "Received \"" &lt;&lt; selection_data.get_data_as_string()
        &lt;&lt; "\" in label " &lt;&lt; std::endl;
  }

  context-&gt;drag_finish(false, false, time);
}
</programlisting>
<!-- end inserted example code -->

<para lang="en">
There is a more complex example in examples/others/dnd.
</para>

</sect1>

</chapter>

<chapter id="chapter-clipboard">
<title>Área de transferência</title>
<para lang="en">Simple text copy-paste functionality is provided for free by widgets such as
<classname>Gtk::Entry</classname> and <classname>Gtk::TextView</classname>,
but you might need special code to deal with your own data formats. For instance,
a drawing program would need special code to allow copy and paste within a view,
or between documents.</para>

<para lang="en">
You can usually pretend that <classname>Gtk::Clipboard</classname> is a singleton.
You can get the default clipboard instance with <methodname>Gtk::Clipboard::get()</methodname>.
This is probably the only clipboard you will ever need.
</para>

<para lang="en">
Your application doesn't need to wait for clipboard operations, particularly
between the time when the user chooses Copy and then later chooses Paste. Most
<classname>Gtk::Clipboard</classname> methods take
<classname>sigc::slot</classname>s which specify callback methods. When
<classname>Gtk::Clipboard</classname> is ready, it will call these methods,
either providing the requested data, or asking for data.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1Clipboard.html">Reference</ulink></para>

<sect1 id="sec-clipboard-targets">
<title>Alvos</title>
<para lang="en">
Different applications contain different types of data, and they might make that data available in
a variety of formats. <application>gtkmm</application> calls these data types <literal>target</literal>s.</para>

<para lang="en">
For instance, <application>gedit</application> can supply and receive the <literal>"UTF8_STRING"</literal>
target, so you can paste data into <application>gedit</application> from any application that supplies that target.
Or two different image editing applications might supply and receive a variety of image formats as targets.
As long as one application can receive one of the targets that the other supplies then you will be able to copy data from one to the other.
</para>

<para lang="en">
A target can be in a variety of binary formats. This chapter, and the examples,
assume that the data is 8-bit text. This would allow us to use an XML format
for the clipboard data. However this would probably not be appropriate for
binary data such as images. <classname>Gtk::Clipboard</classname> provides
overloads that allow you to specify the format in more detail if
necessary.
</para>

<para lang="en">The <link linkend="chapter-draganddrop">Drag and Drop</link> API uses the same mechanism.
You should probably use the same data targets and formats for both Clipboard and Drag and Drop operations.</para>
</sect1>

<sect1 id="sec-clipboard-copy">
<title>Copiar</title>
<para lang="en">
When the user asks to copy some data, you should tell the
<classname>Clipboard</classname> what targets are available, and provide the
callback methods that it can use to get the data. At this point you should
store a copy of the data, to be provided when the clipboard calls your callback
method in response to a paste.
</para>
<para>Por exemplo,</para>
<programlisting lang="en">Glib::RefPtr&lt;Gtk::Clipboard&gt; refClipboard = Gtk::Clipboard::get();

//Targets:
std::vector&lt;Gtk::TargetEntry&gt; targets;
targets.push_back( Gtk::TargetEntry("example_custom_target") );
targets.push_back( Gtk::TargetEntry("UTF8_STRING") );

refClipboard-&gt;set( targets,
    sigc::mem_fun(*this, &amp;ExampleWindow::on_clipboard_get),
    sigc::mem_fun(*this, &amp;ExampleWindow::on_clipboard_clear) );</programlisting>

<para lang="en">Your callback will then provide the stored data when the user chooses to paste the data. For instance:
</para>
<programlisting lang="en">void ExampleWindow::on_clipboard_get(
    Gtk::SelectionData&amp; selection_data, guint /* info */)
{
  const std::string target = selection_data.get_target();

  if(target == "example_custom_target")
    selection_data.set("example_custom_target", m_ClipboardStore);
}</programlisting>
<para lang="en">
The <literal>ideal</literal> example below can supply more than one clipboard target.
</para>

<para lang="en">The clear callback allows you to free the memory used by your stored data when the clipboard replaces its data with something else.
</para>

</sect1>

<sect1 id="sec-clipboard-paste">
<title>Colar</title>
<para lang="en">
When the user asks to paste data from the <classname>Clipboard</classname>, you
should request a specific format and provide a callback method which will be
called with the actual data. For instance:
</para>
<programlisting lang="en">refClipboard-&gt;request_contents("example_custom_target",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_clipboard_received) );</programlisting>

<para lang="en">Here is an example callback method:
</para>
<programlisting lang="en">void ExampleWindow::on_clipboard_received(
    const Gtk::SelectionData&amp; selection_data)
{
  Glib::ustring clipboard_data = selection_data.get_data_as_string();
  //Do something with the pasted data.
}</programlisting>

<sect2 id="dnd-discovering-targets">
<title>Descobrindo os alvos disponíveis</title>
<para lang="en">
To find out what targets are currently available on the
<classname>Clipboard</classname> for pasting, call the
<methodname>request_targets()</methodname> method, specifying a method to be called
with the information. For instance:
</para>
<programlisting lang="en">refClipboard-&gt;request_targets( sigc::mem_fun(*this,
    &amp;ExampleWindow::on_clipboard_received_targets) );</programlisting>

<para lang="en">
In your callback, compare the vector of available targets with those that your application supports for pasting. You could enable or disable a Paste menu item, depending on whether pasting is currently possible. For instance:
</para>
<programlisting lang="en">void ExampleWindow::on_clipboard_received_targets(
  const std::vector&lt;Glib::ustring&gt;&amp; targets)
{
  const bool bPasteIsPossible =
    std::find(targets.begin(), targets.end(),
      example_target_custom) != targets.end();

  // Enable/Disable the Paste button appropriately:
  m_Button_Paste.set_sensitive(bPasteIsPossible);
}</programlisting>
</sect2>

</sect1>

<sect1 id="sec-clipboard-examples"><title lang="en">Examples</title>

<sect2 id="sec-clipboard-example-simple"><title>Simples</title>
<para lang="en">
This example allows copy and pasting of application-specific data, using the
standard text target. Although this is simple, it's not ideal because it does
not identify the <classname>Clipboard</classname> data as being of a particular
type.
</para>

<figure id="figure-clipboard-simple">
  <title>Área de transferência - Simples</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/clipboard_simple.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/clipboard/simple/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_copy();
  void on_button_paste();
  void on_clipboard_text_received(const Glib::ustring&amp; text);

  //Child widgets:
  Gtk::Box m_VBox;

  Gtk::Label m_Label;
  
  Gtk::Grid m_Grid;
  Gtk::ToggleButton m_ButtonA1, m_ButtonA2, m_ButtonB1, m_ButtonB2;

  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Copy, m_Button_Paste;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Label("Select cells in the grid, click Copy, then open a second "
        "instance of this example to try pasting the copied data."),
  m_ButtonA1("A1"), m_ButtonA2("A2"), m_ButtonB1("B1"), m_ButtonB2("B2"),
  m_Button_Copy("_Copy", /* mnemonic= */ true), m_Button_Paste("_Paste", true)
{
  set_title("Gtk::Clipboard example");
  set_border_width(12);

  add(m_VBox);

  m_VBox.pack_start(m_Label, Gtk::PACK_SHRINK);

  //Fill Grid:
  m_VBox.pack_start(m_Grid);
  m_Grid.set_row_homogeneous(true);
  m_Grid.set_column_homogeneous(true);
  m_Grid.attach(m_ButtonA1, 0, 0, 1, 1);
  m_Grid.attach(m_ButtonA2, 1, 0, 1, 1);
  m_Grid.attach(m_ButtonB1, 0, 1, 1, 1);
  m_Grid.attach(m_ButtonB2, 1, 1, 1, 1);

  //Add ButtonBox to bottom:
  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
  m_VBox.set_spacing(6);

  //Fill ButtonBox:
  m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
  m_ButtonBox.pack_start(m_Button_Copy, Gtk::PACK_SHRINK);
  m_Button_Copy.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_copy) );
  m_ButtonBox.pack_start(m_Button_Paste, Gtk::PACK_SHRINK);
  m_Button_Paste.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_paste) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_copy()
{
  //Build a string representation of the stuff to be copied:
  //Ideally you would use XML, with an XML parser here:
  Glib::ustring strData;
  strData += m_ButtonA1.get_active() ? "1" : "0";
  strData += m_ButtonA2.get_active() ? "1" : "0";
  strData += m_ButtonB1.get_active() ? "1" : "0";
  strData += m_ButtonB2.get_active() ? "1" : "0";

  Glib::RefPtr&lt;Gtk::Clipboard&gt; refClipboard = Gtk::Clipboard::get();
  refClipboard-&gt;set_text(strData);
}

void ExampleWindow::on_button_paste()
{
  //Tell the clipboard to call our method when it is ready:
  Glib::RefPtr&lt;Gtk::Clipboard&gt; refClipboard = Gtk::Clipboard::get();
  refClipboard-&gt;request_text(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_clipboard_text_received) );
}

void ExampleWindow::on_clipboard_text_received(const Glib::ustring&amp; text)
{
  //See comment in on_button_copy() about this silly clipboard format.
  if(text.size() &gt;= 4)
  {
    m_ButtonA1.set_active( text[0] == '1' );
    m_ButtonA2.set_active( text[1] == '1' );
    m_ButtonB1.set_active( text[2] == '1' );
    m_ButtonB2.set_active( text[3] == '1' );
  }
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  //APPLICATION_NON_UNIQUE because it shall be possible to run several
  //instances of this application simultaneously.
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(
    argc, argv, "org.gtkmm.example", Gio::APPLICATION_NON_UNIQUE);

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

<sect2 id="sec-clipboard-example-ideal"><title>Ideal</title>
<para lang="en">This is like the simple example, but it
<orderedlist>
<listitem><simpara lang="en">Defines a custom clipboard target, though the format of that target is still text.</simpara></listitem>
<listitem><simpara lang="en">It supports pasting of 2 targets - both the custom one and a text one that creates an arbitrary text representation of the custom data.</simpara></listitem>
<listitem><simpara lang="en">It uses <methodname>request_targets()</methodname> and the <literal>owner_change</literal> signal and disables the Paste button if it can't use anything on the clipboard.</simpara></listitem>
</orderedlist>
</para>

<figure id="figure-clipboard-ideal">
  <title>Área de transferência - Ideal</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/clipboard_ideal.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/clipboard/ideal/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_copy();
  void on_button_paste();

  void on_clipboard_owner_change(GdkEventOwnerChange* event);
  void on_clipboard_get(Gtk::SelectionData&amp; selection_data, guint info);
  void on_clipboard_clear();

  void on_clipboard_received(const Gtk::SelectionData&amp; selection_data);
  void on_clipboard_received_targets(const std::vector&lt;Glib::ustring&gt;&amp; targets);
   
  virtual void update_paste_status(); //Disable the paste button if there is nothing to paste.

  //Child widgets:
  Gtk::Box m_VBox;

  Gtk::Label m_Label;
  
  Gtk::Grid m_Grid;
  Gtk::ToggleButton m_ButtonA1, m_ButtonA2, m_ButtonB1, m_ButtonB2;

  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Copy, m_Button_Paste;

  Glib::ustring m_ClipboardStore; //Keep copied stuff here, until it is pasted. This could be a big complex data structure.
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;algorithm&gt;

namespace
{

//These should usually be MIME types.
const char example_target_custom[] = "gtkmmclipboardexample";
const char example_target_text[]   = "UTF8_STRING";

} // anonymous namespace


ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Label("Select cells in the grid, click Copy, then open a second instance "
          "of this example to try pasting the copied data.\nOr try pasting the "
          "text representation into gedit."),
  m_ButtonA1("A1"), m_ButtonA2("A2"), m_ButtonB1("B1"), m_ButtonB2("B2"),
  m_Button_Copy("_Copy", /* mnemonic= */ true), m_Button_Paste("_Paste", true)
{
  set_title("Gtk::Clipboard example");
  set_border_width(12);

  add(m_VBox);

  m_VBox.pack_start(m_Label, Gtk::PACK_SHRINK);

  //Fill Grid:
  m_VBox.pack_start(m_Grid);
  m_Grid.set_row_homogeneous(true);
  m_Grid.set_column_homogeneous(true);
  m_Grid.attach(m_ButtonA1, 0, 0, 1, 1);
  m_Grid.attach(m_ButtonA2, 1, 0, 1, 1);
  m_Grid.attach(m_ButtonB1, 0, 1, 1, 1);
  m_Grid.attach(m_ButtonB2, 1, 1, 1, 1);

  //Add ButtonBox to bottom:
  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
  m_VBox.set_spacing(6);

  //Fill ButtonBox:
  m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
  m_ButtonBox.pack_start(m_Button_Copy, Gtk::PACK_SHRINK);
  m_Button_Copy.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_copy) );
  m_ButtonBox.pack_start(m_Button_Paste, Gtk::PACK_SHRINK);
  m_Button_Paste.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_paste) );

  //Connect a signal handler that will be called when the contents of
  //the clipboard change.
  Gtk::Clipboard::get()-&gt;signal_owner_change().connect(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_clipboard_owner_change) );

  show_all_children();

  update_paste_status();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_copy()
{
  //Build a string representation of the stuff to be copied:
  //Ideally you would use XML, with an XML parser here:
  Glib::ustring strData;
  strData += m_ButtonA1.get_active() ? "1" : "0";
  strData += m_ButtonA2.get_active() ? "1" : "0";
  strData += m_ButtonB1.get_active() ? "1" : "0";
  strData += m_ButtonB2.get_active() ? "1" : "0";

  Glib::RefPtr&lt;Gtk::Clipboard&gt; refClipboard = Gtk::Clipboard::get();

  //Targets:
  std::vector&lt;Gtk::TargetEntry&gt; targets;

  targets.push_back( Gtk::TargetEntry(example_target_custom) );
  targets.push_back( Gtk::TargetEntry(example_target_text) );

  refClipboard-&gt;set(targets,
    sigc::mem_fun(*this, &amp;ExampleWindow::on_clipboard_get),
    sigc::mem_fun(*this, &amp;ExampleWindow::on_clipboard_clear) );

  //Store the copied data until it is pasted:
  //(Must be done after the call to refClipboard-&gt;set(), because that call
  //may trigger a call to on_clipboard_clear.)
  m_ClipboardStore = strData;

  update_paste_status();
}

void ExampleWindow::on_button_paste()
{
  //Tell the clipboard to call our method when it is ready:
  Glib::RefPtr&lt;Gtk::Clipboard&gt; refClipboard = Gtk::Clipboard::get();

  refClipboard-&gt;request_contents(example_target_custom, 
    sigc::mem_fun(*this, &amp;ExampleWindow::on_clipboard_received) );

  update_paste_status();
}

void ExampleWindow::on_clipboard_owner_change(GdkEventOwnerChange*)
{
  update_paste_status();
}

void ExampleWindow::on_clipboard_get(Gtk::SelectionData&amp; selection_data,
  guint /* info */)
{
  // info corresponds to the optional info parameter in Gtk::TargetEntry's
  // constructor. We don't use that, so we use selection_data's target instead.

  const std::string target = selection_data.get_target();

  if(target == example_target_custom)
  {
    // This set() override uses an 8-bit text format for the data.
    selection_data.set(example_target_custom, m_ClipboardStore);
  }
  else if(target == example_target_text)
  {
    //Build some arbitrary text representation of the data,
    //so that people see something when they paste into a text editor:
    Glib::ustring text_representation;

    text_representation += m_ButtonA1.get_active() ? "A1, " : "";
    text_representation += m_ButtonA2.get_active() ? "A2, " : "";
    text_representation += m_ButtonB1.get_active() ? "B1, " : "";
    text_representation += m_ButtonB2.get_active() ? "B2, " : "";

    selection_data.set_text(text_representation);
  }
  else
  {
    g_warning("ExampleWindow::on_clipboard_get(): "
            "Unexpected clipboard target format.");
  }
}

void ExampleWindow::on_clipboard_clear()
{
  //This isn't really necessary. I guess it might save memory.
  m_ClipboardStore.clear();
}

void ExampleWindow::on_clipboard_received(
        const Gtk::SelectionData&amp; selection_data)
{
  const std::string target = selection_data.get_target();

  //It should always be this, because that's what we asked for when calling
  //request_contents().
  if(target == example_target_custom)
  {
    Glib::ustring clipboard_data = selection_data.get_data_as_string();

    //See comment in on_button_copy() about this silly clipboard format.
    if(clipboard_data.size() &gt;= 4)
    {
      m_ButtonA1.set_active( clipboard_data[0] == '1' );
      m_ButtonA2.set_active( clipboard_data[1] == '1' );
      m_ButtonB1.set_active( clipboard_data[2] == '1' );
      m_ButtonB2.set_active( clipboard_data[3] == '1' );
    }
  }
}

void ExampleWindow::update_paste_status()
{
  //Disable the paste button if there is nothing to paste.

  Glib::RefPtr&lt;Gtk::Clipboard&gt; refClipboard = Gtk::Clipboard::get();

  //Discover what targets are available:
  refClipboard-&gt;request_targets(sigc::mem_fun(*this,
              &amp;ExampleWindow::on_clipboard_received_targets) );
}

void ExampleWindow::on_clipboard_received_targets(
  const std::vector&lt;Glib::ustring&gt;&amp; targets)
{
  const bool bPasteIsPossible =
    std::find(targets.begin(), targets.end(),
      example_target_custom) != targets.end();

  // Enable/Disable the Paste button appropriately:
  m_Button_Paste.set_sensitive(bPasteIsPossible);
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  //APPLICATION_NON_UNIQUE because it shall be possible to run several
  //instances of this application simultaneously.
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(
    argc, argv, "org.gtkmm.example", Gio::APPLICATION_NON_UNIQUE);

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->

</sect2>

</sect1>


</chapter>

<chapter id="chapter-printing">
<title>Imprimindo</title>

<para lang="en">
At the application development level, <application>gtkmm</application>'s printing API
provides dialogs that are consistent across applications and allows use of Cairo's common drawing API, with Pango-driven text rendering. In the implementation of this common API, platform-specific backends and printer-specific drivers are used.
</para>

<sect1 id="sec-printoperation">
<title lang="en">PrintOperation</title>

<para lang="en">
The primary object is <classname>Gtk::PrintOperation</classname>, allocated
for each print operation. To handle page drawing connect to its signals,
or inherit from it and override the default virtual signal handlers.
<classname>PrintOperation</classname> automatically handles all the settings
affecting the print loop.
</para>

<sect2 id="sec-printoperation-signals">
<title>Sinais</title>

<para lang="en">
The <methodname>PrintOperation::run()</methodname> method starts the print loop,
during which various signals are emitted:

<itemizedlist>
  <listitem>
    <para lang="en">
      <literal>begin_print</literal>:
      You must handle this signal, because this is where you
      create and set up a <classname>Pango::Layout</classname> using the
      provided <classname>Gtk::PrintContext</classname>, and break up your
      printing output into pages.
    </para>
  </listitem>

  <listitem>
    <para lang="en">
      <literal>paginate</literal>: Pagination is potentially slow so if you
      need to monitor it you can call the
      <methodname>PrintOperation::set_show_progress()</methodname> method and
      handle this signal.
    </para>
  </listitem>

  <listitem>
    <para lang="en">
      For each page that needs to be rendered, the following signals
      are emitted:
      <itemizedlist>
        <listitem>
          <para lang="en">
            <literal>request_page_setup</literal>: Provides a
            <classname>PrintContext</classname>, page number and
            <classname>Gtk::PageSetup</classname>. Handle this signal if you
            need to modify page setup on a per-page basis.
          </para>
        </listitem>

        <listitem>
          <para lang="en">
            <literal>draw_page</literal>: You must handle this signal, which provides a
            <classname>PrintContext</classname> and a page number.
            The <classname>PrintContext</classname> should be used
            to create a <classname>Cairo::Context</classname> into which
            the provided page should be drawn. To render text, iterate over
            the <classname>Pango::Layout</classname> you created in the
            <literal>begin_print</literal> handler.
          </para>
        </listitem>
      </itemizedlist>
    </para>
  </listitem>

  <listitem>
    <para lang="en">
      <literal>end_print</literal>: A handler for it is a safe place to free
      any resources related to a <classname>PrintOperation</classname>.
      If you have your custom class that inherits from
      <classname>PrintOperation</classname>, it is naturally simpler to do it
      in the destructor.
    </para>
  </listitem>

  <listitem>
    <para lang="en">
      <literal>done</literal>: This signal is emitted when printing is finished, meaning when the
      print data is spooled. Note that the provided
      <literal>Gtk::PrintOperationResult</literal> may indicate that
      an error occurred. In any case you probably want to notify the user
      about the final status.
    </para>
  </listitem>

  <listitem>
    <para lang="en">
      <literal>status_changed</literal>: Emitted whenever a print job's
      status changes, until it is finished. Call the
      <methodname>PrintOperation::set_track_print_status()</methodname> method to
      monitor the job status after spooling. To see the status, use
      <methodname>get_status()</methodname> or
      <methodname>get_status_string()</methodname>.
    </para>
  </listitem>
</itemizedlist>

</para>

<para lang="en">
<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1PrintOperation.html">Reference</ulink>
</para>

</sect2>

</sect1>

<sect1 id="sec-page-setup">
<title>Configurar página</title>

<para lang="en">
The <classname>PrintOperation</classname> class has a method called
<methodname>set_default_page_setup()</methodname> which selects the default
paper size, orientation and margins. To show a page setup dialog from your
application, use the <methodname>Gtk::run_page_setup_dialog()</methodname> method,
which returns a <classname>Gtk::PageSetup</classname> object with the chosen
settings. Use this object to update a <classname>PrintOperation</classname>
and to access the selected <classname>Gtk::PaperSize</classname>,
<literal>Gtk::PageOrientation</literal> and printer-specific margins.
</para>
<para lang="en">You should save the chosen <classname>Gtk::PageSetup</classname>
so you can use it again if the page setup dialog is shown again.</para>

<para lang="en">For instance,
<programlisting lang="en">
//Within a class that inherits from Gtk::Window and keeps m_refPageSetup and m_refSettings as members...
Glib::RefPtr&lt;Gtk::PageSetup&gt; new_page_setup = Gtk::run_page_setup_dialog(*this, m_refPageSetup, m_refSettings);
m_refPageSetup = new_page_setup;
</programlisting>
</para>

<para lang="en">
<ulink url="http://developer.gnome.org/gtkmm/unstable/classGtk_1_1PageSetup.html">Reference</ulink>
</para>

<para lang="en">
The Cairo coordinate system, in the <literal>draw_page</literal> handler,
is automatically rotated to the current page orientation. It is normally
within the printer margins, but you can change that via the
<methodname>PrintOperation::set_use_full_page()</methodname>
method. The default measurement unit is device pixels. To select other units,
use the <methodname>PrintOperation::set_unit()</methodname> method.
</para>

</sect1>

<sect1 id="sec-printing-rendering-text">
<title>Processamento de texto</title>

<para lang="en">
Text rendering is done using Pango.
The <classname>Pango::Layout</classname> object for printing should be created by calling
the <methodname>PrintContext::create_pango_layout()</methodname> method.
The <classname>PrintContext</classname> object also provides the page metrics,
via <methodname>get_width()</methodname> and <methodname>get_height()</methodname>.
The number of pages can be set with
<methodname>PrintOperation::set_n_pages()</methodname>. To actually render the
 Pango text in <literal>on_draw_page</literal>, get a
<classname>Cairo::Context</classname> with
<methodname>PrintContext::get_cairo_context()</methodname> and show the
<classname>Pango::LayoutLine</classname>s that appear within the requested
page number.
</para>

<para lang="en">
See <link linkend="sec-printing-example-simple">an example</link>
of exactly how this can be done.
</para>

</sect1>

<sect1 id="sec-async-printing-ops">
<title>Operações assíncronas</title>

<para lang="en">
By default, <methodname>PrintOperation::run()</methodname> returns when a print
operation is completed. If you need to run a non-blocking print operation,
call <methodname>PrintOperation::set_allow_async()</methodname>. Note that <methodname>set_allow_async()</methodname> is not supported
on all platforms, however the <literal>done</literal> signal will still be emitted.
</para>

<para lang="en">
<methodname>run()</methodname> may return
<literal>PRINT_OPERATION_RESULT_IN_PROGRESS</literal>. To track status
and handle the result or error you need to implement signal handlers for
the <literal>done</literal> and <literal>status_changed</literal> signals:
</para>

<para lang="en">For instance,
<programlisting lang="en">
// in class ExampleWindow's method...
Glib::RefPtr&lt;PrintOperation&gt; op = PrintOperation::create();
// ...set up op...
op-&gt;signal_done().connect(sigc::bind(sigc::mem_fun(*this, &amp;ExampleWindow::on_printoperation_done), op));
// run the op
</programlisting>
</para>

<para lang="en">Second, check for an error and connect to the <literal>status_changed</literal> signal. For instance:
<programlisting lang="en">
void ExampleWindow::on_printoperation_done(Gtk::PrintOperationResult result, const Glib::RefPtr&lt;PrintOperation&gt;&amp; op)
{
  if (result == Gtk::PRINT_OPERATION_RESULT_ERROR)
    //notify user
  else if (result == Gtk::PRINT_OPERATION_RESULT_APPLY)
    //Update PrintSettings with the ones used in this PrintOperation

  if (! op-&gt;is_finished())
    op-&gt;signal_status_changed().connect(sigc::bind(sigc::mem_fun(*this, &amp;ExampleWindow::on_printoperation_status_changed), op));
}
</programlisting>
</para>

<para lang="en">Finally, check the status. For instance,
<programlisting lang="en">
void ExampleWindow::on_printoperation_status_changed(const Glib::RefPtr&lt;PrintFormOperation&gt;&amp; op)
{
  if (op-&gt;is_finished())
    //the print job is finished
  else
    //get the status with get_status() or get_status_string()

  //update UI
}
</programlisting>
</para>

</sect1>

<sect1 id="sec-printing-export-to-pdf">
<title>Exportar para PDF</title>
<para lang="en">
The 'Print to file' option is available in the print dialog, without the need for extra implementation. However, it is sometimes useful to generate a pdf file directly from code. For instance,

<programlisting lang="en">
Glib::RefPtr&lt;Gtk::PrintOperation&gt; op = Gtk::PrintOperation::create();
// ...set up op...
op-&gt;set_export_filename("test.pdf");
Gtk::PrintOperationResult res = op-&gt;run(Gtk::PRINT_OPERATION_ACTION_EXPORT);
</programlisting>

</para>

</sect1>

<sect1 id="sec-extending-print-dialog">
<title>Estendendo o diálogo de impressão</title>

<para lang="en">
You may add a custom tab to the print dialog:

<itemizedlist>
  <listitem>
    <para lang="en">
      Set the title of the tab via
      <methodname>PrintOperation::set_custom_tab_label()</methodname>,
      create a new widget and return it from the
      <literal>create_custom_widget</literal> signal handler. You'll probably
      want this to be a container widget, packed with some others.
    </para>
  </listitem>

  <listitem>
    <para lang="en">
      Get the data from the widgets in the
      <literal>custom_widget_apply</literal> signal handler.
    </para>
  </listitem>
</itemizedlist>
</para>

<para lang="en">
Although the <literal>custom_widget_apply</literal> signal provides the widget you
previously created, to simplify things you can keep the widgets you expect
to contain some user input as class members. For example, let's say you have
a <classname>Gtk::Entry</classname> called <literal>m_Entry</literal> as
a member of your <classname>CustomPrintOperation</classname> class:

<programlisting lang="en">
Gtk::Widget* CustomPrintOperation::on_create_custom_widget()
{
  set_custom_tab_label("My custom tab");

  Gtk::Box* hbox = new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 8);
  hbox-&gt;set_border_width(6);

  Gtk::Label* label = Gtk::manage(new Gtk::Label("Enter some text: "));
  hbox-&gt;pack_start(*label, false, false);
  label-&gt;show();

  hbox-&gt;pack_start(m_Entry, false, false);
  m_Entry.show();

  return hbox;
}

void CustomPrintOperation::on_custom_widget_apply(Gtk::Widget* /* widget */)
{
  Glib::ustring user_input = m_Entry.get_text();
  //...
}
</programlisting>

</para>

<para lang="en">
The example in examples/book/printing/advanced demonstrates this.
</para>

</sect1>

<sect1 id="sec-printing-preview">
<title>Visualização</title>

<para lang="en">
The native GTK+ print dialog has a preview button, but you may also start
a preview directly from an application:

<programlisting lang="en">
// in a class that inherits from Gtk::Window...
Glib::RefPtr&lt;PrintOperation&gt; op = PrintOperation::create();
// ...set up op...
op-&gt;run(Gtk::PRINT_OPERATION_ACTION_PREVIEW, *this);
</programlisting>
</para>

<para lang="en">
On Unix, the default preview handler uses an external viewer program.
On Windows, the native preview dialog will be shown. If necessary you may
override this behaviour and provide a custom preview dialog. See the example
located in /examples/book/printing/advanced.
</para>

</sect1>

<sect1 id="sec-printing-example">
<title>Exemplo</title>

<sect2 id="sec-printing-example-simple">
<title>Simples</title>

<para lang="en">
The following example demonstrates how to print some input from a user
interface. It shows how to implement <literal>on_begin_print</literal>
and <literal>on_draw_page</literal>, as well as how to track print status
and update the print settings.
</para>

<figure id="figure-printing-simple">
  <title>Impressão - Simples</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/printing.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/printing/simple/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class PrintFormOperation;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:

  void build_main_menu();

  void print_or_preview(Gtk::PrintOperationAction print_action);

  //PrintOperation signal handlers.
  //We handle these so can get necessary information to update the UI or print settings.
  //Our derived PrintOperation class also overrides some default signal handlers.
  void on_printoperation_status_changed(const Glib::RefPtr&lt;PrintFormOperation&gt;&amp; operation);

  void on_printoperation_done(Gtk::PrintOperationResult result, const Glib::RefPtr&lt;PrintFormOperation&gt;&amp; operation);

  //Action signal handlers:
  void on_menu_file_new();
  void on_menu_file_page_setup();
  void on_menu_file_print_preview();
  void on_menu_file_print();
  void on_menu_file_quit();

  //Printing-related objects:
  Glib::RefPtr&lt;Gtk::PageSetup&gt; m_refPageSetup;
  Glib::RefPtr&lt;Gtk::PrintSettings&gt; m_refSettings;


  //Child widgets:
  Gtk::Box m_VBox;
  Gtk::Grid m_Grid;

  Gtk::Label m_NameLabel;
  Gtk::Entry m_NameEntry;

  Gtk::Label m_SurnameLabel;
  Gtk::Entry m_SurnameEntry;

  Gtk::Label m_CommentsLabel;
  Gtk::ScrolledWindow m_ScrolledWindow;
  Gtk::TextView m_TextView;
  
  Glib::RefPtr&lt;Gtk::TextBuffer&gt; m_refTextBuffer;

  unsigned m_ContextId;
  Gtk::Statusbar m_Statusbar;

  Glib::RefPtr&lt;Gtk::Builder&gt; m_refBuilder;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>printformoperation.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_PRINT_FORM_OPERATION_H
#define GTKMM_PRINT_FORM_OPERATION_H

#include &lt;gtkmm.h&gt;
#include &lt;pangomm.h&gt;
#include &lt;vector&gt;

//We derive our own class from PrintOperation,
//so we can put the actual print implementation here.
class PrintFormOperation : public Gtk::PrintOperation
{
 public:
  static Glib::RefPtr&lt;PrintFormOperation&gt; create();
  virtual ~PrintFormOperation();

  void set_name(const Glib::ustring&amp; name) { m_Name = name; }
  void set_comments(const Glib::ustring&amp; comments) { m_Comments = comments; }

 protected:
  PrintFormOperation();

  //PrintOperation default signal handler overrides:
  virtual void on_begin_print(const Glib::RefPtr&lt;Gtk::PrintContext&gt;&amp; context);
  virtual void on_draw_page(const Glib::RefPtr&lt;Gtk::PrintContext&gt;&amp; context, int page_nr);

  Glib::ustring m_Name;
  Glib::ustring m_Comments;
  Glib::RefPtr&lt;Pango::Layout&gt; m_refLayout;
  std::vector&lt;int&gt; m_PageBreaks; // line numbers where a page break occurs
};

#endif // GTKMM_PRINT_FORM_OPERATION_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include "printformoperation.h"

#include &lt;iostream&gt;

#include &lt;pangomm.h&gt;

const Glib::ustring app_title = "gtkmm Printing Example";

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_NameLabel("Name"),
  m_SurnameLabel("Surname"),
  m_CommentsLabel("Comments")
{
  m_refPageSetup = Gtk::PageSetup::create();
  m_refSettings = Gtk::PrintSettings::create();

  m_ContextId = m_Statusbar.get_context_id(app_title);

  set_title(app_title);
  set_default_size(400, 300);

  add(m_VBox);

  build_main_menu();

  m_VBox.pack_start(m_Grid);

  //Arrange the widgets inside the grid:
  m_Grid.set_row_spacing(5);
  m_Grid.set_column_spacing(5);
  m_Grid.attach(m_NameLabel, 0, 0, 1, 1);
  m_Grid.attach(m_NameEntry, 1, 0, 1, 1);

  m_Grid.attach(m_SurnameLabel, 0, 1, 1, 1);
  m_Grid.attach(m_SurnameEntry, 1, 1, 1, 1);

  //Add the TextView, inside a ScrolledWindow:
  m_ScrolledWindow.add(m_TextView);

  //Only show the scrollbars when they are necessary:
  m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

  m_Grid.attach(m_CommentsLabel, 0, 2, 1, 1);
  m_Grid.attach(m_ScrolledWindow, 1, 2, 1, 1);
  m_ScrolledWindow.set_hexpand(true);
  m_ScrolledWindow.set_vexpand(true);

  m_refTextBuffer = Gtk::TextBuffer::create();
  m_TextView.set_buffer(m_refTextBuffer);

  m_VBox.pack_start(m_Statusbar);

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::build_main_menu()
{
  //Create actions for menus and toolbars:
  Glib::RefPtr&lt;Gio::SimpleActionGroup&gt; refActionGroup =
   Gio::SimpleActionGroup::create();

  //File menu:
  refActionGroup-&gt;add_action("new",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_file_new));

  refActionGroup-&gt;add_action("pagesetup",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_file_page_setup));

  refActionGroup-&gt;add_action("printpreview",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_file_print_preview));

  refActionGroup-&gt;add_action("print",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_file_print));

  refActionGroup-&gt;add_action("quit",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_file_quit));

  insert_action_group("example", refActionGroup);

  m_refBuilder = Gtk::Builder::create();
 
  //TODO: add_accel_group(m_refBuilder-&gt;get_accel_group());

  //Layout the actions in a menubar and toolbar:
  
  Glib::ustring ui_info = 
   "&lt;interface&gt;"
    "  &lt;menu id='menu-example'&gt;"
    "    &lt;submenu&gt;"
    "      &lt;attribute name='label' translatable='yes'&gt;_File&lt;/attribute&gt;"
    "      &lt;section&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;Page _Setup&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;example.pagesetup&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;Print Preview&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;example.printpreview&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "        &lt;item&gt;"
    "          &lt;attribute name='label' translatable='yes'&gt;_Print&lt;/attribute&gt;"
    "          &lt;attribute name='action'&gt;example.print&lt;/attribute&gt;"
    "        &lt;/item&gt;"
    "      &lt;/section&gt;"
    "    &lt;/submenu&gt;"
    "  &lt;/menu&gt;"
/* TODO:
      "  &lt;toolbar  name='ToolBar'&gt;"
        "    &lt;toolitem action='New'/&gt;"
        "    &lt;toolitem action='Print'/&gt;"
        "      &lt;separator/&gt;"
        "    &lt;toolitem action='Quit'/&gt;"
        "  &lt;/toolbar&gt;"
*/
    "&lt;/interface&gt;";

  try
  {      
    m_refBuilder-&gt;add_from_string(ui_info);
  }
  catch(const Glib::Error&amp; ex)
  {
    std::cerr &lt;&lt; "building menus failed: " &lt;&lt; ex.what();
  }


  //Get the menubar and toolbar widgets, and add them to a container widget:
  Glib::RefPtr&lt;Glib::Object&gt; object =
    m_refBuilder-&gt;get_object("menu-example");
  Glib::RefPtr&lt;Gio::Menu&gt; gmenu =
    Glib::RefPtr&lt;Gio::Menu&gt;::cast_dynamic(object);
  if(!gmenu)
    g_warning("GMenu not found");

  Gtk::MenuBar* pMenubar = new Gtk::MenuBar(gmenu);
  m_VBox.pack_start(*pMenubar, Gtk::PACK_SHRINK);

/* TODO:
  Gtk::Widget* pToolbar = m_refBuilder-&gt;get_widget("/ToolBar") ;
  if(pToolbar)
    m_VBox.pack_start(*pToolbar, Gtk::PACK_SHRINK);
*/
}

void ExampleWindow::on_printoperation_status_changed(
        const Glib::RefPtr&lt;PrintFormOperation&gt;&amp; operation)
{
  Glib::ustring status_msg;

  if (operation-&gt;is_finished())
  {
    status_msg = "Print job completed.";
  }
  else
  {
    //You could also use get_status().
    status_msg = operation-&gt;get_status_string();
  }

  m_Statusbar.push(status_msg, m_ContextId);
}

void ExampleWindow::on_printoperation_done(Gtk::PrintOperationResult result,
        const Glib::RefPtr&lt;PrintFormOperation&gt;&amp; operation)
{
  //Printing is "done" when the print data is spooled.

  if (result == Gtk::PRINT_OPERATION_RESULT_ERROR)
  {
    Gtk::MessageDialog err_dialog(*this, "Error printing form", false,
            Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
    err_dialog.run();
  }
  else if (result == Gtk::PRINT_OPERATION_RESULT_APPLY)
  {
    //Update PrintSettings with the ones used in this PrintOperation:
    m_refSettings = operation-&gt;get_print_settings();
  }

  if (! operation-&gt;is_finished())
  {
    //We will connect to the status-changed signal to track status
    //and update a status bar. In addition, you can, for example,
    //keep a list of active print operations, or provide a progress dialog.
    operation-&gt;signal_status_changed().connect(sigc::bind(sigc::mem_fun(*this,
                    &amp;ExampleWindow::on_printoperation_status_changed),
                operation));
  }
}

void ExampleWindow::print_or_preview(Gtk::PrintOperationAction print_action)
{
  //Create a new PrintOperation with our PageSetup and PrintSettings:
  //(We use our derived PrintOperation class)
  Glib::RefPtr&lt;PrintFormOperation&gt; print = PrintFormOperation::create();

  print-&gt;set_name(m_NameEntry.get_text() + " " + m_SurnameEntry.get_text());
  print-&gt;set_comments(m_refTextBuffer-&gt;get_text(false /*Don't include hidden*/));

  print-&gt;set_track_print_status();
  print-&gt;set_default_page_setup(m_refPageSetup);
  print-&gt;set_print_settings(m_refSettings);

  print-&gt;signal_done().connect(sigc::bind(sigc::mem_fun(*this,
                  &amp;ExampleWindow::on_printoperation_done), print));
  try
  {
    print-&gt;run(print_action /* print or preview */, *this);
  }
  catch (const Gtk::PrintError&amp; ex)
  {
    //See documentation for exact Gtk::PrintError error codes.
    std::cerr &lt;&lt; "An error occurred while trying to run a print operation:"
        &lt;&lt; ex.what() &lt;&lt; std::endl;
  }
}

void ExampleWindow::on_menu_file_new()
{
  //Clear entries and textview:
  m_NameEntry.set_text("");
  m_SurnameEntry.set_text("");
  m_refTextBuffer-&gt;set_text("");
  m_TextView.set_buffer(m_refTextBuffer);
}

void ExampleWindow::on_menu_file_page_setup()
{
  //Show the page setup dialog, asking it to start with the existing settings:
  Glib::RefPtr&lt;Gtk::PageSetup&gt; new_page_setup =
      Gtk::run_page_setup_dialog(*this, m_refPageSetup, m_refSettings);

  //Save the chosen page setup dialog for use when printing, previewing, or
  //showing the page setup dialog again:
  m_refPageSetup = new_page_setup;
}

void ExampleWindow::on_menu_file_print_preview()
{
  print_or_preview(Gtk::PRINT_OPERATION_ACTION_PREVIEW);
}

void ExampleWindow::on_menu_file_print()
{
  print_or_preview(Gtk::PRINT_OPERATION_ACTION_PRINT_DIALOG);
}

void ExampleWindow::on_menu_file_quit()
{
  hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<para lang="en">File: <filename>printformoperation.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "printformoperation.h"

PrintFormOperation::PrintFormOperation()
{
}

PrintFormOperation::~PrintFormOperation()
{
}

Glib::RefPtr&lt;PrintFormOperation&gt; PrintFormOperation::create()
{
  return Glib::RefPtr&lt;PrintFormOperation&gt;(new PrintFormOperation());
}

void PrintFormOperation::on_begin_print(
        const Glib::RefPtr&lt;Gtk::PrintContext&gt;&amp; print_context)
{
  //Create and set up a Pango layout for PrintData based on the passed
  //PrintContext: We then use this to calculate the number of pages needed, and
  //the lines that are on each page.
  m_refLayout = print_context-&gt;create_pango_layout();

  Pango::FontDescription font_desc("sans 12");
  m_refLayout-&gt;set_font_description(font_desc);

  const double width = print_context-&gt;get_width();
  const double height = print_context-&gt;get_height();

  m_refLayout-&gt;set_width(static_cast&lt;int&gt;(width * Pango::SCALE));

  //Set and mark up the text to print:
  Glib::ustring marked_up_form_text;
  marked_up_form_text += "&lt;b&gt;Name&lt;/b&gt;: " + m_Name + "\n\n";
  marked_up_form_text += "&lt;b&gt;Comments&lt;/b&gt;: " + m_Comments;

  m_refLayout-&gt;set_markup(marked_up_form_text);

  //Set the number of pages to print by determining the line numbers
  //where page breaks occur:
  const int line_count = m_refLayout-&gt;get_line_count();

  Glib::RefPtr&lt;Pango::LayoutLine&gt; layout_line;
  double page_height = 0;

  for (int line = 0; line &lt; line_count; ++line)
  {
    Pango::Rectangle ink_rect, logical_rect;

    layout_line = m_refLayout-&gt;get_line(line);
    layout_line-&gt;get_extents(ink_rect, logical_rect);

    const double line_height = logical_rect.get_height() / 1024.0;

    if (page_height + line_height &gt; height)
    {
      m_PageBreaks.push_back(line);
      page_height = 0;
    }

    page_height += line_height;
  }

  set_n_pages(m_PageBreaks.size() + 1);
}

void PrintFormOperation::on_draw_page(
        const Glib::RefPtr&lt;Gtk::PrintContext&gt;&amp; print_context, int page_nr)
{
  //Decide which lines we need to print in order to print the specified page:
  int start_page_line = 0;
  int end_page_line = 0;

  if(page_nr == 0)
  {
    start_page_line = 0;
  }
  else
  {
    start_page_line = m_PageBreaks[page_nr - 1];
  }

  if(page_nr &lt; static_cast&lt;int&gt;(m_PageBreaks.size()))
  {
    end_page_line = m_PageBreaks[page_nr];
  }
  else
  {
    end_page_line = m_refLayout-&gt;get_line_count();
  }

  //Get a Cairo Context, which is used as a drawing board:
  Cairo::RefPtr&lt;Cairo::Context&gt; cairo_ctx = print_context-&gt;get_cairo_context();

  //We'll use black letters:
  cairo_ctx-&gt;set_source_rgb(0, 0, 0);

  //Render Pango LayoutLines over the Cairo context:
  Pango::LayoutIter iter = m_refLayout-&gt;get_iter();

  double start_pos = 0;
  int line_index = 0;

  do
  {
    if(line_index &gt;= start_page_line)
    {
      Glib::RefPtr&lt;Pango::LayoutLine&gt; layout_line = iter.get_line();
      Pango::Rectangle logical_rect = iter.get_line_logical_extents();
      int baseline = iter.get_baseline();

      if (line_index == start_page_line)
      {
        start_pos = logical_rect.get_y() / 1024.0;
      }

      cairo_ctx-&gt;move_to(logical_rect.get_x() / 1024.0,
        baseline / 1024.0 - start_pos);

      layout_line-&gt;show_in_cairo_context(cairo_ctx);
    }

    line_index++;
  }
  while(line_index &lt; end_page_line &amp;&amp; iter.next_line());
}

</programlisting>
<!-- end inserted example code -->

</sect2>

</sect1>

</chapter>

<chapter id="chapter-recent-documents">
  <title>Documentos usados recentemente</title>

  <para lang="en">
    <application>gtkmm</application> provides an easy way to manage recently used documents. The classes
    involved in implementing this functionality are
    <classname>RecentManager</classname>,
    <classname>RecentChooserDialog</classname>,
    <classname>RecentChooserMenu</classname>,
    <classname>RecentChooserWidget</classname>,
    <classname>RecentAction</classname>, and
    <classname>RecentFilter</classname>.
  </para>
  <para lang="en">
    Each item in the list of recently used files is identified by its URI, and
    can have associated metadata. The metadata can be used to specify how the
    file should be displayed, a description of the file, its mime type, which
    application registered it, whether it's private to the registering
    application, and several other things.
  </para>
  <sect1 id="sec-recentmanager">
    <title lang="en">RecentManager</title>
    <para lang="en">
      <classname>RecentManager</classname> acts as a database of
      recently used files. You use this class to register new files, remove
      files from the list, or look up recently used files. There is one list
      of recently used files per user.
    </para>
    <para lang="en">
      You can create a new <classname>RecentManager</classname>, but you'll most
      likely just want to use the default one. You can get a reference to the
      default <classname>RecentManager</classname> with
      <methodname>get_default()</methodname>.
    </para>
    <para lang="en">
      <classname>RecentManager</classname> is the model of a model-view pattern,
      where the view is a class that implements the
      <classname>RecentChooser</classname> interface.
    </para>
    <sect2 id="recent-files-adding">
      <title lang="en">Adding Items to the List of Recent Files</title>
      <para lang="en">
        To add a new file to the list of recent documents, in the simplest case,
        you only need to provide the URI. For example:
      </para>
      <programlisting lang="en">Glib::RefPtr&lt;Gtk::RecentManager&gt; recent_manager = Gtk::RecentManager::get_default();
recent_manager-&gt;add_item(uri);</programlisting>
      <para lang="en">
        If you want to register a file with metadata, you can pass a
        <classname>RecentManager::Data</classname> parameter to
        <methodname>add_item()</methodname>. The metadata that can be set on a
        particular file item is as follows:
      </para>
      <itemizedlist id="list-file-metadata">
        <listitem>
          <para lang="en"><varname>app_exec</varname>: The command line to be used to launch
            this resource. This string may contain the "f" and "u" escape
            characters which will be expanded to the resource file path and URI
            respectively</para>
        </listitem>
        <listitem>
          <para lang="en"><varname>app_name</varname>: The name of the application that
            registered the resource</para>
        </listitem>
        <listitem>
          <para lang="en"><varname>description</varname>: A short description of the
            resource as a UTF-8 encoded string</para>
        </listitem>
        <listitem>
          <para lang="en"><varname>display_name</varname>: The name of the resource to be
            used for display as a UTF-8 encoded string</para>
        </listitem>
        <listitem>
          <para lang="en"><varname>groups</varname>: A list of groups associated with this
            item. Groups are essentially arbitrary strings associated with a
            particular resource. They can be thought of as 'categories' (such
            as "email", "graphics", etc) or tags for the resource.</para>
        </listitem>
        <listitem>
          <para lang="en"><varname>is_private</varname>: Whether this resource should be
            visible only to applications that have registered it or not</para>
        </listitem>
        <listitem>
          <para><varname>mime_type</varname>: O tipo MIME do recurso</para>
        </listitem>
      </itemizedlist>
      <para lang="en">
        In addition to adding items to the list, you can also look up items from
        the list and modify or remove items.
      </para>
    </sect2>
    <sect2 id="recent-files-lookup">
      <title lang="en">Looking up Items in the List of Recent Files</title>
      <para lang="en">
        To look up recently used files, <classname>RecentManager</classname>
        provides several functions. To look up a specific item by its URI, you
        can use the <methodname>lookup_item()</methodname> function, which will
        return a <classname>RecentInfo</classname> class. If the specified URI
        did not exist in the list of recent files,
        <methodname>lookup_item()</methodname> throws a
        <classname>RecentManagerError</classname> exception. For example:
      </para>
<programlisting lang="en">Glib::RefPtr&lt;Gtk::RecentInfo&gt; info;
try
{
  info = recent_manager-&gt;lookup_item(uri);
}
catch(const Gtk::RecentManagerError&amp; ex)
{
  std::cerr &lt;&lt; "RecentManagerError: " &lt;&lt; ex.what() &lt;&lt; std::endl;
}
if (info)
{
  // item was found
}</programlisting>
      <para lang="en">
        A <classname>RecentInfo</classname> object is essentially an object
        containing all of the metadata about a single recently-used file. You
        can use this object to look up any of the properties listed
        <link linkend="list-file-metadata">above</link>.
      </para>
      <para lang="en">
        If you don't want to look for a specific URI, but instead want to get a
        list of all recently used items, <classname>RecentManager</classname>
        provides the <methodname>get_items()</methodname> function. The return
        value of this function is a <classname>std::vector</classname> of all
        recently used files. The following code demonstrates how you might get a
        list of recently used files:
      </para>
      <programlisting lang="en">std::vector&lt; Glib::RefPtr&lt;Gtk::RecentInfo&gt; &gt; info_list = recent_manager-&gt;get_items();</programlisting>
      <para lang="en">
        The maximum age of items in the recently used files list can be set with
        <methodname>Gtk::Settings::property_gtk_recent_files_max_age()</methodname>.
        Default value: 30 days.
      </para>
    </sect2>
    <sect2 id="recent-files-modifying">
      <title>Modificando a lista de arquivos recentes</title>
      <para lang="en">
        There may be times when you need to modify the list of recent files.
        For instance, if a file is moved or renamed, you may need to update the
        file's location in the recent files list so that it doesn't point to an
        incorrect location. You can update an item's location by using
        <methodname>move_item()</methodname>.
      </para>
      <para lang="en">
        In addition to changing a file's URI, you can also remove items from the
        list, either one at a time or by clearing them all at once. The former
        is accomplished with <methodname>remove_item()</methodname>, the latter with
        <methodname>purge_items()</methodname>.
      </para>
      <note>
        <para lang="en">
        The functions <methodname>move_item()</methodname>,
        <methodname>remove_item()</methodname> and
        <methodname>purge_items()</methodname> have no effect on the actual files
        that are referred to by the URIs, they only modify the list of recent
        files.
        </para>
      </note>
    </sect2>
  </sect1>

  <sect1 id="sec-recentchooser">
    <title lang="en">RecentChooser</title>
    <para lang="en">
      <classname>RecentChooser</classname> is an interface that can be
      implemented by widgets displaying the list of recently used files.
      <application>gtkmm</application> provides four built-in implementations for choosing recent files:
      <classname>RecentChooserWidget</classname>,
      <classname>RecentChooserDialog</classname>,
      <classname>RecentChooserMenu</classname>, and
      <classname>RecentAction</classname>.
    </para>
    <para lang="en">
      <classname>RecentChooserWidget</classname> is a simple widget for
      displaying a list of recently used files.
      <classname>RecentChooserWidget</classname> is the basic building block for
      <classname>RecentChooserDialog</classname>, but you can embed it into your
      user interface if you want to.
    </para>
    <para lang="en">
      <classname>RecentChooserMenu</classname> and
      <classname>RecentAction</classname> allow you to list recently used files
      as a menu.
    </para>
    <sect2 id="recentchooserdialog-example">
      <title>Exemplo simples de um RecentChooserDialog</title>
      <para lang="en">
        Shown below is a simple example of how to use the
        <classname>RecentChooserDialog</classname> and the
        <classname>RecentAction</classname> classes in a program.
        This simple program has a menubar with a
        <guimenuitem>Recent Files Dialog</guimenuitem> menu item.
        When you select this menu item, a dialog pops up showing the list of
        recently used files.
      </para>
      <note>
        <para lang="en">
          If this is the first time you're using a program that uses the Recent
          Files framework, the dialog may be empty at first. Otherwise it
          should show the list of recently used documents registered by other
          applications.
        </para>
      </note>
      <para lang="en">
        After selecting the <guimenuitem>Recent Files Dialog</guimenuitem> menu
        item, you should see something similar to the following window.
      </para>
      <screenshot>
          <graphic format="PNG" fileref="figures/recentchooserdialog.png"/>
      </screenshot>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/recent_files?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_menu_file_recent_files_item();
  void on_menu_file_recent_files_dialog();
  void on_menu_file_quit();
  void on_menu_file_new();

  //Child widgets:
  Gtk::Box m_Box;

  Glib::RefPtr&lt;Gtk::Builder&gt; m_refBuilder;
  Glib::RefPtr&lt;Gio::SimpleActionGroup&gt; m_refActionGroup;

  Glib::RefPtr&lt;Gtk::RecentManager&gt; m_refRecentManager;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
: m_Box(Gtk::ORIENTATION_VERTICAL),
  m_refRecentManager(Gtk::RecentManager::get_default())
{
  set_title("recent files example");
  set_default_size(200, 200);

  //We can put a MenuBar at the top of the box and other stuff below it.
  add(m_Box);

  //Create actions for menus and toolbars:
  m_refActionGroup = Gio::SimpleActionGroup::create();

  //File menu:
  m_refActionGroup-&gt;add_action("new",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_file_new));

  //A menu item to open the recent-files dialog:
  m_refActionGroup-&gt;add_action("recent-files-dialog",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_file_recent_files_dialog) );

  m_refActionGroup-&gt;add_action("quit",
    sigc::mem_fun(*this, &amp;ExampleWindow::on_menu_file_quit) );

  insert_action_group("example", m_refActionGroup);


  m_refBuilder = Gtk::Builder::create();

  //TODO: add_accel_group(m_refBuilder-&gt;get_accel_group());

  //Layout the actions in a menubar and toolbar:
  const char* ui_info =
    "&lt;interface&gt;"
    "  &lt;menu id='menubar'&gt;"
    "    &lt;submenu&gt;"
    "      &lt;attribute name='label' translatable='yes'&gt;_File&lt;/attribute&gt;"
    "      &lt;item&gt;"
    "        &lt;attribute name='label' translatable='yes'&gt;_New&lt;/attribute&gt;"
    "        &lt;attribute name='action'&gt;example.new&lt;/attribute&gt;"
    "        &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;n&lt;/attribute&gt;"
    "      &lt;/item&gt;"
    "      &lt;item&gt;"
    "        &lt;attribute name='label' translatable='yes'&gt;Recent Files _Dialog&lt;/attribute&gt;"
    "        &lt;attribute name='action'&gt;example.recent-files-dialog&lt;/attribute&gt;"
    "        &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;o&lt;/attribute&gt;"
    "      &lt;/item&gt;"
    "      &lt;item&gt;"
    "        &lt;attribute name='label' translatable='yes'&gt;_Quit&lt;/attribute&gt;"
    "        &lt;attribute name='action'&gt;example.quit&lt;/attribute&gt;"
    "        &lt;attribute name='accel'&gt;&amp;lt;Primary&amp;gt;q&lt;/attribute&gt;"
    "      &lt;/item&gt;"
    "    &lt;/submenu&gt;"
    "  &lt;/menu&gt;";

/* TODO: 
        "  &lt;toolbar  name='ToolBar'&gt;"
        "    &lt;toolitem action='FileNew'/&gt;"
        "    &lt;toolitem action='FileQuit'/&gt;"
        "  &lt;/toolbar&gt;"
        "&lt;/ui&gt;";
*/

  try
  {
    m_refBuilder-&gt;add_from_string(ui_info);
  }
  catch(const Glib::Error&amp; ex)
  {
    std::cerr &lt;&lt; "building menus failed: " &lt;&lt;  ex.what();
  }

  //Get the menubar and toolbar widgets, and add them to a container widget:
  Glib::RefPtr&lt;Glib::Object&gt; object =
    m_refBuilder-&gt;get_object("menubar");
  Glib::RefPtr&lt;Gio::Menu&gt; gmenu =
    Glib::RefPtr&lt;Gio::Menu&gt;::cast_dynamic(object);
  if(!gmenu)
    g_warning("GMenu not found");

  //Menubar:
  Gtk::MenuBar* pMenubar = new Gtk::MenuBar(gmenu);
  m_Box.pack_start(*pMenubar, Gtk::PACK_SHRINK);

/* TODO:
  Gtk::Widget* pToolbar = m_refBuilder-&gt;get_widget("/ToolBar");
  if(pToolbar)
    m_Box.pack_start(*pToolbar, Gtk::PACK_SHRINK);
*/

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_menu_file_new()
{
  std::cout &lt;&lt; " New File" &lt;&lt; std::endl;
}

void ExampleWindow::on_menu_file_quit()
{
  hide(); //Closes the main window to stop the app-&gt;run().
}

void ExampleWindow::on_menu_file_recent_files_dialog()
{
  Gtk::RecentChooserDialog dialog(*this, "Recent Files", m_refRecentManager);
  dialog.add_button("Select File", Gtk::RESPONSE_OK);
  dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL);

  const int response = dialog.run();
  dialog.hide();
  if(response == Gtk::RESPONSE_OK)
  {
    std::cout &lt;&lt; "URI selected = " &lt;&lt; dialog.get_current_uri() &lt;&lt; std::endl;
  }
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
      <para lang="en">
        The constructor for <classname>ExampleWindow</classname> creates the
        menu using <classname>UIManager</classname> (see <xref linkend="chapter-menus-and-toolbars"/> for more information). It then adds
        the menu and the toolbar to the window.
      </para>
    </sect2>
    <sect2 id="recent-files-filtering">
      <title>Filtrando arquivos recentes</title>
      <para lang="en">
        For any of the <classname>RecentChooser</classname> classes, if you
        don't wish to display all of the items in the list of recent files, you
        can filter the list to show only those that you want. You can filter
        the list with the help of the <classname>RecentFilter</classname> class.
        This class allows you to filter recent files by their name
        (<methodname>add_pattern()</methodname>), their mime type
        (<methodname>add_mime_type()</methodname>), the application that registered
        them (<methodname>add_application()</methodname>), or by a custom filter
        function (<methodname>add_custom()</methodname>). It also provides the
        ability to filter based on how long ago the file was modified and which
        groups it belongs to.
      </para>
      <para lang="en">
        After you've created and set up the filter to match only the items you
        want, you can apply a filter to a chooser widget with the
        <methodname>RecentChooser::add_filter()</methodname> function.
      </para>
    </sect2>
  </sect1>
</chapter>

<chapter id="chapter-plugs-sockets">
  <title>Plugs e Sockets</title>
  <sect1 id="sec-plugs-sockets-overview">
    <title>Visão geral</title>
    <para lang="en">
      From time to time, it may be useful to be able to embed a widget from
      another application within your application. <application>gtkmm</application> allows you to do
      this with the <classname>Gtk::Socket</classname> and
      <classname>Gtk::Plug</classname> classes. It is not anticipated that very
      many applications will need this functionality, but in the rare case that
      you need to display a widget that is running in a completely different
      process, these classes can be very helpful.
    </para>
    <para lang="en">
      The communication between a <classname>Socket</classname> and a
      <classname>Plug</classname> follows the XEmbed protocol. This protocol has
      also been implemented in other toolkits (e.g. Qt), which allows the same
      level of integration when embedding a Qt widget in GTK+ or vice versa.
    </para>
    <para lang="en">
      The way that <classname>Sockets</classname> and
      <classname>Plugs</classname> work together is through their window ids.
      Both a <classname>Socket</classname> and a <classname>Plug</classname>
      have IDs that can be retrieved with their <methodname>get_id()</methodname>
      member functions. The use of these IDs will be explained below in <xref linkend="sec-connecting-plugs-sockets"/>.
    </para>
    <sect2 id="sec-sockets">
      <title>Soquetes</title>
      <para lang="en">
        A <classname>Socket</classname> is a special kind of container widget that
        provides the ability to embed widgets from one process into another
        process in a way that is transparent to the user.
      </para>
    </sect2>
    <sect2 id="sec-plugs">
      <title>Plugues</title>
      <para lang="en">
        A <classname>Plug</classname> is a special kind of Window that can be
        plugged into a <classname>Socket</classname>. Besides the normal
        properties and methods of <classname>Gtk::Window</classname>, a
        <classname>Plug</classname> provides a constructor that takes the ID of
        a <classname>Socket</classname>, which will automatically embed the
        <classname>Plug</classname> into the <classname>Socket</classname> that
        matches that ID.
      </para>
      <para lang="en">
        Since a <classname>Plug</classname> is just a special type of
        <classname>Gtk::Window</classname> class, you can add containers or
        widgets to it like you would to any other window.
      </para>
    </sect2>
    <sect2 id="sec-connecting-plugs-sockets">
      <title lang="en">Connecting Plugs and Sockets</title>
      <para lang="en">
        After a <classname>Socket</classname> or <classname>Plug</classname>
        object is realized, you can obtain its ID with its
        <methodname>get_id()</methodname> function. This ID can then be shared with
        other processes so that other processes know how to connect to
        each other.
      </para>
      <para lang="en">
        There are two basic strategies that can be used:
        <itemizedlist>
          <listitem>
            <para lang="en">
              Create a <classname>Socket</classname> object in one process and
              pass the ID of that <classname>Socket</classname> to another
              process so that it can create a <classname>Plug</classname> object
              by specifying the given <classname>Socket</classname> ID in its
              constructor. There is no way to assign a
              <classname>Plug</classname> to a particular
              <classname>Socket</classname> after creation, so you must pass the
              <classname>Socket</classname> ID to the
              <classname>Plug</classname>'s constructor.
            </para>
          </listitem>
          <listitem>
            <para lang="en">
              Create a <classname>Plug</classname> independantly from any
              particular <classname>Socket</classname> and pass the ID of the
              <classname>Plug</classname> to other processes that need to use
              it. The ID of the <classname>Plug</classname> can be associated
              with a particular <classname>Socket</classname> object using the
              <methodname>Socket::add_id()</methodname> function. This is the
              approach used in the example below.
            </para>
          </listitem>
        </itemizedlist>
      </para>
    </sect2>
  </sect1>
  <sect1 id="sec-plugs-sockets-example">
    <title lang="en">Plugs and Sockets Example</title>
    <para lang="en">
      The following is a simple example of using sockets and plugs. The method
      of communication between processes is deliberately kept very simple: The
      <classname>Plug</classname> writes its ID out to a text file named
      <filename>plug.id</filename> and the process with the socket reads the ID
      from this file. In a real program, you may want to use a more
      sophisticated method of inter-process communication.
    </para>
<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/socket/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>plug.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include &lt;fstream&gt;
#include &lt;gtkmm.h&gt;
#include &lt;gtkmm/plug.h&gt;
#include &lt;glib/gstdio.h&gt;

using namespace std;

const char* id_filename = "plug.id";

void on_embed()
{
  cout &lt;&lt; "I've been embedded." &lt;&lt; endl;
}

class MyPlug : public Gtk::Plug
{
  public:
    MyPlug() :
      m_label("I am the plug")
  {
    set_size_request(150, 100);
    add(m_label);
    signal_embedded().connect(sigc::ptr_fun(on_embed));
    show_all_children();
  }

  private:
    Gtk::Label m_label;
};


int main(int argc, char** argv)
{
  // The plug and the socket have different application ids, so they can run
  // simultaneously.
  Glib::RefPtr&lt;Gtk::Application&gt; app =
    Gtk::Application::create(argc, argv, "org.gtkmm.example.plug");
  MyPlug plug;
  plug.show();

  ofstream out(id_filename);
  out &lt;&lt; plug.get_id();
  out.close();
  cout &lt;&lt; "The window ID is: " &lt;&lt; plug.get_id() &lt;&lt; endl;

  app-&gt;run(plug);

  // remove the ID file when the program exits
  g_remove(id_filename);
  return 0;
}
</programlisting>
<para lang="en">File: <filename>socket.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include &lt;fstream&gt;
#include &lt;gtkmm.h&gt;
#include &lt;gtkmm/socket.h&gt;

using namespace std;

const char* id_filename = "plug.id";

void plug_added()
{
  cout &lt;&lt; "A plug was added" &lt;&lt; endl;
}

bool plug_removed()
{
  cout &lt;&lt; "A Plug was removed" &lt;&lt; endl;
  return true;
}

class MySocketWindow : public Gtk::Window
{
  public:
    MySocketWindow()
    {
      ifstream infile(id_filename);
      if (infile)
      {
        Gtk::Socket* socket = Gtk::manage(new Gtk::Socket());
        add(*socket);
        socket-&gt;signal_plug_added().connect(sigc::ptr_fun(plug_added));
        socket-&gt;signal_plug_removed().connect(sigc::ptr_fun(plug_removed));
        ::Window plug_id = 0;
        infile &gt;&gt; plug_id;
        infile.close();
        socket-&gt;add_id(plug_id);
      }
      else
      {
        Gtk::Label* label = Gtk::manage(
            new Gtk::Label(
              "Plug id file not found.\n Make sure plug is running."));
        add(*label);
        set_size_request(150, 50);
      }
      show_all();
    }
};

int main(int argc, char** argv)
{
  // The plug and the socket have different application ids, so they can run
  // simultaneously.
  Glib::RefPtr&lt;Gtk::Application&gt; app =
    Gtk::Application::create(argc, argv, "org.gtkmm.example.socket");
  MySocketWindow win;
  app-&gt;run(win);
  return 0;
}
</programlisting>
<!-- end inserted example code -->
    <para lang="en">
      This example creates two executable programs: <filename>socket</filename>
      and <filename>plug</filename>. The idea is that
      <filename>socket</filename> has an application window that will embed a
      widget from the <filename>plug</filename> program. The way this example
      is designed, <filename>plug</filename> must be running first before
      starting <filename>socket</filename>. To see the example in action,
      execute the following commands in order from within the example directory:
    </para>
    <para lang="en">
      Start the <filename>plug</filename> program and send it to the background
      (or just use a different terminal).
    </para>
    <screen>$ ./plug &amp;</screen>
    <para lang="en">
      After which you should see something like the following:
    </para>
    <screen>O ID da janela é: 69206019</screen>
    <para lang="en">Then start the <filename>socket</filename> program:</para>
    <screen>$ ./socket</screen>
    <para lang="en">
      After starting <filename>socket</filename>, you should see the following
      output in the terminal:
    </para>
    <screen lang="en">I've been embedded.
A plug was added</screen>
    <para lang="en">
      The first line of output is from <filename>plug</filename>, after it has
      been notified that it has been embedded inside of a
      <classname>Socket</classname>. The second line was emitted by
      <filename>socket</filename> in response to its
      <methodname>plug_added</methodname> signal. If everything was done as
      described above, the <filename>socket</filename> window should look
      roughly like the following:
    </para>
    <screenshot>
      <graphic format="PNG" fileref="figures/socket.png"/>
    </screenshot>
    <para lang="en">
      If for some reason the <classname>Socket</classname> couldn't attach the
      <classname>Plug</classname>, the window would look something like this:
    </para>
    <screenshot>
      <graphic format="PNG" fileref="figures/socket-fail.png"/>
    </screenshot>
  </sect1>
</chapter>

<chapter id="chapter-keyboardevents">
  <title>Eventos de teclado</title>
  <para lang="en">
    X events differ in some ways from other signals. These differences are described
    in the <link linkend="sec-xeventsignals">X Event signals</link> section in
    the appendix. Here we will use keyboard events to show how X events can be
    used in a program.
  </para>
  <sect1 id="sec-keyboardevents-overview">
    <title>Visão geral</title>
    <para lang="en">
      Whenever you press or release a key, an event is emitted. You can connect
      a signal handler to handle such events.
    </para>
    <para lang="en">
      To receive the keyboard events, you must first call the
      <methodname>Gtk::Widget::add_events()</methodname> function with a bit
      mask of the events you're interested in. The event signal handler will
      receive an argument that depends on the type of event. For keyboard
      events it's a <type>GdkEventKey*</type>. As discribed in the
      <link linkend="sec-xeventsignals">appendix</link>, the event signal handler
      returns a <type>bool</type> value, to indicate that the signal is fully
      handled (<literal>true</literal>) or allow event propagation
      (<literal>false</literal>).
    </para>
    <para lang="en">
      To determine which key was pressed or released, you read the value of
      <varname>GdkEventKey::keyval</varname> and compare it with a constant in the
      <filename>&lt;gdk/gdkkeysyms.h&gt;</filename> header file. The states of
      modifier keys (shift, ctrl, etc.) are available as bit-flags in
      <varname>GdkEventKey::state</varname>.
    </para>
    <para lang="en">
      Here's a simple example:
<programlisting lang="en">
bool on_key_press_or_release_event(GdkEventKey* event)
{
  if (event-&gt;type == GDK_KEY_PRESS &amp;&amp;
    event-&gt;keyval == GDK_KEY_1 &amp;&amp;
    (event-&gt;state &amp; (GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK)) == GDK_MOD1_MASK)
  {
    handle_alt_1_press(); // GDK_MOD1_MASK is normally the Alt key
    return true;
  }
  return false;
}

Gtk::Entry m_entry; // in a class definition

// in the class constructor
m_entry.signal_key_press_event().connect( sigc::ptr_fun(&amp;on_key_press_or_release_event) );
m_entry.signal_key_release_event().connect( sigc::ptr_fun(&amp;on_key_press_or_release_event) );
m_entry.add_events(Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK);
</programlisting>
    </para>

    <sect2 id="keyboardevents-simple-example">
    <title>Exemplo</title>
      <para lang="en">
        In this example there are three keyboard shortcuts:
        <keycap>Alt</keycap>+<keycap>1</keycap> selects the first radio button,
        <keycap>Alt</keycap>+<keycap>2</keycap> selects the second one, and the
        <keycap>Esc</keycap> key hides (closes) the window.
        The default event signal handler is overridden, as described in the
        <link linkend="sec-overriding-default-signal-handlers">Overriding default signal handlers</link>
        section in the appendix.
      </para>

      <figure id="figure-keyboardevents-simple">
        <title>Eventos de teclado - Simples</title>
        <screenshot>
          <graphic format="PNG" fileref="figures/keyboardevents_simple.png"/>
        </screenshot>
      </figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/keyboard_events/simple/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:

  ExampleWindow();
  virtual ~ExampleWindow();

private:
  //Override default signal handler:
  virtual bool on_key_press_event(GdkEventKey* event);

  Gtk::Grid m_container;
  Gtk::RadioButton m_first;
  Gtk::RadioButton m_second;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
{
  set_title("Keyboard Events");
  set_border_width(10);
  add(m_container);
  
  // Radio buttons:
  m_first.set_label("First");
  m_second.set_label("Second");

  Gtk::RadioButton::Group group = m_first.get_group();
  m_second.set_group(group);
  m_first.set_active();

  // Main Container:
  m_container.add(m_first);
  m_container.add(m_second);

  // Events.
  // We override the default event signal handler.
  add_events(Gdk::KEY_PRESS_MASK);

  show_all_children();
}

bool ExampleWindow::on_key_press_event(GdkEventKey* event)
{
  //GDK_MOD1_MASK -&gt; the 'alt' key(mask)
  //GDK_KEY_1 -&gt; the '1' key
  //GDK_KEY_2 -&gt; the '2' key

  //select the first radio button, when we press alt + 1
  if((event-&gt;keyval == GDK_KEY_1) &amp;&amp;
    (event-&gt;state &amp;(GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK)) == GDK_MOD1_MASK)
  {
    m_first.set_active();
    //returning true, cancels the propagation of the event
    return true;
  }
  else if((event-&gt;keyval == GDK_KEY_2) &amp;&amp;
    (event-&gt;state &amp; (GDK_SHIFT_MASK | GDK_CONTROL_MASK | GDK_MOD1_MASK)) == GDK_MOD1_MASK)
  {
    //and the second radio button, when we press alt + 2
    m_second.set_active();
    return true;
  }
  else if(event-&gt;keyval == GDK_KEY_Escape)
  {
    //close the window, when the 'esc' key is pressed
    hide();
    return true;
  }

  //if the event has not been handled, call the base class
  return Gtk::Window::on_key_press_event(event);
}

ExampleWindow::~ExampleWindow()
{
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
    </sect2>
  </sect1>

  <sect1 id="sec-keyboardevents-propagation">
    <title>Propagação de eventos</title>
    <para lang="en">
      Event propagation means that, when an event is emitted on a particular
      widget, it can be passed to its parent widget (and that widget can pass
      it to its parent, and so on) and, if the parent has an event handler,
      that handler will be called. 
    </para>
    <para lang="en">
      Contrary to other events, keyboard events are first sent to the toplevel window
      (<classname>Gtk::Window</classname>), where it will be checked
      for any keyboard shortcuts that may be set (accelerator keys and mnemonics,
      used for selecting menu items from the keyboard). After this (and assuming
      the event wasn't handled), it is sent to the widget which has focus,
      and the propagation begins from there.
    </para>
    <para lang="en">
      The event will propagate until it reaches the top-level widget, or until
      you stop the propagation by returning <literal>true</literal> from an
      event handler.
    </para>
    <para lang="en">
      Notice, that after canceling an event, no other function will be called
      (even if it is from the same widget).
    </para>

    <sect2 id="keyboardevents-propagation-example">
    <title>Exemplo</title>
      <para lang="en">
        In this example there are three event handlers that are called after
        <classname>Gtk::Window</classname>'s default event handler, one in the
        <classname>Gtk::Entry</classname>, one in the <classname>Gtk::Grid</classname>
        and one in the <classname>Gtk::Window</classname>.
      </para>
      <para lang="en">
        In the <classname>Gtk::Window</classname>, we have also the default handler
        overridden (<methodname>on_key_release_event()</methodname>), and
        another handler being called before the default handler
        (<methodname>windowKeyReleaseBefore()</methodname>).
      </para>
      <para lang="en">
        The purpose of this example is to show the steps the event takes when it is emitted.
      </para>
      <para lang="en">
        When you write in the entry, a key release event will be emitted,
        which will go first to the toplevel window (<classname>Gtk::Window</classname>),
        since we have one event handler set to be called before, that's what is
        called first (<methodname>windowKeyReleaseBefore()</methodname>).
        Then the default handler is called (which we have overridden), and after
        that the event is sent to the widget that has focus,
        the <classname>Entry</classname> in our example and, depending on whether we let
        it propagate, it can reach the <classname>Grid</classname>'s and the
        <classname>Window</classname>'s event handlers. If it propagates,
        the text you're writing will appear in the <classname>Label</classname>
        above the <classname>Entry</classname>.
      </para>

      <figure id="figure-keyboardevents-propagation">
        <title>Eventos de teclado - Propagação de eventos</title>
        <screenshot>
          <graphic format="PNG" fileref="figures/keyboardevents_propagation.png"/>
        </screenshot>
      </figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/keyboard_events/propagation/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EVENT_PROPAGATION_H
#define GTKMM_EVENT_PROPAGATION_H

#include &lt;gtkmm.h&gt;

class ExampleWindow : public Gtk::Window
{
public:

  ExampleWindow();
  virtual ~ExampleWindow();

private:
  //Override default signal handler:
  virtual bool on_key_release_event(GdkEventKey* event);

  bool entryKeyRelease(GdkEventKey* event);
  bool gridKeyRelease(GdkEventKey* event);
  bool windowKeyReleaseBefore(GdkEventKey* event);
  bool windowKeyRelease(GdkEventKey* event);

  Gtk::Grid m_container;

  Gtk::Label m_label;
  Gtk::Entry m_entry;
  Gtk::CheckButton m_checkbutton_can_propagate;
};

#endif //GTKMM_EVENT_PROPAGATION_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow()
{
  add(m_container);
  set_title("Event Propagation");
  set_border_width(10);
  
  m_label.set_label("A label");
  m_checkbutton_can_propagate.set_label("Can Propagate");
  m_checkbutton_can_propagate.set_active();

  // Main Container
  m_container.set_orientation(Gtk::ORIENTATION_VERTICAL);
  m_container.add(m_label);
  m_container.add(m_entry);
  m_container.add(m_checkbutton_can_propagate);

  // Events
  add_events(Gdk::KEY_RELEASE_MASK);

  m_entry.signal_key_release_event().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::entryKeyRelease));

  m_container.signal_key_release_event().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::gridKeyRelease));

  // Called before the default event signal handler.
  signal_key_release_event().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::windowKeyReleaseBefore), false);

  // Called after the default event signal handler.
  signal_key_release_event().connect(
    sigc::mem_fun(*this, &amp;ExampleWindow::windowKeyRelease));

  show_all_children();
}

//By changing the return value we allow, or don't allow, the event to propagate to other elements.
bool ExampleWindow::entryKeyRelease(GdkEventKey* /* event */ )
{
  std::cout &lt;&lt; "Entry" &lt;&lt; std::endl;

  if(m_checkbutton_can_propagate.get_active())
  {
    return false;
  }

  return true;
}

bool ExampleWindow::gridKeyRelease(GdkEventKey* /* event */ )
{
  std::cout &lt;&lt; "Grid" &lt;&lt; std::endl;

  //Let it propagate:
  return false;
}

bool ExampleWindow::windowKeyReleaseBefore(GdkEventKey* /* event */ )
{
  std::cout &lt;&lt; "Window before" &lt;&lt; std::endl;
  return false;
}

bool ExampleWindow::on_key_release_event(GdkEventKey* event)
{
  std::cout &lt;&lt; "Window overridden" &lt;&lt; std::endl;

  // call base class function (to get the normal behaviour)
  return Gtk::Window::on_key_release_event(event);
}

// This will set the entry's text in the label, every time a key is pressed.
bool ExampleWindow::windowKeyRelease(GdkEventKey* /* event */ )
{
  std::cout &lt;&lt; "Window after";

  //checking if the entry is on focus, otherwise the label would get changed by pressing keys
  //on the window (when the entry is not on focus), even if m_checkbutton_can_propagate wasn't active
  if(m_entry.has_focus())
  {
    m_label.set_text(m_entry.get_text());
    std::cout &lt;&lt; ", " &lt;&lt; m_entry.get_text();
  }
  std::cout &lt;&lt; std::endl;

  return true;
}

ExampleWindow::~ExampleWindow()
{
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<!-- end inserted example code -->
    </sect2>
  </sect1>
</chapter>

<chapter id="chapter-chapter-timeouts">
<title>Tempo limite, E/S e funções ociosas</title>

<sect1 id="sec-timeouts">
<title>Tempos limites</title>

<para lang="en">
You may be wondering how to make <application>gtkmm</application> do useful work while it's idling along. Happily,
you have several options. Using the following methods you can create a timeout
method that will be called every few milliseconds.
</para>

<para>
<programlisting lang="en">
sigc::connection Glib::SignalTimeout::connect(const sigc::slot&lt;bool&gt;&amp; slot,
                                      unsigned int interval, int priority = Glib::PRIORITY_DEFAULT);
</programlisting>
</para>

<para lang="en">
The first argument is a <classname>slot</classname> you wish to have called
when the timeout occurs. The second argument is the number of milliseconds
between calls to that method. You receive a
<classname>sigc::connection</classname> object that can be used to deactivate
the connection using its <methodname>disconnect()</methodname> method:
</para>

<para>

<programlisting>
my_connection.disconnect();
</programlisting>
</para>

<para lang="en">
Another way of destroying the connection is your signal handler.
It has to be of the type <classname>sigc::slot&lt;bool&gt;</classname>.
As you see from the definition your signal handler has to return a value of
the type <literal>bool</literal>. A definition of a sample method might
look like this:

<programlisting lang="en">
bool MyCallback() { std::cout &lt;&lt; "Hello World!\n" &lt;&lt; std::endl; return true; }
</programlisting>

</para>

<para lang="en">
You can stop the timeout method by returning <literal>false</literal> from
your signal handler. Therefore, if you want your
method to be called repeatedly, it should return <literal>true</literal>.
</para>

<para lang="en">
Here's an example of this technique:
</para>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/timeout/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>timerexample.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_TIMEREXAMPLE_H
#define GTKMM_EXAMPLE_TIMEREXAMPLE_H

#include &lt;gtkmm.h&gt;
#include &lt;iostream&gt;
#include &lt;map&gt;

class TimerExample : public Gtk::Window
{
public:
  TimerExample();

protected:
  // signal handlers
  void on_button_add_timer();
  void on_button_delete_timer();
  void on_button_quit();

  // This is the callback function the timeout will call
  bool on_timeout(int timer_number);

  // Member data:

  Gtk::Box m_Box;
  Gtk::Button m_ButtonAddTimer, m_ButtonDeleteTimer, m_ButtonQuit;

  // Keep track of the timers being added:
  int m_timer_number;

  // These two constants are initialized in the constructor's member initializer:
  const int count_value;
  const int timeout_value;

  // STL map for storing our connections
  std::map&lt;int, sigc::connection&gt; m_timers;

  // STL map for storing our timer values.
  // Each timer counts back from COUNT_VALUE to 0 and is removed when it reaches 0
  std::map&lt;int, int&gt; m_counters;
};

#endif // GTKMM_EXAMPLE_TIMEREXAMPLE_H
</programlisting>
<para lang="en">File: <filename>timerexample.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "timerexample.h"

TimerExample::TimerExample() :
  m_Box(Gtk::ORIENTATION_HORIZONTAL, 10),
  m_ButtonAddTimer("_Add", true),
  m_ButtonDeleteTimer("_Remove", true),
  m_ButtonQuit("_Quit", true),
  m_timer_number(0), // start numbering the timers at 0
  count_value(5), // each timer will count down 5 times before disconnecting
  timeout_value(1500) // 1500 ms = 1.5 seconds
{
  set_border_width(10);

  add(m_Box);
  m_Box.pack_start(m_ButtonAddTimer);
  m_Box.pack_start(m_ButtonDeleteTimer);
  m_Box.pack_start(m_ButtonQuit);

  // Connect the three buttons:
  m_ButtonQuit.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;TimerExample::on_button_quit));
  m_ButtonAddTimer.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;TimerExample::on_button_add_timer));
  m_ButtonDeleteTimer.signal_clicked().connect(sigc::mem_fun(*this,
              &amp;TimerExample::on_button_delete_timer));

  show_all_children();
}

void TimerExample::on_button_quit()
{
  hide();
}

void TimerExample::on_button_add_timer()
{
  // Creation of a new object prevents long lines and shows us a little
  // how slots work.  We have 0 parameters and bool as a return value
  // after calling sigc::bind.
  sigc::slot&lt;bool&gt; my_slot = sigc::bind(sigc::mem_fun(*this,
              &amp;TimerExample::on_timeout), m_timer_number);

  // This is where we connect the slot to the Glib::signal_timeout()
  sigc::connection conn = Glib::signal_timeout().connect(my_slot,
          timeout_value);

  // Remember the connection:
  m_timers[m_timer_number] = conn;

  // Initialize timer count:
  m_counters[m_timer_number] = count_value + 1;

  // Print some info to the console for the user:
  std::cout &lt;&lt; "added timeout " &lt;&lt; m_timer_number++ &lt;&lt; std::endl;
}

void TimerExample::on_button_delete_timer()
{
  // any timers?
  if(m_timers.empty())
  {
    // no timers left
    std::cout &lt;&lt; "Sorry, there are no timers left." &lt;&lt; std::endl;
  }
  else
  {
    // get the number of the first timer
    int timer_number = m_timers.begin()-&gt;first;

    // Give some info to the user:
    std::cout &lt;&lt; "manually disconnecting timer " &lt;&lt; timer_number
        &lt;&lt; std::endl;

    // Remove the entry in the counter values
    m_counters.erase(timer_number);

    // Diconnect the signal handler:
    m_timers[timer_number].disconnect();

    // Forget the connection:
    m_timers.erase(timer_number);
  }
}

bool TimerExample::on_timeout(int timer_number)
{
  // Print the timer:
  std::cout &lt;&lt; "This is timer " &lt;&lt; timer_number;

  // decrement and check counter value
  if (--m_counters[timer_number] == 0)
  {
    std::cout &lt;&lt; " being disconnected" &lt;&lt;  std::endl;

    // delete the counter entry in the STL MAP
    m_counters.erase(timer_number);

    // delete the connection entry in the STL MAP
    m_timers.erase(timer_number);

    // Note that we do not have to explicitly call disconnect() on the
    // connection since Gtk::Main does this for us when we return false.
    return false;
  }

  // Print the timer value
  std::cout &lt;&lt; " - " &lt;&lt; m_counters[timer_number] &lt;&lt; "/"
      &lt;&lt; count_value &lt;&lt; std::endl;

 // Keep going (do not disconnect yet):
  return true;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "timerexample.h"
#include &lt;gtkmm/application.h&gt;

int main (int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  TimerExample example;
  return app-&gt;run(example);
}
</programlisting>
<!-- end inserted example code -->

</sect1>

<sect1 id="sec-monitoring-io">
<title>Monitorando E/S</title>

<para lang="en">
A nifty feature of Glib (one of the libraries underlying
<application>gtkmm</application>) is the ability to have it check for data on a file descriptor
for you. This is especially useful for networking applications. The
following method is used to do this:
</para>

<para>
<programlisting lang="en">
sigc::connection Glib::SignalIO::connect(const sigc::slot&lt;bool,Glib::IOCondition&gt;&amp; slot,
                                 int fd, Glib::IOCondition condition,
                                 int priority = Glib::PRIORITY_DEFAULT);
</programlisting>
</para>

<para lang="en">
The first argument is a slot you wish to have called when
the specified event (see argument 3) occurs on the file descriptor you specify
using argument two. Argument three may be one or more (using
<literal>|</literal>) of:
</para>

<itemizedlist>
<listitem>

<para lang="en">
Glib::IO_IN - Call your method when there is data ready for
reading on your file descriptor.

</para>
</listitem>
<listitem>

<para lang="en">
Glib::IO_OUT - Call your method when the file descriptor is
ready for writing.

</para>
</listitem>
<listitem>

<para lang="en">
Glib::IO_PRI - Call your method when the file descriptor has urgent data to be read.

</para>
</listitem>
<listitem>

<para lang="en">
Glib::IO_ERR - Call your method when an error has occurred on the file descriptor.

</para>
</listitem>
<listitem>

<para lang="en">
Glib::IO_HUP - Call your method when hung up (the connection has been broken usually for pipes and sockets).
</para>
</listitem>

</itemizedlist>

<para lang="en">
    The return value is a <classname>sigc::connection</classname> that may be used to stop monitoring
this file descriptor using its <methodname>disconnect()</methodname> method. The
<parameter>slot</parameter> signal handler should be declared as follows:
</para>

<para>
<programlisting lang="en">
bool input_callback(Glib::IOCondition condition);
</programlisting>
</para>

<para lang="en">
where <parameter>condition</parameter> is as
specified above. As usual the slot is created with
<function>sigc::mem_fun()</function> (for a member method of an object), or
<function>sigc::ptr_fun()</function> (for a function).
</para>

<para lang="en">
A little example follows. To use the example just execute it from a terminal;
it doesn't create a window. It will create a pipe named
<literal>testfifo</literal> in the current directory. Then start another shell
and execute <literal>echo "Hello" &gt; testfifo</literal>. The example will
print each line you enter until you execute <literal>echo "Q" &gt;
testfifo</literal>.
</para>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/input/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;build/config.h&gt;
#include &lt;gtkmm/application.h&gt;
#include &lt;glibmm/main.h&gt;
#include &lt;glibmm/iochannel.h&gt;
#include &lt;fcntl.h&gt;
#include &lt;iostream&gt;

#include &lt;unistd.h&gt; //The SUN Forte compiler puts F_OK here.

//The SUN Forte compiler needs these for mkfifo:
#include &lt;sys/types.h&gt;
#include &lt;sys/stat.h&gt;

Glib::RefPtr&lt;Gtk::Application&gt; app;

int read_fd;
Glib::RefPtr&lt;Glib::IOChannel&gt; iochannel;

/*
  send to the fifo with:
  echo "Hello" &gt; testfifo

  quit the program with:
  echo "Q" &gt; testfifo
*/

// this will be our signal handler for read operations
// it will print out the message sent to the fifo
// and quit the program if the message was 'Q'.
bool MyCallback(Glib::IOCondition io_condition)
{
  if ((io_condition &amp; Glib::IO_IN) == 0) {
    std::cerr &lt;&lt; "Invalid fifo response" &lt;&lt; std::endl;
  }
  else {
   Glib::ustring buf;

   iochannel-&gt;read_line(buf);
   std::cout &lt;&lt; buf;
   if (buf == "Q\n")
     app-&gt;quit();

  }
  return true;
}


int main(int argc, char *argv[])
{
  app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  if (access("testfifo", F_OK) == -1) {
    // fifo doesn't exist - create it
    #ifdef HAVE_MKFIFO
    if (mkfifo("testfifo", 0666) != 0) {
      std::cerr &lt;&lt; "error creating fifo" &lt;&lt; std::endl;
      return -1;
    }
    #else
      std::cerr &lt;&lt; "error creating fifo: This platform does not have mkfifo()"
          &lt;&lt; std::endl;
    #endif //HAVE_MKFIFO
  }

  read_fd = open("testfifo", O_RDONLY);
  if (read_fd == -1)
  {
    std::cerr &lt;&lt; "error opening fifo" &lt;&lt; std::endl;
    return -1;
  }

  // connect the signal handler
  Glib::signal_io().connect(sigc::ptr_fun(MyCallback), read_fd, Glib::IO_IN);

  // Creates a iochannel from the file descriptor
  iochannel = Glib::IOChannel::create_from_fd(read_fd);

  // and last but not least - run the application main loop
  app-&gt;hold(); // keep the application running without a window
  app-&gt;run();

  // now remove the temporary fifo
  if(unlink("testfifo"))
    std::cerr &lt;&lt; "error removing fifo" &lt;&lt; std::endl;

  return 0;
}
</programlisting>
<!-- end inserted example code -->

</sect1>

<sect1 id="sec-idle-functions">
<title>Funções ociosas</title>

<para lang="en">
If you want to specify a method that gets called when nothing else is happening, use the following:
</para>

<para>
<programlisting lang="en">
sigc::connection  Glib::SignalIdle::connect(const sigc::slot&lt;bool&gt;&amp; slot,
                                    int priority = Glib::PRIORITY_DEFAULT_IDLE);
</programlisting>
</para>

<para lang="en">
This causes <application>gtkmm</application> to call the specified method whenever nothing else is
happening. You can add a priority (lower numbers are higher priorities). There are two ways to remove the signal handler: calling
<methodname>disconnect()</methodname> on the
<classname>sigc::connection</classname> object, or returning
<literal>false</literal> in the signal handler, which should be declared
as follows:
</para>

<para>
<programlisting lang="en">
bool idleFunc();
</programlisting>
</para>

<para lang="en">
Since this is very similar to the methods above this explanation should
be sufficient to understand what's going on. However, here's a little example:
</para>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/idle/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>idleexample.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_IDLEEXAMPLE_H
#define GTKMM_EXAMPLE_IDLEEXAMPLE_H

#include &lt;gtkmm.h&gt;
#include &lt;iostream&gt;

class IdleExample : public Gtk::Window
{
public:
  IdleExample();

protected:
  // Signal Handlers:
  bool on_timer();
  bool on_idle();
  void on_button_clicked();

  // Member data:
  Gtk::Box m_Box;
  Gtk::Button m_ButtonQuit;
  Gtk::ProgressBar m_ProgressBar_c;
  Gtk::ProgressBar m_ProgressBar_d;
};

#endif // GTKMM_EXAMPLE_IDLEEXAMPLE_H
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "idleexample.h"
#include &lt;gtkmm/application.h&gt;

int main (int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  IdleExample example;
  return app-&gt;run(example);
}
</programlisting>
<para lang="en">File: <filename>idleexample.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "idleexample.h"

IdleExample::IdleExample() :
  m_Box(Gtk::ORIENTATION_VERTICAL, 5),
  m_ButtonQuit("_Quit", true)
{
  set_border_width(5);

  // Put buttons into container

  // Adding a few widgets:
  add(m_Box);
  m_Box.pack_start( *Gtk::manage(new Gtk::Label("Formatting Windows drive C:")));
  m_Box.pack_start( *Gtk::manage(new Gtk::Label("100 MB")) );
  m_Box.pack_start(m_ProgressBar_c);

  m_Box.pack_start( *Gtk::manage(new Gtk::Label("")) );

  m_Box.pack_start( *Gtk::manage(new Gtk::Label("Formatting Windows drive D:")));
  m_Box.pack_start( *Gtk::manage(new Gtk::Label("5000 MB")) );
  m_Box.pack_start(m_ProgressBar_d);

  Gtk::Box* hbox = Gtk::manage( new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL,10));
  m_Box.pack_start(*hbox);
  hbox-&gt;pack_start(m_ButtonQuit, Gtk::PACK_EXPAND_PADDING);

  // Connect the signal handlers:
  m_ButtonQuit.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;IdleExample::on_button_clicked) );

  // formatting drive c in timeout signal handler - called once every 50ms
  Glib::signal_timeout().connect( sigc::mem_fun(*this, &amp;IdleExample::on_timer),
          50 );

  // formatting drive d in idle signal handler - called as quickly as possible
  Glib::signal_idle().connect( sigc::mem_fun(*this, &amp;IdleExample::on_idle) );

  show_all_children();
}


void IdleExample::on_button_clicked()
{
  hide();
}

// this timer callback function is executed once every 50ms (set in connection
// above).  Use timeouts when speed is not critical. (ie periodically updating
// something).
bool IdleExample::on_timer()
{
  double value = m_ProgressBar_c.get_fraction();

  // Update progressbar 1/500th each time:
  m_ProgressBar_c.set_fraction(value + 0.002);
 
  return value &lt; 0.99;  // return false when done
}


// This idle callback function is executed as often as possible, hence it is
// ideal for processing intensive tasks.
bool IdleExample::on_idle()
{
  double value = m_ProgressBar_d.get_fraction();

  // Update progressbar 1/5000th each time:
  m_ProgressBar_d.set_fraction(value + 0.0002);

  return value &lt; 0.99;  // return false when done
}
</programlisting>
<!-- end inserted example code -->

<para lang="en">
This example points out the difference of idle and timeout methods a
little. If you need methods that are called periodically, and speed
is not very important, then you want timeout methods. If
you want methods that are called as often as possible (like
calculating a fractal in background), then use idle methods.
</para>

<para lang="en">
Try executing the example and increasing the system load. The upper
progress bar will increase steadily; the lower one will slow down.
</para>

</sect1>

</chapter>

<chapter id="chapter-memory">
<title>Gerenciamento de memória</title>

<sect1 id="sec-memory-widgets">
<title>Widgets</title>

<sect2 id="memory-normal">
<title>Gerenciamento de memória normal em C++</title>

<para lang="en">
<application>gtkmm</application> allows the programmer to control the lifetime (that is, the construction
and destruction) of any widget in the same manner as any other C++ object.
This flexibility allows you to use <literal>new</literal> and
<literal>delete</literal> to create and destroy objects dynamically
or to use regular class members (that are destroyed automatically when the
class is destroyed) or to use local instances (that are destroyed when the
instance goes out of scope). This flexibility is not present in some C++ GUI
toolkits, which restrict the programmer to only a subset of C++'s memory
management features.
</para>

<para lang="en">Here are some examples of normal C++ memory management:</para>

<sect3 id="memory-class-scope">
<title lang="en">Class Scope widgets</title>

<para lang="en">
If a programmer does not need dynamic memory allocation, automatic widgets in class
scope may be used. One advantage of automatic widgets in class scope is that
memory management is grouped in one place. The programmer does not
risk memory leaks from failing to <literal>delete</literal> a widget.
</para>

<para lang="en">
The primary disadvantage of using class scope widgets is revealing
the class implementation rather than the class interface in the class header.
</para>

<para>
<programlisting lang="en">
#include &lt;gtkmm/button.h&gt;
#include &lt;gtkmm/window.h&gt;
class Foo : public Gtk::Window
{
private:
  Gtk::Button theButton;
  // will be destroyed when the Foo object is destroyed
};
</programlisting>
</para>
</sect3>

<sect3 id="memory-function-scope">
<title lang="en">Function scope widgets</title>

<para lang="en">
If a programmer does not need a class scope widget, a function scope widget
may also be used. The advantages to function scope over class scope are the
increased data hiding and reduced dependencies.
<programlisting lang="en">
{
  Gtk::Button aButton;
  aButton.show();
  ...
  app-&gt;run();
}
</programlisting>
</para>
</sect3>

<sect3 id="memory-dynamic-allocation">
<title lang="en">Dynamic allocation with new and delete</title>

<para lang="en">
Although, in most cases, the programmer will prefer to allow containers to
automatically destroy their children using <function>Gtk::manage()</function> (see
below), the programmer is not required to use <function>Gtk::manage()</function>.
The traditional <literal>new</literal> and <literal>delete</literal> operators
may also be used.
<programlisting lang="en">
Gtk::Button* pButton = new Gtk::Button("Test");

// do something useful with pButton

delete pButton;
</programlisting>
Here, the programmer deletes <varname>pButton</varname> to prevent a memory leak.
</para>
</sect3>

</sect2>

<sect2 id="memory-managed-widgets">
<title>Widgets gerenciados</title>

<para lang="en">
Alternatively, you can let a widget's container control when the widget is
destroyed. In most cases, you want a widget to last only as long as the
container it is in. To delegate the management of a widget's lifetime to its
container, first create it with <function>Gtk::manage()</function> and
pack it into its container with <methodname>Gtk::Container::add()</methodname>,
<methodname>Gtk::Box::pack_start()</methodname>, or a similar method. Now the
widget will be destroyed whenever its container is destroyed.
</para>

<sect3 id="memory-managed-dynamic">
<title lang="en">Dynamic allocation with manage() and add()</title>

<para lang="en">
<application>gtkmm</application> provides the <function>manage()</function> function and
<methodname>add()</methodname> methods to create and destroy widgets. Every widget
except a top-level window must be added or packed into a container in order to
be displayed. The <function>manage()</function> function marks a widget
so that when the widget is added to a container, the container becomes
responsible for deleting the widget.
</para>

<para lang="en">
<programlisting lang="en">
MyContainer::MyContainer()
{
  Gtk::Button* pButton = Gtk::manage(new Gtk::Button("Test"));
  add(*pButton); //add *pButton to MyContainer
}
</programlisting>
Now, when objects of type <classname>MyContainer</classname> are destroyed, the
button will also be deleted. It is no longer necessary to delete <varname>pButton</varname>
to free the button's memory; its deletion has been delegated to the
<classname>MyContainer</classname> object.
</para>

<para lang="en">
Of course, a top-level container will not be added to another container. The
programmer is responsible for destroying the top-level container using one of
the traditional C++ techniques. For instance, your top-level Window might just
be an instance in your <function>main()</function> function.
</para>

</sect3>
</sect2>
</sect1>

<sect1 id="sec-memory-shared-resources">
<title>Recursos compartilhados</title>

<para lang="en">
Some objects, such as <classname>Gdk::Pixbuf</classname>s and
<classname>Pango::Font</classname>s, are obtained from a shared store.
Therefore you cannot instantiate your own instances. These classes typically
inherit from <classname>Glib::Object</classname>. Rather than requiring you to
reference and unreference these objects, <application>gtkmm</application> uses the
<classname>Glib::RefPtr&lt;&gt;</classname> smartpointer. Cairomm has its own
smartpointer, <classname>Cairo::RefPtr&lt;&gt;</classname>.
</para>

<para lang="en">
Objects such as <classname>Gdk::Pixbuf</classname> can only be instantiated
with a <methodname>create()</methodname> function. For instance,
<programlisting lang="en">
Glib::RefPtr&lt;Gdk::Pixbuf&gt; pixbuf = Gdk::Pixbuf::create_from_file(filename);
</programlisting>
</para>

<para lang="en">
You have no way of getting a bare <classname>Gdk::Pixbuf</classname>. In the
example, <varname>pixbuf</varname> is a smart pointer, so you can do this, much
like a normal pointer:
<programlisting lang="en">
int width = 0;
if(pixbuf)
{
  width = pixbuf-&gt;get_width();
}
</programlisting>
</para>

<para lang="en">
When <varname>pixbuf</varname> goes out of scope an
<methodname>unref()</methodname> will happen in the background and you don't need
to worry about it anymore. There's no <literal>new</literal> so there's no
<literal>delete</literal>.
</para>
<para lang="en">
If you copy a <classname>RefPtr</classname>, for instance
<programlisting lang="en">
Glib::RefPtr&lt;Gdk::Pixbuf&gt; pixbuf2 = pixbuf;
</programlisting>
, or if you pass it as a method argument or a return type, then
<classname>RefPtr</classname> will do any necessary referencing to ensure that
the instance will not be destroyed until the last <classname>RefPtr</classname>
has gone out of scope.
</para>
<para>Veja o <link linkend="chapter-refptr">apêndice</link> para obter informações detalhadas sobre RefPtr.</para>
<para lang="en">
If you wish to learn more about smartpointers, you might look in these
books:
<itemizedlist>
<listitem><para lang="en">
Bjarne Stroustrup, "The C++ Programming Language" Forth Edition - section 34.3
</para></listitem>
<listitem><para lang="en">
Nicolai M. Josuttis, "The C++ Standard Library" - section 4.2
</para></listitem>
</itemizedlist>
</para>

</sect1>

</chapter>

<chapter id="chapter-builder">
<title>Glade e Gtk::Builder</title>
<para lang="en">
Although you can use C++ code to instantiate and arrange widgets, this
can soon become tedious and repetitive. And it requires a recompilation to show
changes. The <application>Glade</application> application allows you to layout
widgets on screen and then save an XML description of the arrangement. Your
application can then use the <application>Gtk::Builder</application> API to load
that XML file at runtime and obtain a pointer to specifically named widget
instances.
</para>

<para lang="en">
This has the following advantages:
<orderedlist>
<listitem><simpara lang="en">Less C++ code is required.</simpara></listitem>
<listitem><simpara lang="en">UI changes can be seen more quickly, so UIs are able to improve.</simpara></listitem>
<listitem><simpara lang="en">Designers without programming skills can create and edit UIs.</simpara></listitem>
</orderedlist>
</para>

<para lang="en">
You still need C++ code to deal with User Interface changes triggered by user
actions, but using <application>Gtk::Builder</application> for the widget
layout allows you to focus on implementing that functionality.
</para>

<sect1 id="sec-builder-loading-glade-file">
<title>Carregando arquivos .glade</title>
<para lang="en">
<classname>Gtk::Builder</classname> must be used via a
<classname>Glib::RefPtr</classname>. Like all such classes, you need to use a
<methodname>create()</methodname> method to instantiate it. For instance,
<programlisting lang="en">
Glib::RefPtr&lt;Gtk::Builder&gt; builder = Gtk::Builder::create_from_file("basic.glade");
</programlisting>
This will instantiate the windows defined in the .glade file, though they will
not be shown immediately unless you have specified that via the <guilabel>Properties</guilabel>
window in <application>Glade</application>.
</para>

<para lang="en">To instantiate just one window, or just one of the child widgets, you can specify the name of a widget as the second parameter. For instance,
<programlisting lang="en">
Glib::RefPtr&lt;Gtk::Builder&gt; builder = Gtk::Builder::create_from_file("basic.glade", "treeview_products");
</programlisting>
</para>

</sect1>

<sect1 id="sec-builder-accessing-widgets">
<title>Acessando widgets</title>

<para lang="en">
To access a widget, for instance to <methodname>show()</methodname> a dialog, use
the <methodname>get_widget()</methodname> method, providing the widget's name. This
name should be specified in the <application>Glade</application> Properties
window. If the widget could not be found, or is of the wrong type, then the
pointer will be set to 0.
<programlisting lang="en">
Gtk::Dialog* pDialog = 0;
builder-&gt;get_widget("DialogBasic", pDialog);
</programlisting>
</para>

<para lang="en">
<application>Gtk::Builder</application> checks for a null pointer, and checks
that the widget is of the expected type, and will show warnings on the command
line about these.
</para>

<para lang="en">
Remember that you are not instantiating a widget with
<methodname>get_widget()</methodname>, you are just obtaining a pointer to one that
already exists. You will always receive a pointer to the same instance when you
call <methodname>get_widget()</methodname> on the same
<classname>Gtk::Builder</classname>, with the same widget name. The
widgets are instantiated during <methodname>Gtk::Builder::create_from_file()</methodname>.
</para>

<para lang="en">
<methodname>get_widget()</methodname> returns child widgets that are
<function>manage()</function>ed (see the <link linkend="chapter-memory">Memory
Management</link> chapter), so they will be deleted when their parent
container is deleted. So, if you get only a child widget from
<application>Gtk::Builder</application>, instead of a whole window, then you must
either put it in a <classname>Container</classname> or delete it.
<classname>Windows</classname> (such as <classname>Dialogs</classname>) cannot
be managed because they have no parent container, so you must delete them at
some point.
</para>

<sect2 id="builder-example-loading">
<title>Exemplo</title>
<para lang="en">
This simple example shows how to load a <application>Glade</application> file at runtime and access the widgets with
<application>Gtk::Builder</application>.
</para>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/builder/basic?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;gtkmm.h&gt;
#include &lt;iostream&gt;

Gtk::Dialog* pDialog = 0;

static
void on_button_clicked()
{
  if(pDialog)
    pDialog-&gt;hide(); //hide() will cause main::run() to end.
}

int main (int argc, char **argv)
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  //Load the GtkBuilder file and instantiate its widgets:
  Glib::RefPtr&lt;Gtk::Builder&gt; refBuilder = Gtk::Builder::create();
  try
  {
    refBuilder-&gt;add_from_file("basic.glade");
  }
  catch(const Glib::FileError&amp; ex)
  {
    std::cerr &lt;&lt; "FileError: " &lt;&lt; ex.what() &lt;&lt; std::endl;
    return 1;
  }
  catch(const Glib::MarkupError&amp; ex)
  {
    std::cerr &lt;&lt; "MarkupError: " &lt;&lt; ex.what() &lt;&lt; std::endl;
    return 1;
  }
  catch(const Gtk::BuilderError&amp; ex)
  {
    std::cerr &lt;&lt; "BuilderError: " &lt;&lt; ex.what() &lt;&lt; std::endl;
    return 1;
  }

  //Get the GtkBuilder-instantiated Dialog:
  refBuilder-&gt;get_widget("DialogBasic", pDialog);
  if(pDialog)
  {
    //Get the GtkBuilder-instantiated Button, and connect a signal handler:
    Gtk::Button* pButton = 0;
    refBuilder-&gt;get_widget("quit_button", pButton);
    if(pButton)
    {
      pButton-&gt;signal_clicked().connect( sigc::ptr_fun(on_button_clicked) );
    }

    app-&gt;run(*pDialog);
  }

  delete pDialog;

  return 0;
}
</programlisting>
<!-- end inserted example code -->

</sect2>

</sect1>


<sect1 id="sec-builder-using-derived-widgets">
<title>Usando widgets derivados</title>
<para lang="en">
You can use <application>Glade</application> to layout your own custom widgets
derived from <application>gtkmm</application> widget classes. This keeps your code organized and
encapsulated. Of course you won't see the exact appearance and properties of
your derived widget in <application>Glade</application>, but you can specify
its location and child widgets and the properties of its <application>gtkmm</application> base class.
</para>

<para lang="en">Use <methodname>Gtk::Builder::get_widget_derived()</methodname> like so:
<programlisting lang="en">
DerivedDialog* pDialog = 0;
builder-&gt;get_widget_derived("DialogBasic", pDialog);
</programlisting>
</para>

<para lang="en">
Your derived class must have a constructor that takes a pointer to the
underlying C type, and the <classname>Gtk::Builder</classname> instance.
All relevant classes of <application>gtkmm</application> typedef their underlying C type as
<classname>BaseObjectType</classname> (<classname>Gtk::Dialog</classname>
typedefs <classname>BaseObjectType</classname> as <type>GtkDialog</type>, for instance).
</para>
<para lang="en">
You must call the base class's constructor in the initialization list, providing the C pointer. For
instance,
<programlisting lang="en">
DerivedDialog::DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; builder)
: Gtk::Dialog(cobject)
{
}
</programlisting>
</para>

<para lang="en">
You could then encapsulate the manipulation of the child widgets in the
constructor of the derived class, maybe using <methodname>get_widget()</methodname>
or <methodname>get_widget_derived()</methodname> again. For instance,
<programlisting lang="en">
DerivedDialog::DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; builder)
: Gtk::Dialog(cobject),
  m_builder(builder),
  m_pButton(0)
{
  //Get the Glade-instantiated Button, and connect a signal handler:
  m_builder-&gt;get_widget("quit_button", m_pButton);
  if(m_pButton)
  {
    m_pButton-&gt;signal_clicked().connect( sigc::mem_fun(*this, &amp;DerivedDialog::on_button_quit) );
  }
}
</programlisting>
</para>

<sect2 id="builder-example-accessing">
<title>Exemplo</title>
<para lang="en">
This example shows how to load a <application>Glade</application> file at runtime and access the widgets via a derived class.
</para>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/builder/derived?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>deriveddialog.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_DERIVED_DIALOG_H
#define GTKMM_EXAMPLE_DERIVED_DIALOG_H

#include &lt;gtkmm.h&gt;


class DerivedDialog : public Gtk::Dialog
{
public:
  DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; refGlade);
  virtual ~DerivedDialog();

protected:
  //Signal handlers:
  void on_button_quit();

  Glib::RefPtr&lt;Gtk::Builder&gt; m_refGlade;
  Gtk::Button* m_pButton;
};

#endif //GTKMM_EXAMPLE_DERIVED_WINDOW_H
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "deriveddialog.h"
#include &lt;iostream&gt;

int main (int argc, char **argv)
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  //Load the Glade file and instiate its widgets:
  Glib::RefPtr&lt;Gtk::Builder&gt; refBuilder = Gtk::Builder::create();
  try
  {
    refBuilder-&gt;add_from_file("derived.glade");
  }
  catch(const Glib::FileError&amp; ex)
  {
    std::cerr &lt;&lt; "FileError: " &lt;&lt; ex.what() &lt;&lt; std::endl;
    return 1;
  }
  catch(const Glib::MarkupError&amp; ex)
  {
    std::cerr &lt;&lt; "MarkupError: " &lt;&lt; ex.what() &lt;&lt; std::endl;
    return 1;
  }
  catch(const Gtk::BuilderError&amp; ex)
  {
    std::cerr &lt;&lt; "BuilderError: " &lt;&lt; ex.what() &lt;&lt; std::endl;
    return 1;
  }

  //Get the GtkBuilder-instantiated dialog::
  DerivedDialog* pDialog = 0;
  refBuilder-&gt;get_widget_derived("DialogDerived", pDialog);
  if(pDialog)
  {
    //Start:
    app-&gt;run(*pDialog);
  }

  delete pDialog;

  return 0;
}
</programlisting>
<para lang="en">File: <filename>deriveddialog.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "deriveddialog.h"

DerivedDialog::DerivedDialog(BaseObjectType* cobject, const Glib::RefPtr&lt;Gtk::Builder&gt;&amp; refGlade)
: Gtk::Dialog(cobject),
  m_refGlade(refGlade),
  m_pButton(0)
{
  //Get the Glade-instantiated Button, and connect a signal handler:
  m_refGlade-&gt;get_widget("quit_button", m_pButton);
  if(m_pButton)
  {
    m_pButton-&gt;signal_clicked().connect( sigc::mem_fun(*this, &amp;DerivedDialog::on_button_quit) ); 
  }
}

DerivedDialog::~DerivedDialog()
{
}

void DerivedDialog::on_button_quit()
{
  hide(); //hide() will cause main::run() to end.
}
</programlisting>
<!-- end inserted example code -->

</sect2>

</sect1>

</chapter>

<chapter id="chapter-internationalization">
  <title>Internacionalização e localização</title>

  <para lang="en">
    <application>gtkmm</application> applications can easily support multiple languages, including
    non-European languages such as Chinese and right-to-left languages such as
    Arabic. An appropriately-written and translated <application>gtkmm</application> application will use
    the appropriate language at runtime based on the user's environment.
  </para>
  <para lang="en">
    You might not anticipate the need to support additional languages, but
    you can never rule it out. And it's easier to develop the application
    properly in the first place rather than retrofitting later.
  </para>

  <para lang="en">
    The process of writing source code that allows for translation is called
    <literal>internationalization</literal>, often abbreviated to
    <literal>i18n</literal>. The <literal>Localization</literal> process,
    sometimes abbreviated as <literal>l10n</literal>, provides translated text
    for other languages, based on that source code.
  </para>

  <para lang="en">
    The main activity in the internationalization process is finding strings
    seen by users and marking them for translation. You do not need to do it all
    at once - if you set up the necessary project infrastructure correctly then
    your application will work normally regardless of how many strings you've
    covered.
  </para>

  <para lang="en">
    String literals should be typed in the source code in English, but
    surrounded by a macro. The <application>gettext</application> (or intltool)
    utility can then extract the marked strings for translation, and substitute
    the translated text at runtime.
  </para>

  <sect1 id="sec-internationalization-intro">
    <title>Preparando seu projeto</title>

    <note>
      <para lang="en">
        In the instructions below we will assume that you will not be using
        <application>gettext</application> directly, but
        <application>intltool</application>, which was written specifically for
        <literal>GNOME</literal>. <application>intltool</application> uses
        <function>gettext()</function>, which extracts strings from source code,
        but <application>intltool</application> can also combine strings from
        other files, for example from desktop menu details, and GUI resource
        files such as <application>Glade</application> files, into standard
        <application>gettext</application> <filename>.pot/.po</filename> files.
      </para>
      <para lang="en">
        We also assume that you are using autotools (e.g.
        <application>automake</application> and
        <application>autoconf</application>) to build your project, and
        that you are using <ulink url="http://git.gnome.org/browse/gnome-common/tree/autogen.sh">
          <literal>./autogen.sh</literal> from
          <application>gnome-common</application></ulink>, which, among other
        things, takes care of some <application>intltool</application>
        initialization.
      </para>
    </note>

    <para lang="en">
      Create a sub-directory named <literal>po</literal> in your project's root
      directory. This directory will eventually contain all of your
      translations. Within it, create a file named <literal>LINGUAS</literal>
      and a file named <literal>POTFILES.in</literal>. It is common practice to
      also create a <literal>ChangeLog</literal> file in the
      <literal>po</literal> directory so that translators can keep track of
      translation changes.
    </para>

    <para lang="en">
      <literal>LINGUAS</literal> contains an alphabetically sorted list of codes
      identifying the languages for which your program is translated (comment
      lines starting with a <literal>#</literal> are ignored). Each language
      code listed in the <literal>LINGUAS</literal> file must have a
      corresponding <literal>.po</literal> file. So, if your program has German
      and Japanese translations, your <literal>LINGUAS</literal> file would
      look like this:
    </para>
    <programlisting lang="en"># keep this file sorted alphabetically, one language code per line
de
ja</programlisting>
    <para lang="en">
      (In addition, you'd have the files <literal>ja.po</literal> and
      <literal>de.po</literal> in your
      <literal>po</literal> directory which contain the German and Japanese
      translations, respectively.)
    </para>

    <para lang="en">
      <literal>POTFILES.in</literal> is a list of paths to all files which
      contain strings marked up for translation, starting from the project root
      directory. So for example, if your project sources were located in a
      subdirectory named <literal>src</literal>, and you had two files that
      contained strings that should be translated, your
      <literal>POTFILES.in</literal> file might look like this:
    </para>

    <programlisting lang="en">src/main.cc
src/other.cc</programlisting>

    <para lang="en">
      If you are using <application>gettext</application> directly, you can only
      mark strings for translation if they are in source code file. However, if
      you use <application>intltool</application>, you can mark strings for
      translation in a variety of other file formats, including
      <application>Glade</application> UI files, xml, <ulink url="http://standards.freedesktop.org/desktop-entry-spec/latest/">.desktop
        files</ulink> and several more. So, if you have designed some of the
      application UI in <application>Glade</application> then also add your
      <filename>.glade</filename> files to the list in
      <literal>POTFILES.in</literal>.
    </para>

    <para lang="en">
      Now that there is a place to put your translations, you need to initialize
      <application>intltool</application> and <application>gettext</application>.
      Add the following code to your <literal>configure.ac</literal>,
      substituting 'programname' with the name of your program:
    </para>

    <programlisting lang="en">IT_PROG_INTLTOOL([0.35.0])

GETTEXT_PACKAGE=programname
AC_SUBST(GETTEXT_PACKAGE)
AC_DEFINE_UNQUOTED([GETTEXT_PACKAGE], ["$GETTEXT_PACKAGE"],
                   [The domain to use with gettext])
AM_GLIB_GNU_GETTEXT

PROGRAMNAME_LOCALEDIR=[${datadir}/locale]
AC_SUBST(PROGRAMNAME_LOCALEDIR)</programlisting>

    <para lang="en">
      This <varname>PROGRAMNAME_LOCALEDIR</varname> variable will be used later
      in the <literal>Makefile.am</literal> file, to define a macro that will be
      used when you initialize <application>gettext</application> in your source
      code.
    </para>

    <para lang="en">
      In the top-level Makefile.am:
      <itemizedlist>
        <listitem>
          <para lang="en">Add <literal>po</literal> to the <literal>SUBDIRS</literal>
            variable. Without this, your translations won't get built and
            installed when you build the program</para>
        </listitem>
        <listitem>
          <para lang="en">
            Define <literal>INTLTOOL_FILES</literal> as:
            <programlisting lang="en">INTLTOOL_FILES = intltool-extract.in \
                 intltool-merge.in \
                 intltool-update.in</programlisting>
          </para>
        </listitem>
        <listitem>
          <para lang="en">
            Add <literal>INTLTOOL_FILES</literal> to the
            <literal>EXTRA_DIST</literal> list of files. This ensures that when
            you do a <command>make dist</command>, these commands will be
            included in the source tarball.
          </para>
        </listitem>
        <listitem>
          <para lang="en">
            Update your <literal>DISTCLEANFILES</literal>:
            <programlisting lang="en">DISTCLEANFILES = ... intltool-extract \
                 intltool-merge \
                 intltool-update \
                 po/.intltool-merge-cache</programlisting>
          </para>
        </listitem>
      </itemizedlist>
    </para>

    <para lang="en">
      In your <literal>src/Makefile.am</literal>, update your
      <literal>AM_CPPFLAGS</literal> to add the following preprocessor macro
      definition:
    </para>
    <programlisting lang="en">AM_CPPFLAGS = ... -DPROGRAMNAME_LOCALEDIR=\"${PROGRAMNAME_LOCALEDIR}\"</programlisting>
    <para lang="en">
      This macro will be used when you initialize <literal>gettext</literal> in
      your source code.
    </para>
  </sect1>

<sect1 id="sec-i18n-marking-strings">
  <title>Marcando strings para tradução</title>

  <para lang="en">
    String literals should be typed in the source code in English, but
    they should be surrounded by a call to the <function>gettext()</function>
    function. These strings will be extracted for translation and the
    translations may be used at runtime instead of the original English
    strings.
  </para>

  <para lang="en">
    The <application>GNU gettext</application> package allows you to mark
    strings in source code, extract those strings for translation, and use
    the translated strings in your application.
  </para>

  <para lang="en">
    However, <application>Glib</application> defines
    <function>gettext()</function>
    support macros which are shorter wrappers in an easy-to-use form.
    To use these macros, include <literal>&lt;glibmm/i18n.h&gt;</literal>,
    and then, for example, substitute:
    <programlisting lang="en">display_message("Getting ready for i18n.");</programlisting>
    with:
    <programlisting lang="en">display_message(_("Getting ready for i18n."));</programlisting>
  </para>

  <para lang="en">
    For reference, it is possible to generate a file which contains all
    strings which appear in your code, even if they are not marked for translation,
    together with file name and line
    number references. To generate such a file named
    <literal>my-strings</literal>, execute the following command,
    within the source code directory:

    <programlisting lang="en">xgettext -a -o my-strings --omit-header *.cc *.h</programlisting>
  </para>

  <para lang="en">
    Finally, to let your program use the translation for the current locale,
    add this code to the beginning of your <filename>main.cc</filename> file, to initialize gettext.

<programlisting lang="en">bindtextdomain(GETTEXT_PACKAGE, PROGRAMNAME_LOCALEDIR);
bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
textdomain(GETTEXT_PACKAGE);</programlisting>
  </para>

  <sect2 id="sec-i18n-gettext">
    <title>Como funciona o gettext</title>

    <para lang="en">
      <application>intltool</application> /
      <application>xgettext</application> script extracts the strings
      and puts them in a <filename>mypackage.pot</filename> file.
      The translators of your application create their translations by
      first copying this <filename>.pot</filename> file to a
      <filename>localename.po</filename> file. A locale identifies a
      language and an encoding for that language, including date and numerical
      formats. Later, when the text in your source code has changed, the
      <literal>msmerge</literal> script is used to update the
      <filename>localename.po</filename> files from the regenerated
      <filename>.pot</filename> file.
    </para>

    <para lang="en">
      At install time, the <filename>.po</filename> files are converted to
      a binary format (with the extension <filename>.mo</filename>) and
      placed in a system-wide directory for locale files, for example
      <filename>/usr/share/locale/</filename>.
    </para>

    <para lang="en">
      When the application runs, the <application>gettext</application>
      library checks the system-wide directory to see if there is a
      <filename>.mo</filename> file for the user's locale environment
      (you can set the locale with, for instance, "export LANG=de_DE.UTF-8"
      from a bash console). Later, when the program reaches a
      <literal>gettext</literal> call, it looks for a translation of a
      particular string. If none is found, the original string is used.
    </para>
  </sect2>

  <sect2 id="sec-i18n-testing">
    <title>Testando e adicionando traduções</title>

    <para lang="en">
      To convince yourself that you've done well, you may wish to add a
      translation for a new locale. In order to do that, go to the
      <filename>po</filename> subdirectory of your project and
      execute the following command:
      <programlisting lang="en">intltool-update --pot</programlisting>
    </para>

    <para lang="en">
      That will create a file named <filename>programname.pot</filename>.
      Now copy that file to <filename>languagecode.po</filename>, such as
      <filename>de.po</filename> or <filename>hu.po</filename>. Also add
      that language code to <literal>LINGUAS</literal>. The
      <filename>.po</filename> file contains a header and a list of English strings,
      with space for the translated strings to be entered. Make sure you set the
      encoding of the <filename>.po</filename> file (specified in the header, but
      also as content) to <literal>UTF-8</literal>.
    </para>

    <!-- TODO: This need more explanation. What's the point of the fuzzy tag then? murrayc -->
    <note>
      <para lang="en">
      It's possible that certain strings will be marked as
      <literal>fuzzy</literal> in the <filename>.po</filename> file.
      These translations will not substitute the original string. To make
      them appear, simply remove the <literal>fuzzy</literal> tag.
      </para>
    </note>
  </sect2>

  <sect2 id="sec-i18n-resources">
    <title>Recursos</title>

    <para lang="en">
      More information about what lies behind the internationalization and localization process
      is presented and demonstrated in:

      <itemizedlist>
        <listitem>
          <para lang="en">
            <ulink url="https://wiki.gnome.org/TranslationProject/DevGuidelines">
              L10N Guidelines for Developers</ulink>
          </para>
        </listitem>

        <listitem>
          <para lang="en">
            <ulink url="http://bazaar.launchpad.net/~intltool/intltool/trunk/view/head:/README">Intltool README</ulink>
          </para>
        </listitem>

        <listitem>
          <para lang="en">
            <ulink url="https://wiki.gnome.org/TranslationProject/GitHowTo">How to use Git for GNOME translators</ulink>
          </para>
        </listitem>

        <listitem>
          <para lang="en">
            <ulink url="http://www.gnu.org/software/gettext/manual/gettext.html">gettext manual</ulink>
          </para>
        </listitem>

        <listitem>
          <para lang="en">
            <ulink url="http://ftp.gnome.org/pub/GNOME/sources/gtkmm_hello/"><literal>gtkmm_hello</literal> example package</ulink>
          </para>
        </listitem>

        <listitem>
          <para lang="en">
            <ulink url="http://ftp.gnome.org/pub/GNOME/sources/gnomemm_hello/"><literal>gnomemm_hello</literal> example package</ulink>
          </para>
        </listitem>
      </itemizedlist>
    </para>
  </sect2>

</sect1>

<sect1 id="sec-i18n-expecting-utf8">
<title>Esperando UTF8</title>
<para lang="en">
A properly internationalized application will not make assumptions about the
number of bytes in a character. That means that you shouldn't use pointer
arithmetic to step through the characters in a string, and it means you
shouldn't use <classname>std::string</classname> or standard C functions such
as <function>strlen()</function> because they make the same assumption.
</para>
<para lang="en">
However, you probably already avoid bare char* arrays and pointer arithmetic by
using <classname>std::string</classname>, so you just need to start using
<classname>Glib::ustring</classname> instead. See the <link linkend="sec-basics-ustring">Basics</link> chapter about
<classname>Glib::ustring</classname>.
</para>

<sect2 id="i18n-ustring-iostreams"><title lang="en">Glib::ustring and std::iostreams</title>
<!-- <para>TODO: This section is not clear - it needs to spell things out more clearly and obviously.</para> -->
<para lang="en">
Unfortunately, the integration with the standard iostreams is not completely
foolproof. <application>gtkmm</application> converts <classname>Glib::ustring</classname>s to a
locale-specific encoding (which usually is not UTF-8) if you output them to an
<classname>ostream</classname> with <function>operator&lt;&lt;</function>.
Likewise, retrieving <classname>Glib::ustrings</classname> from
<classname>istream</classname> with <function>operator&gt;&gt;</function>
causes a conversion in the opposite direction. But this scheme breaks down if
you go through a <classname>std::string</classname>, e.g. by inputting text
from a stream to a <classname>std::string</classname> and then implicitly
converting it to a <classname>Glib::ustring</classname>. If the string
contained non-ASCII characters and the current locale is not UTF-8 encoded, the
result is a corrupted <classname>Glib::ustring</classname>. You can work around
this with a manual conversion. For instance, to retrieve the
<classname>std::string</classname> from a <classname>ostringstream</classname>:
<programlisting lang="en">std::ostringstream output;
output.imbue(std::locale("")); // use the user's locale for this stream
output &lt;&lt; percentage &lt;&lt; " % done";
label-&gt;set_text(Glib::locale_to_utf8(output.str()));</programlisting>
</para>
</sect2>

</sect1>

<sect1 id="sec-i18n-pitfalls">
      <title lang="en">Pitfalls</title>

      <para lang="en">There are a few common mistakes that you would discover eventually yourself. But this section might help you to avoid them.</para>

<sect2 id="i18n-string-semantics">
        <title>Mesmas strings, semânticas diferentes</title>

        <para lang="en">Sometimes two english strings are identical but have different meanings in
different contexts, so they would probably not be identical when translated. Since the English strings are
          used as look-up keys, this causes problems.</para>

<para lang="en">
In these cases, you should add extra characters to the strings. For instance,
use <literal>"jumps[noun]"</literal> and <literal>"jumps[verb]"</literal>
instead of just <literal>"jumps"</literal> and strip them again outside the
<function>gettext</function> call. If you add extra characters you should also
add a comment for the translators before the <function>gettext</function> call.
Such comments will be shown in the <filename>.po</filename> files. For
instance:
</para>

<programlisting lang="en">// note to translators: don't translate the "[noun]" part - it is
// just here to distinguish the string from another "jumps" string
text = strip(gettext("jumps[noun]"), "[noun]");</programlisting>
      </sect2>

<sect2 id="i18n-composition">
  <title>Composição de strings</title>

<para lang="en">
C programmers use <function>sprintf()</function> to compose and concatenate
strings. C++ favours streams, but unfortunately, this approach makes
translation difficult, because each fragment of text is translated separately,
without allowing the translators to rearrange them according to the grammar of
the language.</para>

<para lang="en">For instance, this code would be problematic:</para>

<programlisting lang="en">std::cout &lt;&lt; _("Current amount: ") &lt;&lt; amount
          &lt;&lt; _(" Future: ") &lt;&lt; future &lt;&lt; std::endl;

label.set_text(_("Really delete ") + filename + _(" now?"));</programlisting>

<para lang="en">
So you should either avoid this situation or use
<ulink url="http://developer.gnome.org/glibmm/unstable/classGlib_1_1ustring.html"><function>Glib::ustring::compose()</function></ulink>
which supports syntax such as:
<programlisting lang="en">std::cout &lt;&lt; Glib::ustring::compose(
             _("Current amount: %1 Future: %2"), amount, future) &lt;&lt; std::endl;

label.set_text(Glib::ustring::compose(_("Really delete %1 now?"), filename));</programlisting>
</para>
</sect2>

<sect2 id="i18n-display-size">
        <title lang="en">Assuming the displayed size of strings</title>

        <para lang="en">You never know how much space a string will take on screen when translated. It might very possibly be twice the size of the original English string. Luckily, most <application>gtkmm</application> widgets will expand at runtime to the required size.</para>
</sect2>

<sect2 id="i18n-unusual-words">
        <title>Palavras incomuns</title>

        <para lang="en">You should avoid cryptic abbreviations, slang, or jargon.
          They are usually difficult to translate, and are often difficult
for even native speakers to understand. For instance, prefer "application" to "app"</para>
</sect2>

<sect2 id="i18n-non-ascii-characters">
<title lang="en">Using non-ASCII characters in strings</title>

<para lang="en">
Currently, <application>gettext</application> does not support non-ASCII
characters (i.e. any characters with a code above 127) in source code. For
instance, you cannot use the copyright sign (©).
</para>

        <para lang="en">To work around this, you could write a comment in the
          source code just before the string, telling the translators to
          use the special character if it is available in their languages. For english, you could then make an American English
          <filename>en_US.po</filename> translation which used that special character.</para>
      </sect2>
    </sect1>

    <sect1 id="sec-i18n-getting-help-with-translations">
      <title lang="en">Getting help with translations</title>

      <para lang="en">If your program is free software, there is a whole <literal>GNOME</literal>
        subproject devoted to helping you make translations, the
        <ulink url="https://wiki.gnome.org/TranslationProject/"><literal>GNOME</literal>
        Translation Project</ulink>.</para>

      <para lang="en">The way it works is that you upload your source code to a git
        repository where translators can access it, then contact the gnome-i18n
        mailing list and ask to have your program added to the
        <ulink url="http://l10n.gnome.org/module/">list of modules to translate</ulink>.</para>

      <para lang="en">Then you make sure you update the file
        <filename>POTFILES.in</filename> in the
        <filename>po/</filename> subdirectory
        (<command>intltool-update -M</command> can help with this) so
        that the translators always access updated
        <filename>myprogram.pot</filename> files, and simply freeze
        the strings at least a couple of days before you make a new
        release, announcing it on gnome-i18n. Depending on the number
        of strings your program contains and how popular it is, the
        translations will then start to tick in as
        <filename>languagename.po</filename> files.</para>

      <para lang="en">Note that most language teams only consist of 1-3 persons,
        so if your program contains a lot of strings, it might last a
        while before anyone has the time to look at it. Also, most
        translators do not want to waste their time (translating is
        a very time-consuming task) so if they do not assess your
        project as being really serious (in the sense that it is
        polished and being maintained) they may decide to spend their
        time on some other project.</para>
    </sect1>
</chapter>

<chapter id="chapter-customwidgets">
    <title>Widgets personalizados</title>

    <para lang="en"><application>gtkmm</application> makes it very easy to derive new widgets by inheriting from an
      existing widget class, either by deriving from a container and adding child
      widgets, or by deriving from a single-item widget, and changing its behaviour.
      But you might occasionally find that no suitable starting point already exists.
      In this case, you can implement a widget from scratch.</para>

    <sect1 id="sec-custom-containers">
    <title>Contêiners personalizados</title>
    <para lang="en">When deriving from <classname>Gtk::Container</classname>, you should override the following virtual methods:
    <itemizedlist>
      <listitem><para lang="en"><methodname>get_request_mode_vfunc()</methodname>: Return what <literal>Gtk::SizeRequestMode</literal> is preferred by the container.</para></listitem>
      <listitem><para lang="en"><methodname>get_preferred_width_vfunc()</methodname>: Calculate the minimum and natural width of the container.</para></listitem>
      <listitem><para lang="en"><methodname>get_preferred_height_vfunc()</methodname>: Calculate the minimum and natural height of the container.</para></listitem>
      <listitem><para lang="en"><methodname>get_preferred_width_for_height_vfunc()</methodname>: Calculate the minimum and natural width of the container, if it would be given the specified height.</para></listitem>
      <listitem><para lang="en"><methodname>get_preferred_height_for_width_vfunc()</methodname>: Calculate the minimum and natural height of the container, if it would be given the specified width.</para></listitem>
      <listitem><para lang="en"><methodname>on_size_allocate()</methodname>: Position the child widgets, given the height and width that the container has actually been given.</para></listitem>
      <listitem><para lang="en"><methodname>forall_vfunc()</methodname>: Call the same callback for each of the children.</para></listitem>
      <listitem><para lang="en"><methodname>on_add()</methodname>: Add a child widget to the container.</para></listitem>
      <listitem><para lang="en"><methodname>on_remove()</methodname>: Remove a child widget from the container.</para></listitem>
      <listitem><para lang="en"><methodname>child_type_vfunc()</methodname>: Return what type of child can be added.</para></listitem>
    </itemizedlist>
    </para>

    <para lang="en">The <methodname>get_request_mode_vfunc()</methodname>,
        <methodname>get_preferred_width_vfunc()</methodname>,
        <methodname>get_preferred_height_vfunc()</methodname>,
        <methodname>get_preferred_width_for_height_vfunc()</methodname>,
        <methodname>get_preferred_height_for_width_vfunc()</methodname>, and
        <methodname>on_size_allocate()</methodname> virtual methods control the
        layout of the child widgets. For instance, if your container has 2
        child widgets, with one below the other, your
        <methodname>get_request_mode_vfunc()</methodname> might request
        height-for-width layout. Then your
        <methodname>get_preferred_width_vfunc()</methodname>
        might report the maximum of the widths of the child widgets, and
        <methodname>get_preferred_height_for_width_vfunc()</methodname>
        might report the sum of their heights. If you want padding between
        the child widgets then you would add that to the width and height too.
        Your widget's container will use this result to ensure that your widget
        gets enough space, and not less. By examining each widget's parent, and
        its parent, this logic will eventually decide the size of the top-level
        window.</para>

    <para lang="en">You are not guaranteed to get the <literal>Gtk::SizeRequestMode</literal>
        that you request. Therefore all four of the
        <methodname>get_preferred_xxx_vfunc()</methodname> methods must return
        sensible values.</para>

   <para lang="en"><methodname>on_size_allocate()</methodname> receives the actual
       height and width that the parent container has decided to give to your
       widget. This might be more than the minimum, or even more than the natural
       size, for instance if the
       top-level window has been expanded. You might choose to ignore the extra
       space and leave a blank area, or you might choose to expand your child
       widgets to fill the space, or you might choose to expand the padding
       between your widgets. It's your container, so you decide. Don't forget to
       call <methodname>set_allocation()</methodname> inside your
       <methodname>on_size_allocate()</methodname> implementation to actually use the
       allocated space that has been offered by the parent container.</para>

  <para lang="en">Unless your container is a top-level window that derives from
      <classname>Gtk::Window</classname>, you should probably also call
      <methodname>Gtk::Widget::set_has_window(false)</methodname> in your
      constructor. This means that your container does not create its own
      <classname>Gdk::Window</classname>, but uses its parent's
      window. (Note the difference between <classname>Gtk::Window</classname>
      and <classname>Gdk::Window</classname>.) If your container does need
      its own <classname>Gdk::Window</classname>, and does not derive from
      <classname>Gtk::Window</classname>, you must also override the
      <methodname>on_realize()</methodname> method as described in the
      <link linkend="sec-custom-widgets">Custom Widgets</link> section.
      And unless your container draws directly onto the underlying
      <classname>Gdk::Window</classname>, you should probably call
      <methodname>set_redraw_on_allocate(false)</methodname> to improve
      performance.</para>

  <para lang="en">By overriding <methodname>forall_vfunc()</methodname> you can allow
      applications to operate on all of the container's child widgets. For
      instance, <methodname>show_all_children()</methodname> uses this to find all
      the child widgets and show them.</para>

  <para lang="en">Although your container might have its own method to set the child
      widgets, you should still provide an implementation for the virtual
      <methodname>on_add()</methodname> and <methodname>on_remove()</methodname>
      methods from the base class, so that the add() and remove() methods will
      do something appropriate if they are called.</para>

  <para lang="en">Your implementation of the <methodname>child_type_vfunc()</methodname>
      method should report the type of widget that may be added to your
      container, if it is not yet full. This is usually
      <methodname>Gtk::Widget::get_type()</methodname> to indicate that the
      container may contain any class derived from
      <classname>Gtk::Widget</classname>. If the container may not contain any
      more widgets, then this method should return
      <literal>G_TYPE_NONE</literal>.</para>


<sect2 id="custom-container-example"><title>Exemplo</title>

    <para lang="en">This example implements a container with two child widgets, one above
        the other. Of course, in this case it would be far simpler just to use
        a vertical <classname>Gtk::Box</classname>.</para>

<figure id="figure-custom-container">
  <title>Contêiner personalizado</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/custom_container.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/custom/custom_container/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;
#include "mycontainer.h"

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_quit();

  //Child widgets:
  Gtk::Box m_VBox;
  MyContainer m_MyContainer;
  Gtk::Button m_Button_One;
  Gtk::Label m_Label_Two;
  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Quit;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>mycontainer.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_CUSTOM_CONTAINER_MYCONTAINER_H
#define GTKMM_CUSTOM_CONTAINER_MYCONTAINER_H

#include &lt;gtkmm/container.h&gt;

class MyContainer : public Gtk::Container
{
public:
  MyContainer();
  virtual ~MyContainer();

  void set_child_widgets(Gtk::Widget&amp; child_one, Gtk::Widget&amp; child_two);

protected:

  //Overrides:
  virtual Gtk::SizeRequestMode get_request_mode_vfunc() const;
  virtual void get_preferred_width_vfunc(int&amp; minimum_width, int&amp; natural_width) const;
  virtual void get_preferred_height_for_width_vfunc(int width, int&amp; minimum_height, int&amp; natural_height) const;
  virtual void get_preferred_height_vfunc(int&amp; minimum_height, int&amp; natural_height) const;
  virtual void get_preferred_width_for_height_vfunc(int height, int&amp; minimum_width, int&amp; natural_width) const;
  virtual void on_size_allocate(Gtk::Allocation&amp; allocation);

  virtual void forall_vfunc(gboolean include_internals, GtkCallback callback, gpointer callback_data);

  virtual void on_add(Gtk::Widget* child);
  virtual void on_remove(Gtk::Widget* child);
  virtual GType child_type_vfunc() const;

  Gtk::Widget* m_child_one;
  Gtk::Widget* m_child_two;
};

#endif //GTKMM_CUSTOM_CONTAINER_MYCONTAINER_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_One("Child One"),
  m_Label_Two("Child 2", Gtk::ALIGN_END, Gtk::ALIGN_CENTER),
  m_Button_Quit("Quit")
{
  set_title("Custom Container example");
  set_border_width(6);
  set_default_size(400, 200);

  add(m_VBox);

  //Add the child widgets to the custom container:
  m_MyContainer.set_child_widgets(m_Button_One, m_Label_Two);

  m_VBox.pack_start(m_MyContainer, Gtk::PACK_EXPAND_WIDGET);
  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);

  m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
  m_ButtonBox.set_border_width(6);
  m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
  m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this,
              &amp;ExampleWindow::on_button_quit) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_quit()
{
  hide();
}

</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<para lang="en">File: <filename>mycontainer.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include &lt;iostream&gt;
#include &lt;algorithm&gt; // std::max
#include "mycontainer.h"

MyContainer::MyContainer()
: m_child_one(0), m_child_two(0)
{
  set_has_window(false);
  set_redraw_on_allocate(false);
}

MyContainer::~MyContainer()
{
/*
  // These calls to Gtk::Widget::unparent() are necessary if MyContainer is
  // deleted before its children. But if you use a version of gtkmm where bug
  // https://bugzilla.gnome.org/show_bug.cgi?id=605728
  // has not been fixed (gtkmm 3.7.10 or earlier) and the children are deleted
  // before the container, these calls can make the program crash.
  // That's because on_remove() is not called, when the children are deleted.
  if (m_child_one)
    m_child_one-&gt;unparent();

  if (m_child_two)
    m_child_two-&gt;unparent();
*/
}

void MyContainer::set_child_widgets(Gtk::Widget&amp; child_one,
        Gtk::Widget&amp; child_two)
{
  m_child_one = &amp;child_one;
  m_child_two = &amp;child_two;

  m_child_one-&gt;set_parent(*this);
  m_child_two-&gt;set_parent(*this);
}

//This example container is a simplified VBox with at most two children.
Gtk::SizeRequestMode MyContainer::get_request_mode_vfunc() const
{
  return Gtk::SIZE_REQUEST_HEIGHT_FOR_WIDTH;
}

//Discover the total amount of minimum space and natural space needed by
//this container and its children.
void MyContainer::get_preferred_width_vfunc(int&amp; minimum_width, int&amp; natural_width) const
{
  int child_minimum_width[2] = {0, 0};
  int child_natural_width[2] = {0, 0};

  if(m_child_one &amp;&amp; m_child_one-&gt;get_visible())
    m_child_one-&gt;get_preferred_width(child_minimum_width[0], child_natural_width[0]);

  if(m_child_two &amp;&amp; m_child_two-&gt;get_visible())
    m_child_two-&gt;get_preferred_width(child_minimum_width[1], child_natural_width[1]);

  //Request a width equal to the width of the widest visible child.
  minimum_width = std::max(child_minimum_width[0], child_minimum_width[1]);
  natural_width = std::max(child_natural_width[0], child_natural_width[1]);
}

void MyContainer::get_preferred_height_for_width_vfunc(int width,
   int&amp; minimum_height, int&amp; natural_height) const
{
  int child_minimum_height[2] = {0, 0};
  int child_natural_height[2] = {0, 0};
  int nvis_children = 0;

  if(m_child_one &amp;&amp; m_child_one-&gt;get_visible())
  {
    ++nvis_children;
    m_child_one-&gt;get_preferred_height_for_width(width, child_minimum_height[0],
                                                child_natural_height[0]);
  }

  if(m_child_two &amp;&amp; m_child_two-&gt;get_visible())
  {
    ++nvis_children;
    m_child_two-&gt;get_preferred_height_for_width(width, child_minimum_height[1],
                                                child_natural_height[1]);
  }

  //The allocated height will be divided equally among the visible children.
  //Request a height equal to the number of visible children times the height
  //of the highest child.
  minimum_height = nvis_children * std::max(child_minimum_height[0],
                                            child_minimum_height[1]);
  natural_height = nvis_children * std::max(child_natural_height[0],
                                            child_natural_height[1]);
}

void MyContainer::get_preferred_height_vfunc(int&amp; minimum_height, int&amp; natural_height) const
{
  int child_minimum_height[2] = {0, 0};
  int child_natural_height[2] = {0, 0};
  int nvis_children = 0;

  if(m_child_one &amp;&amp; m_child_one-&gt;get_visible())
  {
    ++nvis_children;
    m_child_one-&gt;get_preferred_height(child_minimum_height[0], child_natural_height[0]);
  }

  if(m_child_two &amp;&amp; m_child_two-&gt;get_visible())
  {
    ++nvis_children;
    m_child_two-&gt;get_preferred_height(child_minimum_height[1], child_natural_height[1]);
  }

  //The allocated height will be divided equally among the visible children.
  //Request a height equal to the number of visible children times the height
  //of the highest child.
  minimum_height = nvis_children * std::max(child_minimum_height[0],
                                            child_minimum_height[1]);
  natural_height = nvis_children * std::max(child_natural_height[0],
                                            child_natural_height[1]);
}

void MyContainer::get_preferred_width_for_height_vfunc(int height,
   int&amp; minimum_width, int&amp; natural_width) const
{
  int child_minimum_width[2] = {0, 0};
  int child_natural_width[2] = {0, 0};
  int nvis_children = 0;

  //Get number of visible children.
  if(m_child_one &amp;&amp; m_child_one-&gt;get_visible())
    ++nvis_children;
  if(m_child_two &amp;&amp; m_child_two-&gt;get_visible())
    ++nvis_children;

  if(nvis_children &gt; 0)
  {
    //Divide the height equally among the visible children.
    const int height_per_child = height / nvis_children;

    if(m_child_one &amp;&amp; m_child_one-&gt;get_visible())
      m_child_one-&gt;get_preferred_width_for_height(height_per_child,
                   child_minimum_width[0], child_natural_width[0]);

    if(m_child_two &amp;&amp; m_child_two-&gt;get_visible())
      m_child_two-&gt;get_preferred_width_for_height(height_per_child,
                   child_minimum_width[1], child_natural_width[1]);
  }

  //Request a width equal to the width of the widest child.
  minimum_width = std::max(child_minimum_width[0], child_minimum_width[1]);
  natural_width = std::max(child_natural_width[0], child_natural_width[1]);
}

void MyContainer::on_size_allocate(Gtk::Allocation&amp; allocation)
{
  //Do something with the space that we have actually been given:
  //(We will not be given heights or widths less than we have requested, though
  //we might get more.)

  //Use the offered allocation for this container:
  set_allocation(allocation);

  //Get number of visible children.
  int nvis_children = 0;
  if(m_child_one &amp;&amp; m_child_one-&gt;get_visible())
    ++nvis_children;
  if(m_child_two &amp;&amp; m_child_two-&gt;get_visible())
    ++nvis_children;

  if(nvis_children &lt;= 0)
    return;

  //Assign space to the children:
  Gtk::Allocation child_allocation_one;
  Gtk::Allocation child_allocation_two;

  //Place the first child at the top-left:
  child_allocation_one.set_x( allocation.get_x() );
  child_allocation_one.set_y( allocation.get_y() );

  //Make it take up the full width available:
  child_allocation_one.set_width( allocation.get_width() );

  if(m_child_one &amp;&amp; m_child_one-&gt;get_visible())
  {
    //Divide the height equally among the visible children.
    child_allocation_one.set_height( allocation.get_height() / nvis_children);
    m_child_one-&gt;size_allocate(child_allocation_one);
  }
  else
    child_allocation_one.set_height(0);

  //Place the second child below the first child:
  child_allocation_two.set_x( allocation.get_x() );
  child_allocation_two.set_y( allocation.get_y() +
          child_allocation_one.get_height());

  //Make it take up the full width available:
  child_allocation_two.set_width( allocation.get_width() );

  //Make it take up the remaining height:
  child_allocation_two.set_height( allocation.get_height() -
          child_allocation_one.get_height());

  if(m_child_two &amp;&amp; m_child_two-&gt;get_visible())
    m_child_two-&gt;size_allocate(child_allocation_two);
}

void MyContainer::forall_vfunc(gboolean, GtkCallback callback, gpointer callback_data)
{
  if(m_child_one)
    callback(m_child_one-&gt;gobj(), callback_data);

  if(m_child_two)
    callback(m_child_two-&gt;gobj(), callback_data);
}

void MyContainer::on_add(Gtk::Widget* child)
{
  if(!m_child_one)
  {
    m_child_one = child;
    m_child_one-&gt;set_parent(*this);
  }
  else if(!m_child_two)
  {
    m_child_two = child;
    m_child_two-&gt;set_parent(*this);
  }
}

void MyContainer::on_remove(Gtk::Widget* child)
{
  if(child)
  {
    const bool visible = child-&gt;get_visible();
    bool found = false;

    if(child == m_child_one)
    {
      m_child_one = 0;
      found = true;
    }
    else if(child == m_child_two)
    {
      m_child_two = 0;
      found = true;
    }

    if(found)
    {
      child-&gt;unparent();

      if(visible)
        queue_resize();
    }
  }
}

GType MyContainer::child_type_vfunc() const
{
  //If there is still space for one widget, then report the type of widget that
  //may be added.
  if(!m_child_one || !m_child_two)
    return Gtk::Widget::get_type();
  else
  {
    //No more widgets may be added.
    return G_TYPE_NONE;
  }
}
</programlisting>
<!-- end inserted example code -->
</sect2>

    </sect1>

    <sect1 id="sec-custom-widgets">
    <title>Widgets personalizados</title>
    <para lang="en">By deriving directly from <classname>Gtk::Widget</classname> you can
        do all the drawing for your widget directly, instead of just arranging
        child widgets. For instance, a <classname>Gtk::Label</classname> draws
        the text of the label, but does not do this by using other
        widgets.</para>

    <para lang="en">When deriving from <classname>Gtk::Widget</classname>, you should
        override the following virtual methods. The methods marked (optional)
        need not be overridden in all custom widgets. The base class's methods
        may be appropriate.
    <itemizedlist>
      <listitem><para lang="en"><methodname>get_request_mode_vfunc()</methodname>: (optional) Return what <literal>Gtk::SizeRequestMode</literal> is preferred by the widget.</para></listitem>
      <listitem><para lang="en"><methodname>get_preferred_width_vfunc()</methodname>: Calculate the minimum and natural width of the widget.</para></listitem>
      <listitem><para lang="en"><methodname>get_preferred_height_vfunc()</methodname>: Calculate the minimum and natural height of the widget.</para></listitem>
      <listitem><para lang="en"><methodname>get_preferred_width_for_height_vfunc()</methodname>: Calculate the minimum and natural width of the widget, if it would be given the specified height.</para></listitem>
      <listitem><para lang="en"><methodname>get_preferred_height_for_width_vfunc()</methodname>: Calculate the minimum and natural height of the widget, if it would be given the specified width.</para></listitem>
      <listitem><para lang="en"><methodname>on_size_allocate()</methodname>: Position the widget, given the height and width that it has actually been given.</para></listitem>
      <listitem><para lang="en"><methodname>on_realize()</methodname>: Associate a <classname>Gdk::Window</classname> with the widget.</para></listitem>
      <listitem><para lang="en"><methodname>on_unrealize()</methodname>: (optional) Break the association with the <classname>Gdk::Window</classname>. </para></listitem>
      <listitem><para lang="en"><methodname>on_map()</methodname>: (optional)</para></listitem>
      <listitem><para lang="en"><methodname>on_unmap()</methodname>: (optional)</para></listitem>
      <listitem><para lang="en"><methodname>on_draw()</methodname>: Draw on the supplied <classname>Cairo::Context</classname>.</para></listitem>
    </itemizedlist>
    </para>

    <para lang="en">The first 6 methods in the previous table are also overridden in custom
        containers. They are briefly described in the
        <link linkend="sec-custom-containers">Custom Containers</link> section.
    </para>

    <para lang="en">Most custom widgets need their own <classname>Gdk::Window</classname>
      to draw on. Then you can call
      <methodname>Gtk::Widget::set_has_window(true)</methodname> in your
      constructor. (This is the default value.) If you do not call
      <methodname>set_has_window(false)</methodname>, you must override
      <methodname>on_realize()</methodname> and call
      <methodname>Gtk::Widget::set_realized()</methodname> and
      <methodname>Gtk::Widget::set_window()</methodname> from there.</para>

<sect2 id="custom-style-properties">
<title lang="en">Custom Style Properties</title>

<para lang="en">You can add style properties to your widget class, whether it's derived directly
from <classname>Gtk::Widget</classname> or from another widget class. The values of
the style properties can be read from a CSS (Cascading Style Sheets) file. The users
of your widget, or the users of an application program with your widget, can then
modify the style of your widget without modifying the source code.
Useful classes are <classname>Gtk::StyleProperty</classname> and <classname>Gtk::CssProvider</classname>.
With <methodname>Gtk::Widget::get_style_property()</methodname> you can read the values
of both your own style properties and those of your widget's base class. Note that style
properties are not wrapped in <application>gtkmm</application>. See <application>GTK+</application>'s
documentation for lists of existing style properties.
The following example shows a simple use of a custom style property.
</para>
</sect2>

<sect2 id="custom-widget-example"><title>Exemplo</title>

<para lang="en">This example implements a widget which draws a Penrose triangle.</para>

<figure id="figure-custom-widget">
  <title>Widget personalizado</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/custom_widget.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/custom/custom_widget/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>mywidget.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_CUSTOM_WIDGET_MYWIDGET_H
#define GTKMM_CUSTOM_WIDGET_MYWIDGET_H

#include &lt;gtkmm/widget.h&gt;
#include &lt;gtkmm/cssprovider.h&gt;
#include &lt;gtkmm/styleproperty.h&gt;

class MyWidget : public Gtk::Widget
{
public:
  MyWidget();
  virtual ~MyWidget();

protected:

  //Overrides:
  virtual Gtk::SizeRequestMode get_request_mode_vfunc() const;
  virtual void get_preferred_width_vfunc(int&amp; minimum_width, int&amp; natural_width) const;
  virtual void get_preferred_height_for_width_vfunc(int width, int&amp; minimum_height, int&amp; natural_height) const;
  virtual void get_preferred_height_vfunc(int&amp; minimum_height, int&amp; natural_height) const;
  virtual void get_preferred_width_for_height_vfunc(int height, int&amp; minimum_width, int&amp; natural_width) const;
  virtual void on_size_allocate(Gtk::Allocation&amp; allocation);
  virtual void on_map();
  virtual void on_unmap();
  virtual void on_realize();
  virtual void on_unrealize();
  virtual bool on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr);

  //Signal handler:
  void on_parsing_error(const Glib::RefPtr&lt;const Gtk::CssSection&gt;&amp; section, const Glib::Error&amp; error);

  Gtk::StyleProperty&lt;int&gt; m_scale_prop;
  Glib::RefPtr&lt;Gdk::Window&gt; m_refGdkWindow;
  Glib::RefPtr&lt;Gtk::CssProvider&gt; m_refCssProvider;

  int m_scale;
};

#endif //GTKMM_CUSTOM_WIDGET_MYWIDGET_H
</programlisting>
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;
#include "mywidget.h"

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  virtual ~ExampleWindow();

protected:
  //Signal handlers:
  void on_button_quit();

  //Child widgets:
  Gtk::Box m_VBox;
  MyWidget m_MyWidget;
  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_Button_Quit;
};

#endif //GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"

ExampleWindow::ExampleWindow()
: m_VBox(Gtk::ORIENTATION_VERTICAL),
  m_Button_Quit("Quit")
{
  set_title("Custom Widget example");
  set_border_width(6);
  set_default_size(400, 200);

  add(m_VBox);
  m_VBox.pack_start(m_MyWidget, Gtk::PACK_EXPAND_WIDGET);
  m_MyWidget.show();

  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);

  m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
  m_ButtonBox.set_border_width(6);
  m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
  m_Button_Quit.signal_clicked().connect( sigc::mem_fun(*this, &amp;ExampleWindow::on_button_quit) );

  show_all_children();
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_button_quit()
{
  hide();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char *argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<para lang="en">File: <filename>mywidget.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "mywidget.h"
#include &lt;gdkmm/general.h&gt;  // for cairo helper functions
#include &lt;iostream&gt;
//#include &lt;gtk/gtkwidget.h&gt; //For GTK_IS_WIDGET()
#include &lt;cstring&gt;

// The MyWidget class uses API which was added in gtkmm 3.15.3 (Gtk::CssProviderError,
// Gtk::CssProvider::signal_parsing_error() and Gtk::CssSection) and in gtkmm 3.15.2
// (Gtk::StyleProperty).

MyWidget::MyWidget() :
  //The GType name will actually be gtkmm__CustomObject_mywidget
  Glib::ObjectBase("mywidget"),
  Gtk::Widget(),
  //Install a style property so that an aspect of this widget may be themed
  //via a CSS style sheet file:
  m_scale_prop(*this, "example_scale", 500),
  m_scale(1000)
{
  set_has_window(true);

  //This shows the GType name, which must be used in the CSS file.
  std::cout &lt;&lt; "GType name: " &lt;&lt; G_OBJECT_TYPE_NAME(gobj()) &lt;&lt; std::endl;

  //This shows that the GType still derives from GtkWidget:
  //std::cout &lt;&lt; "Gtype is a GtkWidget?:" &lt;&lt; GTK_IS_WIDGET(gobj()) &lt;&lt; std::endl;

  m_refCssProvider = Gtk::CssProvider::create();
  Glib::RefPtr&lt;Gtk::StyleContext&gt; refStyleContext = get_style_context();
  refStyleContext-&gt;add_provider(m_refCssProvider,
    GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
  m_refCssProvider-&gt;signal_parsing_error().connect(
    sigc::mem_fun(*this, &amp;MyWidget::on_parsing_error));
    
  try
  {
    m_refCssProvider-&gt;load_from_path("custom_gtk.css");
  }
  catch(const Gtk::CssProviderError&amp; ex)
  {
    std::cerr &lt;&lt; "CssProviderError, Gtk::CssProvider::load_from_path() failed: "
              &lt;&lt; ex.what() &lt;&lt; std::endl;
  }
  catch(const Glib::Error&amp; ex)
  {
    std::cerr &lt;&lt; "Error, Gtk::CssProvider::load_from_path() failed: "
              &lt;&lt; ex.what() &lt;&lt; std::endl;
  }
}

MyWidget::~MyWidget()
{
}

Gtk::SizeRequestMode MyWidget::get_request_mode_vfunc() const
{
  //Accept the default value supplied by the base class.
  return Gtk::Widget::get_request_mode_vfunc();
}

//Discover the total amount of minimum space and natural space needed by
//this widget.
//Let's make this simple example widget always need minimum 60 by 50 and
//natural 100 by 70.
void MyWidget::get_preferred_width_vfunc(int&amp; minimum_width, int&amp; natural_width) const
{
  minimum_width = 60;
  natural_width = 100;
}

void MyWidget::get_preferred_height_for_width_vfunc(int /* width */,
   int&amp; minimum_height, int&amp; natural_height) const
{
  minimum_height = 50;
  natural_height = 70;
}

void MyWidget::get_preferred_height_vfunc(int&amp; minimum_height, int&amp; natural_height) const
{
  minimum_height = 50;
  natural_height = 70;
}

void MyWidget::get_preferred_width_for_height_vfunc(int /* height */,
   int&amp; minimum_width, int&amp; natural_width) const
{
  minimum_width = 60;
  natural_width = 100;
}

void MyWidget::on_size_allocate(Gtk::Allocation&amp; allocation)
{
  //Do something with the space that we have actually been given:
  //(We will not be given heights or widths less than we have requested, though
  //we might get more)

  //Use the offered allocation for this container:
  set_allocation(allocation);

  if(m_refGdkWindow)
  {
    m_refGdkWindow-&gt;move_resize( allocation.get_x(), allocation.get_y(),
            allocation.get_width(), allocation.get_height() );
  }
}

void MyWidget::on_map()
{
  //Call base class:
  Gtk::Widget::on_map();
}

void MyWidget::on_unmap()
{
  //Call base class:
  Gtk::Widget::on_unmap();
}

void MyWidget::on_realize()
{
  //Do not call base class Gtk::Widget::on_realize().
  //It's intended only for widgets that set_has_window(false).

  set_realized();

  //Get the themed style from the CSS file:
  m_scale = m_scale_prop.get_value();
  std::cout &lt;&lt; "m_scale (example_scale from the theme/css-file) is: "
      &lt;&lt; m_scale &lt;&lt; std::endl;

  if(!m_refGdkWindow)
  {
    //Create the GdkWindow:

    GdkWindowAttr attributes;
    memset(&amp;attributes, 0, sizeof(attributes));

    Gtk::Allocation allocation = get_allocation();

    //Set initial position and size of the Gdk::Window:
    attributes.x = allocation.get_x();
    attributes.y = allocation.get_y();
    attributes.width = allocation.get_width();
    attributes.height = allocation.get_height();

    attributes.event_mask = get_events () | Gdk::EXPOSURE_MASK;
    attributes.window_type = GDK_WINDOW_CHILD;
    attributes.wclass = GDK_INPUT_OUTPUT;

    m_refGdkWindow = Gdk::Window::create(get_parent_window(), &amp;attributes,
            GDK_WA_X | GDK_WA_Y);
    set_window(m_refGdkWindow);

    //make the widget receive expose events
    m_refGdkWindow-&gt;set_user_data(gobj());
  }
}

void MyWidget::on_unrealize()
{
  m_refGdkWindow.reset();

  //Call base class:
  Gtk::Widget::on_unrealize();
}

bool MyWidget::on_draw(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; cr)
{
  const Gtk::Allocation allocation = get_allocation();
  const double scale_x = (double)allocation.get_width() / m_scale;
  const double scale_y = (double)allocation.get_height() / m_scale;

  // paint the background
  get_style_context()-&gt;render_background(cr,
    allocation.get_x(), allocation.get_y(),
    allocation.get_width(), allocation.get_height());

  // draw the foreground
  Gdk::Cairo::set_source_rgba(cr, get_style_context()-&gt;get_color());
  cr-&gt;move_to(155.*scale_x, 165.*scale_y);
  cr-&gt;line_to(155.*scale_x, 838.*scale_y);
  cr-&gt;line_to(265.*scale_x, 900.*scale_y);
  cr-&gt;line_to(849.*scale_x, 564.*scale_y);
  cr-&gt;line_to(849.*scale_x, 438.*scale_y);
  cr-&gt;line_to(265.*scale_x, 100.*scale_y);
  cr-&gt;line_to(155.*scale_x, 165.*scale_y);
  cr-&gt;move_to(265.*scale_x, 100.*scale_y);
  cr-&gt;line_to(265.*scale_x, 652.*scale_y);
  cr-&gt;line_to(526.*scale_x, 502.*scale_y);
  cr-&gt;move_to(369.*scale_x, 411.*scale_y);
  cr-&gt;line_to(633.*scale_x, 564.*scale_y);
  cr-&gt;move_to(369.*scale_x, 286.*scale_y);
  cr-&gt;line_to(369.*scale_x, 592.*scale_y);
  cr-&gt;move_to(369.*scale_x, 286.*scale_y);
  cr-&gt;line_to(849.*scale_x, 564.*scale_y);
  cr-&gt;move_to(633.*scale_x, 564.*scale_y);
  cr-&gt;line_to(155.*scale_x, 838.*scale_y);
  cr-&gt;stroke();

  return true;
}

void MyWidget::on_parsing_error(const Glib::RefPtr&lt;const Gtk::CssSection&gt;&amp; section, const Glib::Error&amp; error)
{
  std::cerr &lt;&lt; "on_parsing_error(): " &lt;&lt; error.what() &lt;&lt; std::endl;
  if (section)
  {
    std::cerr &lt;&lt; "  URI = " &lt;&lt; section-&gt;get_file()-&gt;get_uri() &lt;&lt; std::endl;
    std::cerr &lt;&lt; "  start_line = " &lt;&lt; section-&gt;get_start_line()+1
              &lt;&lt; ", end_line = " &lt;&lt; section-&gt;get_end_line()+1 &lt;&lt; std::endl;
    std::cerr &lt;&lt; "  start_position = " &lt;&lt; section-&gt;get_start_position()
              &lt;&lt; ", end_position = " &lt;&lt; section-&gt;get_end_position() &lt;&lt; std::endl;
  }
}
</programlisting>
<para lang="en">File: <filename>custom_gtk.css</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
/* Example of a CSS style sheet with a custom style property.
 *
 * The name of the style property must have its canonical form, i.e. characters
 * other than ASCII letters, digits, and hyphens must be replaced by hyphens.
*/

* {
  /* -&lt;widget class name&gt;-&lt;style property canonical name&gt;: &lt;value&gt;; */
  -gtkmm__CustomObject_mywidget-example-scale: 920;
}

gtkmm__CustomObject_mywidget {
  background-color: rgb(255,0,0);
  color:            rgb(0,0,255);
}

</programlisting>
<!-- end inserted example code -->
</sect2>

    </sect1>



</chapter>

<chapter id="chapter-multi-threaded-programs">
<title>Programas com várias linhas de processamento</title>

<sect1 id="sec-the-constraints">
<title lang="en">The constraints</title>

<para lang="en">
<application>glibmm</application> provides the normal set of thread
launching functions, mutexes, condition variables and scoped locking
classes required for writing multi-threaded programs using C++.
</para>

<para lang="en">
However, care is required when writing programs based on <application>gtkmm</application> using
multiple threads of execution, arising from the fact that
<application>libsigc++</application>, and in particular
<classname>sigc::trackable</classname>, are not thread-safe. That's
because none of the complex interactions that occur behind the scenes
when using <application>libsigc++</application> are protected by a
mutex or other means of synchronization.
<footnote>
<para lang="en">
These interactions arise from the fact that, amongst other things, a
class inheriting from <classname>sigc::trackable</classname> will, via
that inheritance, have a <classname>std::list</classname> object
keeping track of slots created by calls to
<function>sigc::mem_fun()</function> representing any of its
non-static methods (more particularly it keeps a list of callbacks
which will null the connected slots on its destruction). Each
<classname>sigc::slot</classname> object also keeps, via
<classname>sigc::slot_rep</classname>, its own
<classname>sigc::trackable</classname> object to track any
<classname>sigc::connection</classname> objects which it needs to
inform about its demise, and also has a function to deregister itself
from any <classname>sigc::trackable</classname> on disconnection or
destruction. <classname>sigc::signal</classname> objects also keep
lists of slots, which will be updated by a call to their
<methodname>connect()</methodname> method or calls to any
<classname>sigc::connection</classname> object relating to such a
connection.
</para>
</footnote>
</para>

<sect2 id="the-rules">
<title>As regras</title>

<para lang="en">
This requires a number of rules to be observed when writing
multi-threaded programs using <application>gtkmm</application>. These are set out below, but
one point to note is that extra care is required when deriving classes
from <classname>sigc::trackable</classname>, because the effects are
unintuitive (see particularly points 4 and 5 below).
</para>

<orderedlist>

<listitem>
<para lang="en">
Use <classname>Glib::Dispatcher</classname> to invoke <application>gtkmm</application> functions
from worker threads (this is dealt with in more detail in the next
section).
</para>
</listitem>

<listitem>
<para lang="en">
A <classname>sigc::signal</classname> object should be regarded as
owned by the thread which created it. Only that thread should connect
a <classname>sigc::slot</classname> object to the signal object, and
only that thread should <methodname>emit()</methodname> or call
<methodname>operator()()</methodname> on the signal, or null any
connected <classname>sigc::slot</classname> object. It follows
(amongst other things) that any signal object provided by a <application>gtkmm</application>
widget should only be operated on in the main GUI thread and any
object deriving from <classname>sigc::trackable</classname> having its
non-static methods referenced by slots connected to the signal object
should only be destroyed in that thread.
</para>
</listitem>

<listitem>
<para lang="en">
Any <classname>sigc::connection</classname> object should be regarded
as owned by the thread in which the method returning the
<classname>sigc::connection</classname> object was called. Only that
thread should call <classname>sigc::connection</classname> methods on
the object.
</para>
</listitem>

<listitem>
<para lang="en">
A <classname>sigc::slot</classname> object created by a call to
<function>sigc::mem_fun()</function> which references a method of a
class deriving from <classname>sigc::trackable</classname> should
never be copied to another thread, nor destroyed by a different thread
than the one which created it. (One consequence of this is that
<methodname>Glib::Threads::Thread::create()</methodname> should not be
called with a slot argument created by a call to
<function>sigc::mem_fun()</function> which represents a method of such
a class. It is however safe to pass
<methodname>Glib::Threads::Thread::create()</methodname> a function
object representing such a method by using, say,
<function>boost::bind()</function> or, in C++11,
<function>std::bind()</function> or a C++11 lambda expression.)
</para>
</listitem>

<listitem>
<para lang="en">
If a particular class object derives from
<classname>sigc::trackable</classname>, only one thread should create
<classname>sigc::slot</classname> objects representing any of the
class's non-static methods by calling
<function>sigc::mem_fun()</function>. The first thread to create such
a slot should be regarded as owning the relevant object for the
purpose of creating further slots referencing <emphasis>any</emphasis>
of its non-static methods using that function, or nulling those slots
by disconnecting them or destroying the trackable object.
</para>
</listitem>

<listitem>
<para lang="en">
Although <application>glib</application> is itself thread-safe, any
<application>glibmm</application> wrappers which use
<application>libsigc++</application> will not be. So for example, only
the thread in which a main loop runs should call
<methodname>Glib::SignalIdle::connect()</methodname>,
<methodname>Glib::SignalIO::connect()</methodname>,
<methodname>Glib::SignalTimeout::connect()</methodname>,
<methodname>Glib::SignalTimeout::connect_seconds</methodname>
for that main loop, or manipulate any
<classname>sigc::connection</classname> object returned by them.
</para>
<para lang="en">
The connect*_once() variants,
<methodname>Glib::SignalIdle::connect_once()</methodname>,
<methodname>Glib::SignalTimeout::connect_once()</methodname>,
<methodname>Glib::SignalTimeout::connect_seconds_once()</methodname>,
are thread-safe for any case where the slot is not created by a call to
<function>sigc::mem_fun()</function> which represents a method of a class
deriving from <classname>sigc::trackable</classname>. This is similar to
<methodname>Glib::Threads::Thread::create()</methodname> as mentioned in point 4.
</para>
</listitem>

</orderedlist>

</sect2>

</sect1>

<sect1 id="sec-using-glib-dispatcher">
<title lang="en">Using Glib::Dispatcher</title>

<para lang="en">
The slots connected to <classname>sigc::signal</classname> objects
execute in the thread which calls <methodname>emit()</methodname> or
<methodname>operator()()</methodname> on the signal.
<classname>Glib::Dispatcher</classname> does not behave this way:
instead its connected slots execute in the thread in which the
<classname>Glib::Dispatcher</classname> object was constructed (which
must have a glib main loop). If a
<classname>Glib::Dispatcher</classname> object is constructed in the
main GUI thread (which will therefore be the receiver thread), any
worker thread can emit on it and have the connected slots safely
execute <application>gtkmm</application> functions.
</para>

<para lang="en">
Some thread safety rules on the use of
<classname>Glib::Dispatcher</classname> still apply. As mentioned, a
<classname>Glib::Dispatcher</classname> object must be constructed in
the receiver thread (the thread in whose main loop it will execute its
connected slots). By default this is the main program thread, although
there is a <classname>Glib::Dispatcher</classname> constructor which
can take the <classname>Glib::MainContext</classname> object of any
thread which has a main loop. Only the receiver thread should call
<methodname>connect()</methodname> on the
<classname>Glib::Dispatcher</classname> object, or manipulate any
related <classname>sigc::connection</classname> object, unless
additional synchronization is employed. However, any worker thread can
safely emit on the <classname>Glib::Dispatcher</classname> object
without any locking once the receiver thread has connected the slots,
provided that it is constructed before the worker thread is started
(if it is constructed after the thread has started, additional
synchronization will normally be required to ensure visibility).
</para>

<para lang="en">
Aside from the fact that connected slots always execute in the
receiver thread, <classname>Glib::Dispatcher</classname> objects are
similar to <classname>sigc::signal&lt;void&gt;</classname> objects.
They therefore cannot pass unbound arguments nor return a value. The
best way to pass unbound arguments is with a thread-safe
(asynchronous) queue. At the time of writing
<application>glibmm</application> does not have one, although most
people writing multi-threaded code will have one available to them
(they are relatively easy to write although there are subtleties in
combining thread safety with strong exception safety).
</para>

<para lang="en">
A <classname>Glib::Dispatcher</classname> object can be emitted on by
the receiver thread as well as by a worker thread, although this
should be done within reasonable bounds. On unix-like systems
<classname>Glib::Dispatcher</classname> objects share a single common
pipe, which could in theory at least fill up on a very heavily loaded
system running a program with a very large number of
<classname>Dispatcher</classname> objects in use. Were the pipe to
fill up before the receiver thread's main loop has had an opportunity
to read from it to empty it, and the receiver thread attempt to emit
and so write to it when it is in that condition, the receiver thread
would block on the write, so deadlocking. Where the receiver thread is
to emit, a normal <classname>sigc::signal&lt;void&gt;</classname>
object could of course be used instead.
</para>

</sect1>

<sect1 id="sec-multithread-example">
<title>Exemplo</title>
<para lang="en">
This is an example program with two threads, one GUI thread, like in all
<application>gtkmm</application> programs, and one worker thread. The worker thread is created when you
press the <literal>Start work</literal> button. It is deleted when the work is
finished, when you press the <literal>Stop work</literal> button, or when you
press the <literal>Quit</literal> button.
</para>

<para lang="en">
A <classname>Glib::Dispatcher</classname> is used for sending notifications
from the worker thread to the GUI thread. The <classname>ExampleWorker</classname>
class contains data which is accessed by both threads. This data is protected
by a <classname>Glib::Threads::Mutex</classname>.
Only the GUI thread updates the GUI.
</para>

<figure id="figure-multithread">
  <title lang="en">Multi-Threaded Program</title>
  <screenshot>
    <graphic format="PNG" fileref="figures/multithread.png"/>
  </screenshot>
</figure>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/multithread?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>exampleworker.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWORKER_H
#define GTKMM_EXAMPLEWORKER_H

#include &lt;gtkmm.h&gt;

class ExampleWindow;

class ExampleWorker
{
public:
  ExampleWorker();

  // Thread function.
  void do_work(ExampleWindow* caller);

  void get_data(double* fraction_done, Glib::ustring* message) const;
  void stop_work();
  bool has_stopped() const;

private:
  // Synchronizes access to member data.
  mutable Glib::Threads::Mutex m_Mutex;

  // Data used by both GUI thread and worker thread.
  bool m_shall_stop;
  bool m_has_stopped;
  double m_fraction_done;
  Glib::ustring m_message;
};

#endif // GTKMM_EXAMPLEWORKER_H
</programlisting>
<para lang="en">File: <filename>examplewindow.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;
#include "exampleworker.h"

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();

  // Called from the worker thread.
  void notify();

private:
  // Signal handlers.
  void on_start_button_clicked();
  void on_stop_button_clicked();
  void on_quit_button_clicked();

  void update_start_stop_buttons();
  void update_widgets();

  // Dispatcher handler.
  void on_notification_from_worker_thread();

  // Member data.
  Gtk::Box m_VBox;
  Gtk::ButtonBox m_ButtonBox;
  Gtk::Button m_ButtonStart;
  Gtk::Button m_ButtonStop;
  Gtk::Button m_ButtonQuit;
  Gtk::ProgressBar m_ProgressBar;
  Gtk::ScrolledWindow m_ScrolledWindow;
  Gtk::TextView m_TextView;

  Glib::Dispatcher m_Dispatcher;
  ExampleWorker m_Worker;
  Glib::Threads::Thread* m_WorkerThread;
};

#endif // GTKMM_EXAMPLEWINDOW_H
</programlisting>
<para lang="en">File: <filename>examplewindow.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow() :
  m_VBox(Gtk::ORIENTATION_VERTICAL, 5),
  m_ButtonBox(Gtk::ORIENTATION_HORIZONTAL),
  m_ButtonStart("Start work"),
  m_ButtonStop("Stop work"),
  m_ButtonQuit("_Quit", /* mnemonic= */ true),
  m_ProgressBar(),
  m_ScrolledWindow(),
  m_TextView(),
  m_Dispatcher(),
  m_Worker(),
  m_WorkerThread(0)
{
  set_title("Multi-threaded example");
  set_border_width(5);
  set_default_size(300, 300);

  add(m_VBox);

  // Add the ProgressBar.
  m_VBox.pack_start(m_ProgressBar, Gtk::PACK_SHRINK);

  m_ProgressBar.set_text("Fraction done");
  m_ProgressBar.set_show_text();

  // Add the TextView, inside a ScrolledWindow.
  m_ScrolledWindow.add(m_TextView);

  // Only show the scrollbars when they are necessary.
  m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

  m_VBox.pack_start(m_ScrolledWindow);

  m_TextView.set_editable(false);

  // Add the buttons to the ButtonBox.
  m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);

  m_ButtonBox.pack_start(m_ButtonStart, Gtk::PACK_SHRINK);
  m_ButtonBox.pack_start(m_ButtonStop, Gtk::PACK_SHRINK);
  m_ButtonBox.pack_start(m_ButtonQuit, Gtk::PACK_SHRINK);
  m_ButtonBox.set_border_width(5);
  m_ButtonBox.set_spacing(5);
  m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);

  // Connect the signal handlers to the buttons.
  m_ButtonStart.signal_clicked().connect(sigc::mem_fun(*this, &amp;ExampleWindow::on_start_button_clicked));
  m_ButtonStop.signal_clicked().connect(sigc::mem_fun(*this, &amp;ExampleWindow::on_stop_button_clicked));
  m_ButtonQuit.signal_clicked().connect(sigc::mem_fun(*this, &amp;ExampleWindow::on_quit_button_clicked));

  // Connect the handler to the dispatcher.
  m_Dispatcher.connect(sigc::mem_fun(*this, &amp;ExampleWindow::on_notification_from_worker_thread));

  // Create a text buffer mark for use in update_widgets().
  Glib::RefPtr&lt;Gtk::TextBuffer&gt; buffer = m_TextView.get_buffer();
  buffer-&gt;create_mark("last_line", buffer-&gt;end(), /* left_gravity= */ true);

  update_start_stop_buttons();

  show_all_children();
}

void ExampleWindow::on_start_button_clicked()
{
  if (m_WorkerThread)
  {
    std::cout &lt;&lt; "Can't start a worker thread while another one is running." &lt;&lt; std::endl;
  }
  else
  {
    // Start a new worker thread.
    m_WorkerThread = Glib::Threads::Thread::create(
      sigc::bind(sigc::mem_fun(m_Worker, &amp;ExampleWorker::do_work), this));
  }
  update_start_stop_buttons();
}

void ExampleWindow::on_stop_button_clicked()
{
  if (!m_WorkerThread)
  {
    std::cout &lt;&lt; "Can't stop a worker thread. None is running." &lt;&lt; std::endl;
  }
  else
  {
   // Order the worker thread to stop.
    m_Worker.stop_work();
    m_ButtonStop.set_sensitive(false);
  }
}

void ExampleWindow::update_start_stop_buttons()
{
  const bool thread_is_running = m_WorkerThread != 0;

  m_ButtonStart.set_sensitive(!thread_is_running);
  m_ButtonStop.set_sensitive(thread_is_running);
}

void ExampleWindow::update_widgets()
{
  double fraction_done;
  Glib::ustring message_from_worker_thread;
  m_Worker.get_data(&amp;fraction_done, &amp;message_from_worker_thread);

  m_ProgressBar.set_fraction(fraction_done);

  if (message_from_worker_thread != m_TextView.get_buffer()-&gt;get_text())
  {
    Glib::RefPtr&lt;Gtk::TextBuffer&gt; buffer = m_TextView.get_buffer();
    buffer-&gt;set_text(message_from_worker_thread);

    // Scroll the last inserted line into view. That's somewhat complicated.
    Gtk::TextIter iter = buffer-&gt;end();
    iter.set_line_offset(0); // Beginning of last line
    Glib::RefPtr&lt;Gtk::TextMark&gt; mark = buffer-&gt;get_mark("last_line");
    buffer-&gt;move_mark(mark, iter);
    m_TextView.scroll_to(mark);
    // TextView::scroll_to(iter) is not perfect.
    // We do need a TextMark to always get the last line into view.
  }
}

void ExampleWindow::on_quit_button_clicked()
{
  if (m_WorkerThread)
  {
    // Order the worker thread to stop and wait for it to stop.
    m_Worker.stop_work();
    m_WorkerThread-&gt;join();
  }
  hide();
}

// notify() is called from ExampleWorker::do_work(). It is executed in the worker
// thread. It triggers a call to on_notification_from_worker_thread(), which is
// executed in the GUI thread.
void ExampleWindow::notify()
{
  m_Dispatcher.emit();
}

void ExampleWindow::on_notification_from_worker_thread()
{
  if (m_WorkerThread &amp;&amp; m_Worker.has_stopped())
  {
    // Work is done.
    m_WorkerThread-&gt;join();
    m_WorkerThread = 0;
    update_start_stop_buttons();
  }
  update_widgets();
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main (int argc, char* argv[])
{
  Glib::RefPtr&lt;Gtk::Application&gt; app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

  ExampleWindow window;

  //Shows the window and returns when it is closed.
  return app-&gt;run(window);
}
</programlisting>
<para lang="en">File: <filename>exampleworker.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "exampleworker.h"
#include "examplewindow.h"
#include &lt;sstream&gt;

ExampleWorker::ExampleWorker() :
  m_Mutex(),
  m_shall_stop(false),
  m_has_stopped(false),
  m_fraction_done(0.0),
  m_message()
{
}

// Accesses to these data are synchronized by a mutex.
// Some microseconds can be saved by getting all data at once, instead of having
// separate get_fraction_done() and get_message() methods.
void ExampleWorker::get_data(double* fraction_done, Glib::ustring* message) const
{
  Glib::Threads::Mutex::Lock lock(m_Mutex);

  if (fraction_done)
    *fraction_done = m_fraction_done;

  if (message)
    *message = m_message;
}

void ExampleWorker::stop_work()
{
  Glib::Threads::Mutex::Lock lock(m_Mutex);
  m_shall_stop = true;
}

bool ExampleWorker::has_stopped() const
{
  Glib::Threads::Mutex::Lock lock(m_Mutex);
  return m_has_stopped;
}

void ExampleWorker::do_work(ExampleWindow* caller)
{
  {
    Glib::Threads::Mutex::Lock lock(m_Mutex);
    m_has_stopped = false;
    m_fraction_done = 0.0;
    m_message = "";
  } // The mutex is unlocked here by lock's destructor.

  // Simulate a long calculation.
  for (int i = 0; ; ++i) // do until break
  {
    Glib::usleep(250000); // microseconds

    Glib::Threads::Mutex::Lock lock(m_Mutex);

    m_fraction_done += 0.01;

    if (i % 4 == 3)
    {
      std::ostringstream ostr;
      ostr &lt;&lt; (m_fraction_done * 100.0) &lt;&lt; "% done\n";
      m_message += ostr.str();
    }

    if (m_fraction_done &gt;= 1.0)
    {
      m_message += "Finished";
      break;
    }
    if (m_shall_stop)
    {
      m_message += "Stopped";
      break;
    }
    lock.release();
    caller-&gt;notify();
  }

  Glib::Threads::Mutex::Lock lock(m_Mutex);
  m_shall_stop = false;
  m_has_stopped = true;
  lock.release();
  caller-&gt;notify();
}
</programlisting>
<!-- end inserted example code -->

</sect1>

</chapter>

<chapter id="chapter-recommended-techniques">
<title>Técnicas recomendadas</title>

<para lang="en">This section is simply a gathering of wisdom, general style guidelines
and hints for creating <application>gtkmm</application> applications.
</para>

<para lang="en">Use GNU <application>autoconf</application> and
    <application>automake</application>! They are your friends :)
    <application>Automake</application> examines C files, determines how they
    depend on each other, and generates a <filename>Makefile</filename> so the
    files can be compiled in the correct order.
    <application>Autoconf</application> permits automatic configuration of
    software installation, handling a large number of system quirks to increase
    portability.
</para>

<para lang="en">Subclass Widgets to better organize your code. You should probably
    subclass your main <classname>Window</classname> at least. Then you can
    make your child Widgets and signal handlers members of that class.
</para>

<para lang="en">Create your own signals instead of passing pointers around. Objects can
    communicate with each other via signals and signal handlers. This is much
    simpler than objects holding pointers to each other and calling each
    other's methods. <application>gtkmm</application>'s classes uses special versions of
    <classname>sigc::signal</classname>, but you should use normal
    <classname>sigc::signal</classname>s, as described in the
    <application>libsigc++</application> documentation.</para>

<sect1 id="sec-application-lifetime">
    <title>Tempo de vida da aplicação</title>
<para lang="en">Most applications will have only one <classname>Window</classname>, or
    only one main window. These applications can use the
    <methodname>Gtk::Application::run(Gtk::Window&amp;)</methodname> overload. It shows
    the window and returns when the window has been hidden. This might happen
    when the user closes the window, or when your code decides to
    <methodname>hide()</methodname> the window. You can prevent the user from
    closing the window (for instance, if there are unsaved changes) by
    overriding <methodname>Gtk::Window::on_delete_event()</methodname>.</para>
<para lang="en">Most of our examples use this technique.</para>
</sect1>

<sect1 id="sec-using-a-gtkmm-widget">
<title>Usando um widget <application>gtkmm</application></title>

<para lang="en">
    Our examples all tend to have the same structure. They follow these steps
    for using a <classname>Widget</classname>:
</para>

<para>

<orderedlist>
<listitem>
<para lang="en">
Declare a variable of the type of <classname>Widget</classname> you wish to
use, generally as member variable of a derived container class. You could also
declare a pointer to the widget type, and then create it with
<literal>new</literal> in your code. Even when using the widget via a pointer,
it's still probably best to make that pointer a member variable of a container
class so that you can access it later.
</para>
</listitem>

<listitem>
<para lang="en">
 Set the attributes of the widget. If the widget has no default constructor, then you will need to initialize the widget in the initalizer list of your container class's constructor.
</para>
</listitem>

<listitem>
<para lang="en">
Connect any signals you wish to use to the appropriate handlers.
</para>
</listitem>

<listitem>
<para lang="en">
Pack the widget into a container using the appropriate call,
e.g. <methodname>Gtk::Container::add()</methodname> or
<methodname>pack_start()</methodname>.
</para>
</listitem>

<listitem>
<para lang="en">
Call <methodname>show()</methodname> to display the widget.
</para>
</listitem>

</orderedlist>

</para>

<para lang="en">
<methodname>Gtk::Widget::show()</methodname> lets <application>gtkmm</application> know that we have
finished setting the attributes of the widget, and that it is ready to be
displayed. You can use <methodname>Gtk::Widget::hide()</methodname> to make it
disappear again. The order in which you show the widgets is not important, but
we do suggest that you show the top-level window last; this way, the whole
window will appear with its contents already drawn. Otherwise, the user will
first see a blank window, into which the widgets will be gradually drawn.
</para>

</sect1>
</chapter>

<chapter id="chapter-contributing">
<title lang="en">Contributing</title>

<para lang="en">
This document, like so much other great software out there, was
created for free by volunteers. If you are at all knowledgeable about
any aspect of <application>gtkmm</application> that does not already have documentation, please
consider contributing to this document.
</para>
<para lang="en">
Ideally, we would like you to <ulink url="http://www.gtkmm.org/bugs.shtml">provide a patch</ulink> to the
<filename>docs/tutorial/C/index-in.docbook</filename> file. This file is currently
in the <literal>gtkmm-documentation</literal> module in GNOME git.
</para>

<para lang="en">
If you do decide to contribute, please post your contribution to the
<application>gtkmm</application> mailing list at <ulink url="mailto:gtkmm-list@gnome.org">&lt;gtkmm-list@gnome.org&gt;</ulink>. Also, be aware that
the entirety of this document is free, and any addition you provide
must also be free. That is, people must be able to use any portion of
your examples in their programs, and copies of this document
(including your contribution) may be distributed freely.
</para>

</chapter>

<appendix id="chapter-refptr">
<title lang="en">The RefPtr smartpointer</title>
<para lang="en">
<classname>Glib::RefPtr</classname> is a smartpointer. Specifically, it is a
reference-counting smartpointer. You might be familiar with
<classname>std::auto_ptr&lt;&gt;</classname>, <classname>std::unique_ptr&lt;&gt;</classname>
and <classname>std::shared_ptr&lt;&gt;</classname>, which are also smartpointers.
<classname>Glib::RefPtr&lt;&gt;</classname> is similar to <classname>std::shared_ptr&lt;&gt;</classname>,
which is also reference-counting. <classname>Glib::RefPtr&lt;&gt;</classname> was introduced
long before there was a reference-counting smartpointer in the C++ Standard Library.
</para>

<para lang="en"><ulink url="http://developer.gnome.org/glibmm/unstable/classGlib_1_1RefPtr.html">Reference</ulink></para>

<para lang="en">A smartpointer acts much like a normal pointer. Here are a few examples.</para>

<sect1 id="sec-refptr-copying">
    <title>Copiando</title>
<para lang="en">
You can copy <classname>RefPtr</classname>s, just like normal pointers. But
unlike normal pointers, you don't need to worry about deleting the underlying
instance.
</para>
<para>
<programlisting lang="en">
Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf = Gdk::Pixbuf::create_from_file(filename);
Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf2 = refPixbuf;
</programlisting>
</para>
<para lang="en">
Of course this means that you can store <classname>RefPtr</classname>s in
standard containers, such as <classname>std::vector</classname> or
<classname>std::list</classname>.</para>
<para>
<programlisting lang="en">
std::list&lt; Glib::RefPtr&lt;Gdk::Pixbuf&gt; &gt; listPixbufs;
Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf = Gdk::Pixbuf::create_from_file(filename);
listPixbufs.push_back(refPixbuf);
</programlisting>
</para>
</sect1>

<sect1 id="sec-refptr-dereferencing"><title lang="en">Dereferencing</title>
<para lang="en">You can dereference a smartpointer with the -&gt; operator, to
call the methods of the underlying instance, just like a normal pointer.
</para>
<para>
<programlisting lang="en">
Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf = Gdk::Pixbuf::create_from_file(filename);
int width = refPixbuf-&gt;get_width();
</programlisting>
</para>
<para lang="en">But unlike most smartpointers, you can't use the * operator to
access the underlying instance.
</para>
<para>
<programlisting lang="en">
Glib::RefPtr&lt;Gdk::Pixbuf&gt; refPixbuf = Gdk::Pixbuf::create_from_file(filename);
Gdk::Pixbuf&amp; underlying = *refPixbuf; //Syntax error - will not compile.
</programlisting>
</para>
</sect1>

<sect1 id="sec-refptr-casting"><title lang="en">Casting</title>
<para lang="en">
You can cast <classname>RefPtr</classname>s to base types, just like normal
pointers.
</para>
<para>
<programlisting lang="en">
Glib::RefPtr&lt;Gtk::TreeStore&gt; refStore = Gtk::TreeStore::create(columns);
Glib::RefPtr&lt;Gtk::TreeModel&gt; refModel = refStore;
</programlisting>
</para>
<para lang="en">This means that any method which takes a <type>const
Glib::RefPtr&lt;BaseType&gt;</type> argument can also take a
<type>const Glib::RefPtr&lt;DerivedType&gt;</type>. The cast is
implicit, just as it would be for a normal pointer.</para>
<para lang="en">You can also cast to a derived type, but the syntax is
a little different than with a normal pointer.
</para>
<para>
<programlisting lang="en">
Glib::RefPtr&lt;Gtk::TreeStore&gt; refStore =
Glib::RefPtr&lt;Gtk::TreeStore&gt;::cast_dynamic(refModel);
Glib::RefPtr&lt;Gtk::TreeStore&gt; refStore2 =
Glib::RefPtr&lt;Gtk::TreeStore&gt;::cast_static(refModel);
</programlisting>
</para>
</sect1>


<sect1 id="sec-refptr-checking-for-null"><title>Verificação de nulo</title>
<para lang="en">
Just like normal pointers, you can check whether a
<classname>RefPtr</classname> points to anything.
</para>
<para>
<programlisting lang="en">
Glib::RefPtr&lt;Gtk::TreeModel&gt; refModel = m_TreeView.get_model();
if(refModel)
{
  int cols_count = refModel-&gt;get_n_columns();
  ...
}
</programlisting>
</para>
<para lang="en">
But unlike normal pointers, <classname>RefPtr</classname>s are automatically
initialized to null so you don't need to remember to do that yourself.
</para>
</sect1>


<sect1 id="sec-refptr-constness"><title lang="en">Constness</title>
<para lang="en">
The use of the <literal>const</literal> keyword in C++ is not always clear. You
might not realise that <type>const Something*</type> declares a pointer to a
<type>const Something</type>. The pointer can be changed, but not the
<type>Something</type> that it points to.
</para>
<para lang="en">
Therefore, the <classname>RefPtr</classname> equivalent of
<type>Something*</type> for a method parameter is <type>const
    Glib::RefPtr&lt;Something&gt;&amp;</type>, and the equivalent of
<type>const Something*</type> is <type>const Glib::RefPtr&lt;const
    Something&gt;&amp;</type>.
</para>
<para lang="en">
The <literal>const ... &amp;</literal> around both is just for efficiency, like
using <classname>const std::string&amp;</classname> instead of
<classname>std::string</classname> for a method parameter to avoid unnecessary
copying.
</para>
</sect1>

</appendix>


<appendix id="chapter-signals">
<title>Sinais</title>

<sect1 id="sec-connecting-signal-handlers">
<title>Conectando manipuladores de sinais</title>
<para lang="en">
<application>gtkmm</application> widget classes have signal accessor methods, such as
<methodname>Gtk::Button::signal_clicked()</methodname>, which allow you to connect
your signal handler. Thanks to the flexibility of
<application>libsigc++</application>, the callback library used by <application>gtkmm</application>, the
signal handler can be almost any kind of function, but you will probably want
to use a class method. Among <application>GTK+</application> C coders, these
signal handlers are often named callbacks.
</para>

<para lang="en">
Here's an example of a signal handler being connected to a signal:
</para>

<para>
<programlisting lang="en">
#include &lt;gtkmm/button.h&gt;

void on_button_clicked()
{
    std::cout &lt;&lt; "Hello World" &lt;&lt; std::endl;
}

main()
{
    Gtk::Button button("Hello World");
    button.signal_clicked().connect(sigc::ptr_fun(&amp;on_button_clicked));
}
</programlisting>
</para>

<para lang="en">
There's rather a lot to think about in this (non-functional) code.
First let's identify the parties involved:
</para>

<itemizedlist>
<listitem>

<para lang="en">
The signal handler is <methodname>on_button_clicked()</methodname>.
</para>
</listitem>
<listitem>

<para lang="en">
We're hooking it up to the <classname>Gtk::Button</classname> object called
<varname>button</varname>.
</para>
</listitem>
<listitem>

<para lang="en">
When the Button emits its <literal>clicked</literal> signal,
<methodname>on_button_clicked()</methodname> will be called.
</para>
</listitem>

</itemizedlist>

<para lang="en">
Now let's look at the connection again:
</para>

<para>
<programlisting lang="en">
    ...
    button.signal_clicked().connect(sigc::ptr_fun(&amp;on_button_clicked));
    ...
</programlisting>
</para>

<para lang="en">
Note that we don't pass a pointer to <methodname>on_button_clicked()</methodname>
directly to the signal's <methodname>connect()</methodname> method. Instead, we
call <function>sigc::ptr_fun()</function>, and pass the result to
<methodname>connect()</methodname>.
</para>

<para lang="en">
<function>sigc::ptr_fun()</function>  generates a <classname>sigc::slot</classname>.
A slot is an object which
looks and feels like a function, but is actually an object. These are also
known as function objects, or functors.
<function>sigc::ptr_fun()</function> generates a slot for a standalone function or static method.
<function>sigc::mem_fun()</function> generates a slot for a member method of a particular instance.
</para>

<para lang="en">
Here's a slightly larger example of slots in action:
</para>

<para>
<programlisting lang="en">
void on_button_clicked();

class some_class
{
    void on_button_clicked();
};

some_class some_object;

main()
{
    Gtk::Button button;
    button.signal_clicked().connect( sigc::ptr_fun(&amp;on_button_clicked) );
    button.signal_clicked().connect( sigc::mem_fun(some_object, &amp;some_class::on_button_clicked) );
}
</programlisting>
</para>

<para lang="en">
The first call to <methodname>connect()</methodname> is just like the one we saw
last time; nothing new here.</para>
<para lang="en">The next is more interesting.
<function>sigc::mem_fun()</function> is called with two arguments. The first
argument is <parameter>some_object</parameter>, which is the object that our
new slot will be pointing at. The second argument is a pointer to one of its
methods. This particular version of <function>sigc::mem_fun()</function>
creates a slot which will, when "called", call the pointed-to method of the
specified object, in this case
<methodname>some_object.on_button_clicked()</methodname>.
</para>

<para lang="en">
Another thing to note about this example is that we made the call to
<methodname>connect()</methodname> twice for the same signal object. This is
perfectly fine - when the button is clicked, both signal handlers will be
called.
</para>

<para lang="en">
We just told you that the button's <literal>clicked</literal> signal is expecting
to call a method with no arguments. All signals have
requirements like this - you can't hook a function with two arguments
to a signal expecting none (unless you use an adapter, such as
<function>sigc::bind()</function>, of course). Therefore, it's important to
know what type of signal handler you'll be expected to connect to a given
signal.
</para>
</sect1>

<sect1 id="sec-writing-signal-handlers">
<title>Escrevendo manipuladores de sinais</title>

<para lang="en">
To find out what type of signal handler you can connect to a signal, you can
look it up in the reference documentation or the header file. Here's an example of a signal declaration you
might see in the <application>gtkmm</application> headers:
</para>

<para>
<programlisting lang="en">
Glib::SignalProxy1&lt;bool, Gtk::DirectionType&gt; signal_focus()
</programlisting>
</para>

<para lang="en">
Other than the signal's name (<literal>focus</literal>), two things are
important to note here: the number following the word
<classname>SignalProxy</classname> at the beginning (1, in this case), and the
types in the list (<type>bool</type> and <type>Gtk::DirectionType</type>). The
number indicates how many arguments the signal handler should have; the first
type, <type>bool</type>, is the type that the signal handler should return; and
the next type, <type>Gtk::DirectionType</type>, is the type of this signal's
first, and only, argument. By looking at the reference documentation, you can
see the names of the arguments too.
</para>

<para lang="en">
The same principles apply for signals which have more arguments. Here's one
with three (taken from <filename>&lt;gtkmm/textbuffer.h&gt;</filename>):
</para>

<para>
<programlisting lang="en">
Glib::SignalProxy3&lt;void, const TextBuffer::iterator&amp;, const Glib::ustrin&amp;, int&gt; signal_insert();
</programlisting>
</para>

<para lang="en">
It follows the same form. The number 3 at the end of the type's name indicates
that our signal handler will need three arguments. The first type in the type
list is <type>void</type>, so that should be our signal handler's return type.
The following three types are the argument types, in order. Our signal
handler's prototype could look like this:
</para>

<para>
<programlisting lang="en">
void on_insert(const TextBuffer::iterator&amp; pos, const Glib::ustring&amp; text, int bytes)
</programlisting>
</para>
</sect1>

<sect1 id="sec-disconnecting-signal-handlers">
<title>Desconectando manipuladores de sinais</title>

<para lang="en">
Let's take another look at a Signal's <literal>connect</literal> method:
</para>

<para>
<programlisting lang="en">
sigc::signal&lt;void,int&gt;::iterator signal&lt;void,int&gt;::connect( const sigc::slot&lt;void,int&gt;&amp; );
</programlisting>
</para>

<para lang="en">
Notice that the return value is of type
<classname>sigc::signal&lt;void,int&gt;::iterator</classname>. This can be
implicitly converted into a <classname>sigc::connection</classname> which in
turn can be used to control the connection. By keeping a connection object you
can disconnect its associated signal handler using the method
<methodname>sigc::connection::disconnect()</methodname>.
</para>

</sect1>
<sect1 id="sec-overriding-default-signal-handlers">
<title lang="en">Overriding default signal handlers</title>

<para lang="en">
So far we've told you to perform actions in
response to button-presses and the like by handling signals.
That's certainly a good way to do things, but it's not the only
way.
</para>

<para lang="en">
Instead of laboriously connecting signal handlers to signals,
you can simply make a new class which inherits from a widget - say, a
Button - and then override the default signal handler, such as Button::on_clicked(). This can be a
lot simpler than hooking up signal handlers for everything.
</para>

<para lang="en">
Subclassing isn't always the best way to accomplish
things. It is only useful when you want the widget to handle its own signal by itself. If you want some other class to handle the signal then you'll need to connect a separate handler. This is even more true if you want several objects to handle the same signal, or if you want one signal handler to respond to the same signal from different objects.
</para>

<para lang="en">
<application>gtkmm</application> classes are designed with overriding in mind; they contain
virtual member methods specifically intended to be overridden.
</para>

<para lang="en">
Let's look at an example of overriding:
</para>

<para>
<programlisting lang="en">
#include &lt;gtkmm/button.h&gt;

class OverriddenButton : public Gtk::Button
{
protected:
    virtual void on_clicked();
}

void OverriddenButton::on_clicked()
{
    std::cout &lt;&lt; "Hello World" &lt;&lt; std::endl;

    // call the base class's version of the method:
    Gtk::Button::on_clicked();
}
</programlisting>
</para>

<para lang="en">
Here  we define a new class called <classname>OverriddenButton</classname>,
which inherits from <classname>Gtk::Button</classname>. The only thing we
change is the <methodname>on_clicked()</methodname> method, which is called
whenever <classname>Gtk::Button</classname> emits the
<literal>clicked</literal> signal. This method prints "Hello World" to
<literal>stdout</literal>, and then calls the original, overridden method, to
let <classname>Gtk::Button</classname> do what it would have done had we not
overridden.
</para>

<para lang="en">
You don't always need to call the parent's method; there are times
when you might not want to. Note that we called the parent method
<emphasis>after</emphasis> writing "Hello World", but we could have called it before.
In this simple example, it hardly matters much, but there are times
when it will. With signals, it's not quite so easy to change details
like this, and you can do something here which you can't do at all
with connected signal handlers: you can call the parent method in the <emphasis>middle</emphasis> of
your custom code.
</para>

</sect1>

<sect1 id="sec-binding-extra-arguments">
<title>Ligando argumentos extras</title>
<para lang="en">
If you use one signal handler to catch the same signal from several widgets,
you might like that signal handler to receive some extra information. For
instance, you might want to know which button was clicked. You can do this with
<function>sigc::bind()</function>. Here's some code from the <link linkend="sec-helloworld2">helloworld2</link> example.
<programlisting lang="en">
m_button1.signal_clicked().connect( sigc::bind&lt;Glib::ustring&gt;( sigc::mem_fun(*this, &amp;HelloWorld::on_button_clicked), "button 1") );
</programlisting>
This says that we want the signal to send an extra
<classname>Glib::ustring</classname> argument to the signal handler, and that
the value of that argument should be "button 1". Of course we will need to add
that extra argument to the declaration of our signal handler:
<programlisting lang="en">
virtual void on_button_clicked(Glib::ustring data);
</programlisting>
Of course, a normal "clicked" signal handler would have no arguments.
</para>
<para lang="en">
<function>sigc::bind()</function> is not commonly used, but you might find it
helpful sometimes. If you are familiar with <application>GTK+</application>
programming then you have probably noticed that this is similar to the extra
<literal>gpointer data</literal> arguments which all GTK+ callbacks have. This
is generally overused in <application>GTK+</application> to pass information
that should be stored as member data in a derived widget, but widget derivation
is very difficult in C. We have far less need of this hack in <application>gtkmm</application>.
</para>
</sect1>

<sect1 id="sec-xeventsignals">
<title>Sinais de eventos X</title>
<para lang="en">
The <classname>Widget</classname> class has some special signals which
correspond to the underlying X-Windows events. These are suffixed by
<literal>_event</literal>; for instance,
<methodname>Widget::signal_button_press_event()</methodname>.
</para>
<para lang="en">
You might occasionally find it useful to handle X events when there's something
you can't accomplish with normal signals. <classname>Gtk::Button</classname>,
for example, does not send mouse-pointer coordinates with its
<literal>clicked</literal> signal, but you could handle
<literal>button_press_event</literal> if you needed this
information. X events are also often used to handle key-presses.
</para>

<para lang="en">
These signals behave slightly differently. The value returned from the signal handler indicates whether it has fully "handled"
the event. If the value is <literal>false</literal> then <application>gtkmm</application> will pass the event on to the next signal handler. If the value is <literal>true</literal> then no other signal handlers will need to be called.
</para>

<para lang="en">
Handling an X event doesn't affect the Widget's other signals. If you handle
<literal>button_press_event</literal> for
<classname>Gtk::Button</classname>, you'll still be able to get the
<literal>clicked</literal> signal. They are emitted at (nearly) the same time.
</para>

<para lang="en">Note also that not all widgets receive all X events by default. To receive additional
X events, you can use <methodname>Gtk::Widget::set_events()</methodname> before showing the
widget, or <methodname>Gtk::Widget::add_events()</methodname> after showing the widget. However,
some widgets must first be placed inside an <classname>EventBox</classname> widget. See
the <link linkend="chapter-widgets-without-xwindows">Widgets Without X-Windows</link> chapter.
</para>

<para lang="en">
Here's a simple example:
<programlisting lang="en">
bool on_button_press(GdkEventButton* event);
Gtk::Button button("label");
button.signal_button_press_event().connect( sigc::ptr_fun(&amp;on_button_press) );
</programlisting>
</para>
<para lang="en">
When the mouse is over the button and a mouse button is pressed,
<methodname>on_button_press()</methodname> will be called.
</para>

<para lang="en">
<type>GdkEventButton</type> is a structure containing the event's parameters,
such as the coordinates of the mouse pointer at the time the button was
pressed. There are several different types of <type>GdkEvent</type> structures
for the various events.
</para>

<sect2 id="signal-handler-sequence">
<title>Sequência de manipulador de sinal</title>
<para lang="en">By default, your signal handlers are called after any previously-connected
signal handlers. However, this can be a problem with the X Event signals. For instance,
the existing signal handlers, or the default signal handler, might return <literal>true</literal>
to stop other signal handlers from being called. To specify that your signal handler
should be called before the other signal handlers, so that it will always be called,
you can specify <literal>false</literal> for the optional <literal>after</literal>
parameter. For instance,
<programlisting lang="en">
button.signal_button_press_event().connect( sigc::ptr_fun(&amp;on_mywindow_button_press), false );
</programlisting>
</para>
<para lang="en">The event is delivered first to the widget the event occurred in. If all
signal handlers in that widget return <literal>false</literal> (indicating that
the event has not been handled), then the signal will be propagated to the parent
widget and emitted there. This continues all the way up to the top-level widget
if no one handles the event. 
</para>
</sect2>

</sect1>

<sect1 id="sec-exceptions-in-signal-handlers">
<title lang="en">Exceptions in signal handlers</title>
<para lang="en">
When a program is aborted because of an unhandled C++ exception, it's sometimes
possible to use a debugger to find the location where the exception was thrown.
This is more difficult than usual if the exception was thrown from a signal handler.
</para>
<para lang="en">
This section describes primarily what you can expect on a Linux system, when you
use <ulink url="http://www.gnu.org/software/gdb/">the gdb debugger</ulink>.
</para>
<para lang="en">
First, let's look at a simple example where an exception is thrown from a normal
function (no signal handler).
<programlisting lang="en">
// without_signal.cc
#include &lt;gtkmm.h&gt;

bool throwSomething()
{
  throw "Something";
  return true;
}

int main(int argc, char** argv)
{
  throwSomething();
  Glib::RefPtr&lt;Gtk::Application&gt; app =
    Gtk::Application::create(argc, argv, "org.gtkmm.without_signal");
  return app-&gt;run();
}
</programlisting>
</para>
<para lang="en">
Here is an excerpt from a <application>gdb</application> session. Only the most
interesting parts of the output are shown.
<programlisting lang="en">
&gt; gdb without_signal
(gdb) run
terminate called after throwing an instance of 'char const*'

Program received signal SIGABRT, Aborted.
(gdb) backtrace
#7  0x08048864 in throwSomething () at without_signal.cc:6
#8  0x0804887d in main (argc=1, argv=0xbfffecd4) at without_signal.cc:12
</programlisting>
You can see that the exception was thrown from <filename>without_signal.cc</filename>,
line 6 (<code>throw "Something";</code>).
</para>
<para lang="en">
Now let's see what happens when an exception is thrown from a signal handler.
Here's the source code.
<programlisting lang="en">
// with_signal.cc
#include &lt;gtkmm.h&gt;

bool throwSomething()
{
  throw "Something";
  return true;
}

int main(int argc, char** argv)
{
  Glib::signal_timeout().connect(sigc::ptr_fun(throwSomething), 500);
  Glib::RefPtr&lt;Gtk::Application&gt; app =
    Gtk::Application::create(argc, argv, "org.gtkmm.with_signal");
  app-&gt;hold();
  return app-&gt;run();
}
</programlisting>
</para>
<para lang="en">
And here's an excerpt from a <application>gdb</application> session.
<programlisting lang="en">
&gt; gdb with_signal
(gdb) run
(with_signal:2703): glibmm-ERROR **:
unhandled exception (type unknown) in signal handler

Program received signal SIGTRAP, Trace/breakpoint trap.
(gdb) backtrace
#2  0x0063c6ab in glibmm_unexpected_exception () at exceptionhandler.cc:77
#3  Glib::exception_handlers_invoke () at exceptionhandler.cc:150
#4  0x0063d370 in glibmm_source_callback (data=0x804d620) at main.cc:212
#13 0x002e1b31 in Gtk::Application::run (this=0x804f300) at application.cc:178
#14 0x08048ccc in main (argc=1, argv=0xbfffecd4) at with_signal.cc:16
</programlisting>
The exception is caught in <application>glibmm</application>, and the program
ends with a call to <function>g_error()</function>. Other exceptions may result
in different behaviour, but in any case the exception from a signal handler is
caught in <application>glibmm</application> or <application>gtkmm</application>, and
<application>gdb</application> can't see where it was thrown.
</para>
<para lang="en">
To see where the exception is thrown, you can use the <application>gdb</application>
command <userinput>catch throw</userinput>.
<programlisting lang="en">
&gt; gdb with_signal
(gdb) catch throw
Catchpoint 1 (throw)
(gdb) run
Catchpoint 1 (exception thrown), 0x00714ff0 in __cxa_throw ()
(gdb) backtrace
#0  0x00714ff0 in __cxa_throw () from /usr/lib/i386-linux-gnu/libstdc++.so.6
#1  0x08048bd4 in throwSomething () at with_signal.cc:6
(gdb) continue
Continuing.
(with_signal:2375): glibmm-ERROR **
unhandled exception (type unknown) in signal handler

Program received signal SIGTRAP, Trace/breakpoint trap.
</programlisting>
</para>
<para lang="en">
If there are many caught exceptions before the interesting uncaught one, this
method can be tedious. It can be automated with the following
<application>gdb</application> commands.
<programlisting lang="en">
(gdb) catch throw
(gdb) commands
(gdb)   backtrace
(gdb)   continue
(gdb)   end
(gdb) set pagination off
(gdb) run
</programlisting>
These commands will print a backtrace from each <code>throw</code> and continue.
The backtrace from the last (or possibly the last but one) <code>throw</code>
before the program stops, is the interesting one.
</para>
</sect1>

</appendix>


<appendix id="chapter-custom-signals">
<title>Criando seus próprios sinais</title>
<para lang="en">
Now that you've seen signals and signal handlers in <application>gtkmm</application>, you
might like to use the same technique to allow interaction between your
own classes. That's actually very simple by using the
<application>libsigc++</application> library directly.
</para>
<para lang="en">
This isn't purely a <application>gtkmm</application> or GUI issue. <application>gtkmm</application> uses
<application>libsigc++</application> to implement its proxy wrappers for the
<application>GTK+</application> signal system, but for new,
non-GTK+ signals, you can create pure C++ signals, using the
<classname>sigc::signal&lt;&gt;</classname> template.
</para>
<para lang="en">
For instance, to create a signal that sends 2 parameters, a <type>bool</type>
and an <type>int</type>, just declare a <classname>sigc::signal</classname>,
like so:
<programlisting lang="en">
sigc::signal&lt;void, bool, int&gt; signal_something;
</programlisting>
</para>
<para lang="en">
You could just declare that signal as a public member variable, but
some people find that distasteful and prefer to make it available via
an accessor method, like so:
<programlisting lang="en">
class Server
{
public:
  //signal accessor:
  typedef sigc::signal&lt;void, bool, int&gt; type_signal_something;
  type_signal_something signal_something();

protected:
  type_signal_something m_signal_something;
};

Server::type_signal_something Server::signal_something()
{
  return m_signal_something;
}
</programlisting>
</para>

<para lang="en">
You can then connect to the signal using the same syntax used when
connecting to <application>gtkmm</application> signals. For instance,
<programlisting lang="en">
server.signal_something().connect(
  sigc::mem_fun(client, &amp;Client::on_server_something) );
</programlisting>
</para>

<sect1 id="chapter-custom-signals-example"><title>Exemplo</title>

<para lang="en">
This is a full working example that defines and uses custom signals.
</para>

<para lang="en"><ulink url="http://git.gnome.org/browse/gtkmm-documentation/tree/examples/book/signals/custom/?h=master">Source Code</ulink></para>
<!-- start inserted example code -->
<para lang="en">File: <filename>server.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_SERVER_H
#define GTKMM_EXAMPLE_SERVER_H

#include &lt;sigc++/sigc++.h&gt;

class Server
{
public:
  Server();
  virtual ~Server();

  void do_something();

  //signal accessor:
  typedef sigc::signal&lt;void, bool, int&gt; type_signal_something;
  type_signal_something signal_something();

protected:
  type_signal_something m_signal_something;
};

#endif //GTKMM_EXAMPLE_SERVER_H
</programlisting>
<para lang="en">File: <filename>client.h</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#ifndef GTKMM_EXAMPLE_CLIENT_H
#define GTKMM_EXAMPLE_CLIENT_H

#include &lt;sigc++/sigc++.h&gt;

//Client must inherit from sigc::trackable.
//because libsigc++ needs to keep track of the lifetime of signal handlers.
class Client : public sigc::trackable
{
public:
  Client();
  virtual ~Client();

  //Signal handler:
  void on_server_something(bool a, int b);
};

#endif //GTKMM_EXAMPLE_CLIENT_H
</programlisting>
<para lang="en">File: <filename>client.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "client.h"
#include &lt;iostream&gt;

Client::Client()
{
}

Client::~Client()
{
}

void Client::on_server_something(bool a, int b)
{
  std::cout &lt;&lt; "Client::on_server_something() called with these parameters: "
      &lt;&lt; a &lt;&lt; ", " &lt;&lt; b &lt;&lt; std::endl;
}
</programlisting>
<para lang="en">File: <filename>main.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "server.h"
#include "client.h"
#include &lt;iostream&gt;

int main(int, char**)
{
  Server server;
  Client client;

  //Connect a Server signal to the signal handler in Client.
  server.signal_something().connect(sigc::mem_fun(client,
              &amp;Client::on_server_something) );

  std::cout &lt;&lt; "Before Server::do_something()" &lt;&lt; std::endl;

  //Tell the server to do something that will eventually cause it to emit the
  //"something" signal.
  server.do_something();    // Client::on_server_something() will run before
                            // Server::do_something() has completed.

  std::cout &lt;&lt; "After Server::do_something()" &lt;&lt; std::endl;

  return 0;
}
</programlisting>
<para lang="en">File: <filename>server.cc</filename> (For use with gtkmm 3, not gtkmm 2)
</para>
<programlisting lang="en">
#include "server.h"
#include &lt;iostream&gt;

Server::Server()
{
}

Server::~Server()
{
}

Server::type_signal_something Server::signal_something()
{
  return m_signal_something;
}

void Server::do_something()
{
  m_signal_something.emit(false, 5);
}

</programlisting>
<!-- end inserted example code -->

</sect1>

</appendix>




<appendix id="sec-signals-comparison">
<title lang="en">Comparison with other signalling systems</title>
<para lang="en">
<!-- TODO: Rewrite this paragraph and talk about Qt's moc. -->
(An aside: <application>GTK+</application> calls this scheme "signalling"; the
sharp-eyed reader with GUI toolkit experience will note that this same design
is often
seen under the name of "broadcaster-listener" (e.g., in Metrowerks'
PowerPlant framework for the Macintosh). It works in much the same
way: one sets up <literal>broadcasters</literal>, and then connects
<literal>listeners</literal> to them; the broadcaster keeps a list of the
objects listening to it, and when someone gives the broadcaster a
message, it calls all of its objects in its list with the message. In
<application>gtkmm</application>, signal objects play the role of broadcasters, and slots
play the role of listeners - sort of. More on this later.)
</para>
<para lang="en">
<application>gtkmm</application> signal handlers are strongly-typed, whereas
<application>GTK+</application> C code allows you to connect a callback with
the wrong number and type of arguments, leading to a segfault at runtime. And,
unlike <application>Qt</application>, <application>gtkmm</application> achieves this without modifying
the C++ language.</para>
<para lang="en">
Re. Overriding signal handlers: You can do this in the straight-C world of GTK+ too; that's what GTK's
object system is for. But in GTK+, you have to go through some
complicated procedures to get object-oriented features like
inheritance and overloading. In C++, it's simple, since those
features are supported in the language itself; you can let the
compiler do the dirty work.
</para>
<para lang="en">
This is one of the places where the beauty of C++ really comes out.
One wouldn't think of subclassing a GTK+ widget simply to override its
action method; it's just too much trouble. In GTK+, you almost always
use signals to get things done, unless you're writing a new widget.
But because overriding methods is so easy in C++, it's entirely
practical - and sensible - to subclass a button for that purpose.
</para>
</appendix>

<appendix id="sec-windows-installation">
        <title><application>gtkmm</application> e Win32</title>
    <para lang="en">
      One of the major advantages of <application>gtkmm</application> is that it is crossplatform. <application>gtkmm</application> programs written on other platforms such as
      GNU/Linux can generally be transferred to Windows (and vice
      versa) with few modifications to the source.
    </para>
    <para lang="en">
      <application>gtkmm</application> currently works with the <ulink url="http://mingw.org/">MingW/GCC3.4 compiler</ulink> and Microsoft
      Visual C++ 2005 or later (including the freely available express
      editions) on the Windows platform. There is an
      <ulink url="ftp://ftp.gnome.org/pub/GNOME/binaries/win32/gtkmm">
      installer</ulink> available for gtkmm on Microsoft Windows. Refer to
      <ulink url="https://wiki.gnome.org/Projects/gtkmm/MSWindows/">
      https://wiki.gnome.org/Projects/gtkmm/MSWindows</ulink> for instructions how to
      use it.
    </para>
  <sect1 id="sec-building-on-win32">
        <title lang="en">Building <application>gtkmm</application> on Win32</title>
    <para lang="en">Please see <ulink url="https://wiki.gnome.org/Projects/gtkmm/MSWindows/BuildingGtkmm">
    https://wiki.gnome.org/Projects/gtkmm/MSWindows/BuildingGtkmm</ulink> for instructions on how to build gtkmm on Windows.
    </para>

    </sect1>
</appendix>

<appendix id="chapter-working-with-source">
  <title>Trabalhando com códigos fonte gtkmm</title>
  <para lang="en">
    If you are interested in helping out with the development of <application>gtkmm</application>, or
    fixing a bug in <application>gtkmm</application>, you'll probably need to build the development
    version of <application>gtkmm</application>. However, you should not install a development version over
    your stable version. Instead, you should install it alongside your existing <application>gtkmm</application>
    installation, in a separate path.
  </para>
  <para lang="en">
    The easiest way to do this is using <ulink url="https://wiki.gnome.org/Projects/Jhbuild">jhbuild</ulink>.
    <application>jhbuild</application> is a program that makes building GNOME
    software much easier by calculating dependencies and building things in the
    correct order. This section will give a brief explanation of how to set up
    <application>jhbuild</application> to build and install <application>gtkmm</application> from the
    source repository (git). For up-to-date information
    on <application>jhbuild</application>, please refer to the <ulink url="http://developer.gnome.org/jhbuild/unstable/">jhbuild manual</ulink>.
    If you need assistance using <application>jhbuild</application>, you should
    ask for help on the <ulink url="http://mail.gnome.org/mailman/listinfo/gnome-love">gnome-love
      mailing list</ulink>.
  </para>
  <note>
    <para lang="en">
    Note that to build <application>gtkmm</application> from git, you'll often need to build many of its
    dependencies from git as well. <application>jhbuild</application> makes
    this easier than it would normally be, but it will take quite a while to
    build and install them all. You will probably encounter build problems,
    though these will usually be corrected quickly if you report them.
    </para>
  </note>
  <sect1 id="sec-setting-up-jhbuild">
    <title>Configurando jhbuild</title>
    <para lang="en">
      To set up <application>jhbuild</application>, follow the basic
      installation instructions from the <ulink url="http://developer.gnome.org/jhbuild/unstable/">jhbuild manual</ulink>.
      After you have installed <application>jhbuild</application>, you
      should copy the sample <application>jhbuild</application> configuration
      file into your home directory by executing the following command from the
      <application>jhbuild</application> directory:
      <screen lang="en">$ cp examples/sample.jhbuildrc ~/.jhbuildrc</screen>
    </para>
    <para lang="en">
      The <application>gtkmm</application> module is defined in the
      <filename>gnome-suites-core-deps-3.x.modules</filename> moduleset, so edit your
      <filename>.jhbuildrc</filename> file and set your moduleset setting to the
      latest version e.g. like so:
      <programlisting lang="en">moduleset = 'gnome-suites-core-deps-3.12'</programlisting>
    </para>
    <para lang="en">
      After setting the correct moduleset, you need to tell
      <application>jhbuild</application> which module or modules to build. To
      build <application>gtkmm</application> and all of its dependencies, set <varname>modules</varname>
      like so:
      <programlisting lang="en">modules = [ 'gtkmm' ]</programlisting>
    </para>
    <para lang="en">
      You can build several modules by setting the
      <varname>modules</varname> variable to a meta-package, e.g.
      <literal>meta-gnome-core</literal>, or listing more than one module name.
      The <varname>modules</varname> variable specifies which modules will be
      built when you don't explicitly specify anything on the command line. You
      can always build a different moduleset later by specifying it on the
      commandline (e.g. <command>jhbuild build gtkmm</command>).
    </para>
    <important>
      <title>Definindo um prefixo</title>
      <para lang="en">
        By default, <application>jhbuild</application>'s configuration is
        configured to install all software built with
        <application>jhbuild</application> under the
        <filename>/opt/gnome</filename> prefix. You can choose a different
        prefix, but it is recommended that you keep this prefix different from
        other software that you've installed (don't set it to
        <filename>/usr</filename>!) If you've followed the jhbuild instructions
        then this prefix belongs to your user, so you don't need to run jhbuild
        as <literal>root</literal>.
      </para>
    </important>
    <para lang="en">
      When you downloaded <application>jhbuild</application> from the git repository,
      you got a number of <filename>.modules</filename> files, specifying
      dependencies between modules. By default <application>jhbuild</application>
      does not use the downloaded versions of these files, but reads the
      latest versions in the git repository. This is usually what you want.
      If you don't want it, use the <varname>use_local_modulesets</varname>
      variable in <filename>.jhbuildrc</filename>.
    </para>
  </sect1>
  <sect1 id="sec-installing-jhbuild">
    <title lang="en">Installing and Using the git version of <application>gtkmm</application></title>
    <para lang="en">
      Once you've configured <application>jhbuild</application> as described
      above, building <application>gtkmm</application> should be relatively straightforward. The first
      time you run <application>jhbuild</application>, you should run the
      following sequence of commands to ensure that
      <application>jhbuild</application> has the required tools and verify that
      it is set up correctly:
      <screen lang="en">$ jhbuild bootstrap
$ jhbuild sanitycheck</screen>
    </para>
    <sect2 id="jhbuild-installing-gtkmm">
      <title lang="en">Installing <application>gtkmm</application> with <application>jhbuild</application></title>
      <para lang="en">
        If everything worked correctly, you should be able to build <application>gtkmm</application> and
        all of its dependencies from git by executing <command>jhbuild
          build</command> (or, if you didn't specify <application>gtkmm</application> in the
        <varname>modules</varname> variable, with the command <command>jhbuild
          build gtkmm</command>).
      </para>
      <para lang="en">
        This command will build and install a series of modules and will probably
        take quite a long time the first time through. After the first time,
        however, it should go quite a bit faster since it only needs to rebuild
        files that changed since the last build. Alternatively, after you've
        built and installed <application>gtkmm</application> the first time, you can rebuild <application>gtkmm</application> by
        itself (without rebuilding all of its dependencies) with the command
        <command>jhbuild buildone gtkmm</command>.
      </para>
    </sect2>
    <sect2 id="jhbuild-using-gtkmm">
      <title lang="en">Using the git version of <application>gtkmm</application></title>
      <para lang="en">
        After you've installed the git version of <application>gtkmm</application>, you're ready to start
        using and experimenting with it. In order to use the new version of
        <application>gtkmm</application> you've just installed, you need to set some environment
        variables so that your <filename>configure</filename> script knows where
        to find the new libraries. Fortunately,
        <application>jhbuild</application> offers an easy solution to this
        problem. Executing the command <command>jhbuild shell</command> will
        start a new shell with all of the correct environment variables set.
        Now if you re-configure and build your project just as you usually do,
        it should link against the newly installed libraries. To return to your
        previous environment, simply exit the <application>jhbuild</application>
        shell.
      </para>
      <para lang="en">
        Once you've built your software, you'll need to run your program within
        the jhbuild environment as well. To do this, you can again use the
        <command>jhbuild shell</command> command to start a new shell with the
        <application>jhbuild</application> environment set up. Alternatively,
        you can execute a one-off command in the
        <application>jhbuild</application> environment using the following
        command: <command>jhbuild run command-name</command>. In this case,
        the command will be run with the correct environment variables set, but
        will return to your previous environment after the program exits.
      </para>

    </sect2>
  </sect1>
</appendix>

<appendix id="chapter-wrapping-c-libraries">
<title lang="en">Wrapping C Libraries with gmmproc</title>
<para lang="en"><application>gtkmm</application> uses the <command>gmmproc</command> tool to generate most of its
    source code, using .defs files that define the APIs of
    <classname>GObject</classname>-based libraries. So it's quite easy to create
    additional gtkmm-style wrappers of other glib/GObject-based
    libraries.</para>
<para lang="en">This involves a variety of tools, some of them crufty, but at least
    they work, and has been used successfully by several
    projects.</para>

<sect1 id="sec-wrapping-build-structure">
<title>Estrutura de construção</title>
<para lang="en">Generation of the source code for a gtkmm-style wrapper API requires use
    of tools such as <command>gmmproc</command> and
    <filename>generate_wrap_init.pl</filename>. In theory you could write your
    own build files to use these appropriately, but a much better option is to
    make use of the build infrastructure provided by the mm-common module. To
    get started, it helps a lot to pick an existing binding module as an example
    to look at.</para>
<para lang="en">For instance, let's pretend that we are wrapping a C library called
    libsomething. It provides a <classname>GObject</classname>-based API with
    types named, for instance, <classname>SomeWidget</classname> and
    <classname>SomeStuff</classname>.</para>

<sect2 id="copying-skeleton-project">
<title>Copiando o esqueleto do projeto</title>

<para lang="en">Typically our wrapper library would be called libsomethingmm. We can start by
  copying the <ulink url="http://git.gnome.org/browse/mm-common/tree/skeletonmm">skeleton
  source tree</ulink> from the mm-common module.
<programlisting lang="en">
  $ git clone git://git.gnome.org/mm-common
  $ cp -a mm-common/skeletonmm libsomethingmm
</programlisting>
</para>
<para lang="en">This provides a directory structure for the source .hg and .ccg files and the generated .h
  and .cc files, with <filename>filelist.am</filename> Automake include files that can specify the
  various files in use, in terms of generic Automake variables. The directory structure usually
  looks like this, after we have renamed the directories appropriately:
<itemizedlist>
    <listitem><para lang="en"><filename>libsomethingmm</filename>: The top-level directory.</para>
     <itemizedlist>
         <listitem><para lang="en"><filename>libsomething</filename>: Contains the main include file and the pkg-config .pc file.</para>
         <itemizedlist>
             <listitem><para lang="en"><filename>src</filename>: Contains .hg and .ccg source files.</para></listitem>
             <listitem><para lang="en"><filename>libsomethingmm</filename>: Contains generated and hand-written .h and .cc files.</para>
             <itemizedlist>
                 <listitem><para lang="en"><filename>private</filename>: Contains generated <filename>*_p.h</filename> files.</para></listitem>
             </itemizedlist>
           </listitem>
         </itemizedlist>
       </listitem>
    </itemizedlist>
  </listitem>
</itemizedlist>
</para>

<para lang="en">As well as renaming the directories, we should rename some of the source
    files. For instance:
<programlisting lang="en">
$ for f in $(find libsomethingmm -depth -name '*skeleton*'); do \
    d="${f%/*}"; b="${f##*/}"; mv "$f" "$d/${b//skeleton/libsomething}"; \
  done
</programlisting>
A number of the skeleton files must still be filled in with project-specific content later.
</para>
<para lang="en">Note that files ending in <filename>.in</filename> will be used to generate
    files with the same name but without the <filename>.in</filename> suffix, by
    replacing some variables with actual values during the configure stage.</para>
</sect2>

<sect2 id="modifying-build-files">
<title>Modificando arquivos de construção</title>

<para lang="en">Now we edit the files to adapt them to our needs. You might prefer to use a multiple-file
  search-replace utility for this, such as <command>regexxer</command>. Note that nearly all of the
  files provided with the skeleton source tree contain placeholder text. Thus, the substitutions
  should be performed globally, and not be limited to the Automake and Autoconf files.</para>
<para lang="en">All mentions of <varname>skeleton</varname> should be replaced by the correct name of the C
  library you are wrapping, such as "something" or "libsomething". In the same manner, all
  instances of <varname>SKELETON</varname> should be replaced by "SOMETHING" or "LIBSOMETHING", and
  all occurrences of <varname>Skeleton</varname> changed to "Something".</para>
<para lang="en">Likewise, replace all instances of <varname>Joe Hacker</varname> by the name of the intended
  copyright holder, which is probably you. Do the same for the <varname>joe@example.com</varname>
  email address.</para>

<sect3 id="modifying-configure.ac">
<title>configure.ac</title>
<para lang="en">In <filename>configure.ac</filename>,
<itemizedlist>
  <listitem><para lang="en">The <function>AC_CONFIG_SRCDIR()</function> line must mention a file
      in our source tree. We can edit this later if we don't yet know the
      names of any of the files that we will create.</para></listitem>
  <listitem><para lang="en">It is common for binding modules to track the version number
      of the library they are wrapping. So, for instance, if the C library is
      at version 1.23.4, then the initial version of the binding module would
      be 1.23.0. However, avoid starting with an even minor version number as
      that usually indicates a stable release.</para></listitem>
  <listitem><para lang="en">The <function>AC_CONFIG_HEADERS()</function> line is used to
      generate two or more configuration header files. The first header file
      in the list contains all configuration macros which are set during the
      configure run. The remaining headers in the list contain only a subset
      of configuration macros and their corresponding <filename>config.h.in</filename>
      file will not be autogenerated. The reason for this separation is that
      the namespaced configuration headers are installed with your library and
      define publically visible macros.</para></listitem>
  <listitem><para lang="en">The <function>AC_SUBST([SOMETHINGMM_MODULES], ['...'])</function>
      line may need to be modified to check for the correct dependencies.</para></listitem>
  <listitem><para lang="en">The <function>AC_CONFIG_FILES()</function> block must mention
      the correct directory names, as described above.</para></listitem>
</itemizedlist>
</para>
</sect3>

<sect3 id="modifying-makefile.am">
<title>Arquivos Makefile.am</title>
<para lang="en">Next we must adapt the various <filename>Makefile.am</filename> files:
  <itemizedlist>
    <listitem><para lang="en">In <filename>skeleton/src/Makefile.am</filename> we
            must mention the correct values for the generic variables that are used
            elsewhere in the build system:</para>
        <variablelist>
            <varlistentry>
                <term lang="en"><varname>binding_name</varname></term>
                <listitem><para lang="en">The name of the library, such as
                        libsomethingmm.</para></listitem>
            </varlistentry>
            <varlistentry>
                <term lang="en"><varname>wrap_init_flags</varname></term>
                <listitem><para lang="en">Additional command-line flags passed to the
                    <filename>generate_wrap_init.pl</filename> script, such
                    as the C++ namespace and the parent directory prefix of
                    include files.</para></listitem>
            </varlistentry>
        </variablelist>
    </listitem>
    <listitem><para lang="en">In <filename>skeleton/skeletonmm/Makefile.am</filename> we
            must mention the correct values for the generic variables that are used
            elsewhere in the build system:</para>
      <variablelist>
        <varlistentry>
          <term lang="en"><varname>lib_LTLIBRARIES</varname></term>
          <listitem><para lang="en">This variable must mention the correct library
              name, and this library name must be used to form the
              <varname>_SOURCES</varname>, <varname>_LDFLAGS</varname>, and
              <varname>_LIBADD</varname> variable names. It is permissible to
              use variables substituted by <filename>configure</filename> like
              <varname>@SOMETHINGMM_API_VERSION@</varname> as part of the
              variable names.</para></listitem>
        </varlistentry>
        <varlistentry>
          <term lang="en"><varname>AM_CPPFLAGS</varname></term>
          <listitem><para lang="en">The command line options passed to the C
              preprocessor.</para></listitem>
        </varlistentry>
        <varlistentry>
          <term lang="en"><varname>AM_CXXFLAGS</varname></term>
          <listitem><para lang="en">The command line options passed to the C++
              compiler.</para></listitem>
        </varlistentry>
      </variablelist>
    </listitem>
  </itemizedlist>
</para>
</sect3>

<sect3 id="creating-hg-ccg">
<title>Criação de arquivos .hg e .ccg</title>
<para lang="en">We should now create our first <filename>.hg</filename> and <filename>.ccg</filename> files,
  to wrap one of the objects in the C library. One pair of example source files already exists:
  <filename>skeleton.ccg</filename> and <filename>skeleton.hg</filename>. Create copies of these
  files as necessary.</para>
<para lang="en">We must mention all of our <filename>.hg</filename> and
  <filename>.ccg</filename> files in the
  <filename>skeleton/src/filelist.am</filename> file, typically in the
  <varname>files_hg</varname> variable.</para>
<para lang="en">Any additional non-generated <filename>.h</filename> and
  <filename>.cc</filename> source files may be placed in
  <filename>skeleton/skeletonmm/</filename> and listed in
  <filename>skeleton/skeletonmm/filelist.am</filename>, typically in the
  <varname>files_extra_h</varname> and <varname>files_extra_cc</varname>
  variables.</para>
<para lang="en">In the <link linkend="sec-wrapping-hg-files">.hg and .ccg files</link>
  section you can learn about the syntax used in these files.</para>
</sect3>
</sect2>
</sect1>

<sect1 id="sec-wrapping-defs-files">
<title>Gerando os arquivos .defs.</title>
<para lang="en">The <filename>.defs</filename> files are text files, in a lisp format, that describe the API
  of a C library, including its
<itemizedlist>
  <listitem><para lang="en">objects (GObjects, widgets, interfaces, boxed-types and plain structs)</para></listitem>
  <listitem><para lang="en">functions</para></listitem>
  <listitem><para lang="en">enums</para></listitem>
  <listitem><para lang="en">signals</para></listitem>
  <listitem><para lang="en">properties</para></listitem>
  <listitem><para lang="en">vfuncs</para></listitem>
</itemizedlist>
</para>
<para lang="en">At the moment, we have separate tools for generating different parts of
  these <filename>.defs</filename>, so we split them up into separate files.
  For instance, in the <filename>gtk/src</filename> directory of the <application>gtkmm</application>
  sources, you will find these files:
    <variablelist>
        <varlistentry>
            <term lang="en"><filename>gtk.defs</filename></term>
            <listitem><para lang="en">Includes the other files.</para></listitem>
        </varlistentry>
        <varlistentry>
            <term lang="en"><filename>gtk_methods.defs</filename></term>
            <listitem><para lang="en">Objects and functions.</para></listitem>
        </varlistentry>
        <varlistentry>
            <term lang="en"><filename>gtk_enums.defs</filename></term>
            <listitem><para lang="en">Enumerations.</para></listitem>
        </varlistentry>
        <varlistentry>
            <term lang="en"><filename>gtk_signals.defs</filename></term>
            <listitem><para lang="en">Signals and properties.</para></listitem>
        </varlistentry>
        <varlistentry>
            <term lang="en"><filename>gtk_vfuncs.defs</filename></term>
            <listitem><para lang="en">vfuncs (function pointer member fields in structs), written by hand.</para></listitem>
        </varlistentry>
    </variablelist>
</para>
<para lang="en">The <filename>skeletonmm/codegen/generate_defs_and_docs.sh</filename> script
generates all <filename>.defs</filename> files and the <filename>*_docs.xml</filename> file,
described in the <link linkend="sec-wrapping-documentation">Documentation</link> section.
</para>

<sect2 id="generating-defs-methods">
<title>Gerando o methods .defs</title>
<para lang="en">This <filename>.defs</filename> file describes objects and their functions.
  It is generated by the <command>h2def.py</command> script which you can find in
  glibmm's <filename>tools/defs_gen</filename> directory. For instance,
<programlisting lang="en">
$ ./h2def.py /usr/include/gtk-3.0/gtk/*.h &gt; gtk_methods.defs
</programlisting>
</para>
</sect2>

<sect2 id="generating-defs-enums">
<title>Gerando o enums .defs</title>
<para lang="en">This <filename>.defs</filename> file describes enum types and their possible
  values. It is generated by the <filename>enum.pl</filename> script which you can
  find in glibmm's <filename>tools</filename> directory. For instance,
<programlisting lang="en">
$ ./enum.pl /usr/include/gtk-3.0/gtk/*.h &gt; gtk_enums.defs
</programlisting>
</para>
</sect2>

<sect2 id="generating-defs-signals-properties">
<title lang="en">Generating the signals and properties .defs</title>
<para lang="en">This <filename>.defs</filename> file describes signals and properties. It is
  generated by the special <filename>generate_extra_defs</filename> utility that is in every
  wrapping project, such as <filename>gtkmm/tools/extra_defs_gen/</filename>.
  For instance
<programlisting lang="en">
$ cd tools/extra_defs_gen
$ ./generate_extra_defs &gt; gtk_signals.defs
</programlisting>
</para>
<para lang="en">You must edit the source code of your own <filename>generate_extra_defs</filename> tool
  in order to generate the <filename>.defs</filename> for the GObject C types that you wish to
  wrap. In the skeleton source tree, the source file is named
  <filename>codegen/extradefs/generate_extra_defs_skeleton.cc</filename>. If not done so
  already, the file should be renamed, with the basename of your new binding substituted
  for the <varname>skeleton</varname> placeholder. The <filename>codegen/Makefile.am</filename>
  file should also mention the new source filename.</para>
<para lang="en">Then edit the <filename>.cc</filename> file to specify the correct types.
  For instance, your <function>main()</function> function might look like this:
<programlisting lang="en">
#include &lt;libsomething.h&gt;

int main(int, char**)
{
  something_init();

  std::cout &lt;&lt; get_defs(SOME_TYPE_WIDGET)
            &lt;&lt; get_defs(SOME_TYPE_STUFF);
  return 0;
}
</programlisting>
</para>
</sect2>

<sect2 id="writing-defs-vfuncs">
<title>Escrevendo o vfuncs .defs</title>
<para lang="en">
  This <filename>.defs</filename> file describes virtual functions (vfuncs).
  It must be written by hand. There is the skeleton file
  <filename>skeleton/src/skeleton_vfunc.defs</filename> to start from. You can also look
  at <application>gtkmm</application>'s <filename>gtk/src/gtk_vfuncs.defs</filename> file.
</para>
</sect2>

</sect1>

<sect1 id="sec-wrapping-hg-files">
    <title>Os arquivos .hg e .ccg</title>
    <para lang="en">The .hg and .ccg source files are very much like
        .h and .cc C++ source files, but they contain extra macros, such as
        <function>_CLASS_GOBJECT()</function> and
        <function>_WRAP_METHOD()</function>, from which
        <command>gmmproc</command> generates appropriate C++ source code,
        usually at the same position in the header. Any additional C++ source
        code will be copied verbatim into the corresponding
        .h or .cc file.</para>
    <para lang="en">A .hg file will typically include some headers
        and then declare a class, using some macros to add API or behaviour to
        this class. For instance, <application>gtkmm</application>'s <filename>button.hg</filename> looks
        roughly like this:

<programlisting lang="en">
#include &lt;gtkmm/bin.h&gt;
#include &lt;gtkmm/activatable.h&gt;
_DEFS(gtkmm,gtk)
_PINCLUDE(gtkmm/private/bin_p.h)

namespace Gtk
{

class Button
  : public Bin,
    public Activatable
{
  _CLASS_GTKOBJECT(Button,GtkButton,GTK_BUTTON,Gtk::Bin,GtkBin)
  _IMPLEMENTS_INTERFACE(Activatable)
public:

  _CTOR_DEFAULT
  explicit Button(const Glib::ustring&amp; label, bool mnemonic = false);

  _WRAP_METHOD(void set_label(const Glib::ustring&amp; label), gtk_button_set_label)

  ...

  _WRAP_SIGNAL(void clicked(), "clicked")

  ...

  _WRAP_PROPERTY("label", Glib::ustring)
};

} // namespace Gtk
</programlisting>
</para>
<para lang="en">The macros in this example do the following:
<variablelist>
    <varlistentry>
        <term lang="en"><function>_DEFS()</function></term>
        <listitem><para lang="en">Specifies the destination directory for generated sources, and the name of the main .defs file that <command>gmmproc</command> should parse.</para></listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en"><function>_PINCLUDE()</function></term>
        <listitem><para lang="en">Tells <command>gmmproc</command> to include a header in the generated private/button_p.h file.</para></listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en"><function>_CLASS_GTKOBJECT()</function></term>
        <listitem><para lang="en">Tells <command>gmmproc</command> to add some typedefs, constructors, and standard methods to this class, as appropriate when wrapping a widget.</para></listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en"><function>_IMPLEMENTS_INTERFACE()</function></term>
        <listitem><para lang="en">Tells <command>gmmproc</command> to add initialization code for the interface.</para></listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en"><function>_CTOR_DEFAULT</function></term>
        <listitem><para lang="en">Add a default constructor.</para></listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en"><function>_WRAP_METHOD()</function>,
            <function>_WRAP_SIGNAL()</function>,
            <function>_WRAP_PROPERTY()</function>, and
            <function>_WRAP_CHILD_PROPERTY()</function></term>
        <listitem><para lang="en">Add methods to wrap parts of the C API.</para></listitem>
    </varlistentry>
</variablelist>
</para>
<para lang="en">The .h and .cc files will be generated from the .hg and .ccg files by
    processing them with <command>gmmproc</command> like so, though this happens
    automatically when using the above build structure:
<programlisting lang="en">
$ cd gtk/src
$ /usr/lib/glibmm-2.4/proc/gmmproc -I ../../tools/m4 --defs . button . ./../gtkmm
</programlisting>
</para>
<para lang="en">Notice that we provided <command>gmmproc</command> with the path to the
    .m4 convert files, the path to the .defs file, the name of a .hg file, the
    source directory, and the destination directory.</para>
<para lang="en">You should avoid including the C header from your C++ header, to avoid
    polluting the global namespace, and to avoid exporting unnecessary public
    API. But you will need to include the necessary C headers from your
    .ccg file.</para>

<para lang="en">The macros are explained in more detail in the following sections.</para>

<sect2 id="gmmproc-m4-conversions">
<title>Conversões m4</title>
<para lang="en">The macros that you use in the .hg and .ccg files often need to know how
to convert a C++ type to a C type, or vice-versa. gmmproc takes this information
from an .m4 file in your <literal>tools/m4/</literal> directory. This allows it
to call a C function in the implementation of your C++ method, passing the
appropriate parameters to that C functon. For instance, this
tells gmmproc how to convert a GtkTreeView pointer to a Gtk::TreeView pointer:
<programlisting lang="en">
_CONVERSION(`GtkTreeView*',`TreeView*',`Glib::wrap($3)')
</programlisting>
</para>

<para lang="en"><literal>$3</literal> will be replaced by the parameter name when this
conversion is used by gmmproc.
</para>

<para lang="en">
Some extra macros make this easier and consistent. Look in gtkmm's .m4 files
for examples. For instance:
<programlisting lang="en">
_CONVERSION(`PrintSettings&amp;',`GtkPrintSettings*',__FR2P)
_CONVERSION(`const PrintSettings&amp;',`GtkPrintSettings*',__FCR2P)
_CONVERSION(`const Glib::RefPtr&lt;Printer&gt;&amp;',`GtkPrinter*',__CONVERT_REFPTR_TO_P($3))
</programlisting>
</para>
</sect2>

<sect2 id="gmmproc-m4-initializations">
<title>Inicializações m4</title>
<para lang="en">
  Often when wrapping methods, it is desirable to store the return of the C
  function in what is called an output parameter.  In this case, the C++ method
  returns <type>void</type> but an output parameter in which to store the value
  of the C function is included in the argument list of the C++ method.
  gmmproc allows such functionality, but appropriate initialization macros must
  be included to tell gmmproc how to initialize the C++ parameter from the
  return of the C function.
</para>
<para lang="en">
  For example, if there was a C function that returned a
  <type>GtkWidget*</type> and for some reason, instead of having the C++ method
  also return the widget, it was desirable to have the C++ method place the
  widget in a specified output parameter, an initialization macro such as the
  following would be necessary:
<programlisting lang="en">
_INITIALIZATION(`Gtk::Widget&amp;',`GtkWidget*',`$3 = Glib::wrap($4)')
</programlisting>
</para>

<para lang="en">
  <literal>$3</literal> will be replaced by the output parameter name of the
  C++ method and <literal>$4</literal> will be replaced by the return of the C
  function when this initialization is used by gmmproc.  For convenience,
  <literal>$1</literal> will also be replaced by the C++ type without the
  ampersand (&amp;) and <literal>$2</literal> will be replaced by the C type.
</para>
</sect2>


<sect2 id="gmmproc-class-macros">
<title>Macros de classes</title>
<para lang="en">The class macro declares the class itself and its relationship with the
    underlying C type. It generates some internal constructors, the member
    <varname>gobject_</varname>, typedefs, the <function>gobj()</function>
    accessors, type registration, and the <function>Glib::wrap()</function>
    method, among other things.</para>
<para lang="en">Other macros, such as <function>_WRAP_METHOD()</function> and
    <function>_WRAP_SIGNAL()</function> may only be used after a call to a
    <function>_CLASS_*</function> macro.</para>

<sect3 id="gmmproc-class-gobject">
<title>_CLASS_GOBJECT</title>
<para lang="en">This macro declares a wrapper for a type that is derived from
    <classname>GObject</classname>, but whose wrapper is not derived from
    <classname>Gtk::Object</classname>.</para>
<para lang="en"><function>_CLASS_GOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )</function></para>
<para lang="en">For instance, from <filename>accelgroup.hg</filename>:
<programlisting lang="en">
_CLASS_GOBJECT(AccelGroup, GtkAccelGroup, GTK_ACCEL_GROUP, Glib::Object, GObject)
</programlisting>
</para>
</sect3>

<sect3 id="gmmproc-class-gtkobject">
<title>_CLASS_GTKOBJECT</title>
<para lang="en">This macro declares a wrapper for a type whose wrapper is derived from
    <classname>Gtk::Object</classname>, such as a widget or dialog.</para>
<para lang="en"><function>_CLASS_GTKOBJECT( C++ class, C class, C casting macro, C++ base class, C base class )</function></para>
<para lang="en">For instance, from <filename>button.hg</filename>:
<programlisting lang="en">
_CLASS_GTKOBJECT(Button, GtkButton, GTK_BUTTON, Gtk::Bin, GtkBin)
</programlisting>
</para>
<para lang="en">You will typically use this macro when the class already derives from Gtk::Object. For instance, you will use it when wrapping a GTK+ Widget, because Gtk::Widget derives from Gtk::Object.</para>
<para lang="en">You might also derive non-widget classes from Gtk::Object so they can be used without <classname>Glib::RefPtr</classname>. For instance, they could then be instantiated with <function>Gtk::manage()</function> or on the stack as a member variable. This is convenient, but you should use this only when you are sure that true reference-counting is not needed. We consider it useful for widgets.</para>
</sect3>

<sect3 id="gmmproc-class-boxedtype">
<title>_CLASS_BOXEDTYPE</title>
<para lang="en">This macro declares a wrapper for a non-<classname>GObject</classname>
    struct, registered with
    <function>g_boxed_type_register_static()</function>.</para>
<para lang="en"><function>_CLASS_BOXEDTYPE( C++ class, C class, new function, copy function, free function )</function></para>
<para lang="en">For instance, from <classname>Gdk::RGBA</classname>:
<programlisting lang="en">
_CLASS_BOXEDTYPE(RGBA, GdkRGBA, NONE, gdk_rgba_copy, gdk_rgba_free)
</programlisting>
</para>
</sect3>

<sect3 id="gmmproc-class-boxedtype-static">
<title>_CLASS_BOXEDTYPE_STATIC</title>
<para lang="en">This macro declares a wrapper for a simple assignable struct such as
    <classname>GdkRectangle</classname>. It is similar to
    <function>_CLASS_BOXEDTYPE</function>, but the C struct is not allocated
    dynamically.</para>
<para lang="en"><function>_CLASS_BOXEDTYPE_STATIC( C++ class, C class )</function></para>
<para lang="en">For instance, for <classname>Gdk::Rectangle</classname>:
<programlisting lang="en">
_CLASS_BOXEDTYPE_STATIC(Rectangle, GdkRectangle)
</programlisting>
</para>
</sect3>

<sect3 id="gmmproc-class-opaque-copyable">
<title>_CLASS_OPAQUE_COPYABLE</title>
<para lang="en">This macro declares a wrapper for an opaque struct that has copy and free
    functions. The new, copy and free functions will be used to instantiate the
    default constructor, copy constructor and destructor.</para>
<para lang="en"><function>_CLASS_OPAQUE_COPYABLE( C++ class, C class, new function, copy function, free function )</function></para>
<para lang="en">For instance, from <classname>Glib::Checksum</classname>:
<programlisting lang="en">
_CLASS_OPAQUE_COPYABLE(Checksum, GChecksum, NONE, g_checksum_copy, g_checksum_free)
</programlisting>
</para>
</sect3>

<sect3 id="gmmproc-class-opaque-refcounted">
<title>_CLASS_OPAQUE_REFCOUNTED</title>
<para lang="en">This macro declares a wrapper for a reference-counted opaque struct. The
    C++ wrapper cannot be directly instantiated and can only be used with
    <classname>Glib::RefPtr</classname>.</para>
<para lang="en"><function>_CLASS_OPAQUE_REFCOUNTED( C++ class, C class, new function, ref function, unref function )</function></para>
<para lang="en">For instance, for <classname>Pango::Coverage</classname>:
<programlisting lang="en">
_CLASS_OPAQUE_REFCOUNTED(Coverage, PangoCoverage, pango_coverage_new, pango_coverage_ref, pango_coverage_unref)
</programlisting>
</para>
</sect3>

<sect3 id="gmmproc-class-generic">
<title>_CLASS_GENERIC</title>
<para lang="en">This macro can be used to wrap structs which don't fit into any
    specialized category.</para>
<para lang="en"><function>_CLASS_GENERIC( C++ class, C class )</function></para>
<para lang="en">For instance, for <classname>Pango::AttrIter</classname>:
<programlisting lang="en">
_CLASS_GENERIC(AttrIter, PangoAttrIterator)
</programlisting>
</para>
</sect3>

<sect3 id="gmmproc-class-interface">
<title>_CLASS_INTERFACE</title>
<para lang="en">This macro declares a wrapper for a type that is derived from
    <classname>GTypeInterface</classname>.
</para>
<para lang="en"><function>_CLASS_INTERFACE( C++ class, C class, C casting macro, C interface struct, Base C++ class (optional), Base C class (optional) )</function></para>
<para lang="en">
For instance, from <filename>celleditable.hg</filename>:
<programlisting lang="en">
_CLASS_INTERFACE(CellEditable, GtkCellEditable, GTK_CELL_EDITABLE, GtkCellEditableIface)
</programlisting>
</para>
<para lang="en">Two extra parameters are optional, for the case that the interface derives from another interface,
which should be the case when the GInterface has another GInterface as a prerequisite.
For instance, from <filename>loadableicon.hg</filename>:
<programlisting lang="en">
_CLASS_INTERFACE(LoadableIcon, GLoadableIcon, G_LOADABLE_ICON, GLoadableIconIface, Icon, GIcon)
</programlisting>
</para>
</sect3>

</sect2>

<sect2 id="gmmproc-constructor-macros">
<title>Contrutor de macros</title>
<para lang="en">The <function>_CTOR_DEFAULT()</function> and
    <function>_WRAP_CTOR()</function> macros add constructors, wrapping the
    specified <function>*_new()</function> C functions. These macros assume that
    the C object has properties with the same names as the function parameters,
    as is usually the case, so that it can supply the parameters directly to a
    <function>g_object_new()</function> call. These constructors never actually
    call the <function>*_new()</function> C functions,
    because gtkmm must actually instantiate derived GTypes, and the
    <function>*_new()</function> C functions are meant only as convenience
    functions for C programmers.</para>
<para lang="en">When using <function>_CLASS_GOBJECT()</function>, the constructors should
    be protected (rather than public) and each constructor should have a
    corresponding <function>_WRAP_CREATE()</function> in the public section.
    This prevents the class from being instantiated without using a
    <classname>RefPtr</classname>. For instance:
<programlisting lang="en">
class TextMark : public Glib::Object
{
  _CLASS_GOBJECT(TextMark, GtkTextMark, GTK_TEXT_MARK, Glib::Object, GObject)

protected:
  _WRAP_CTOR(TextMark(const Glib::ustring&amp; name, bool left_gravity = true), gtk_text_mark_new)

public:
  _WRAP_CREATE(const Glib::ustring&amp; name, bool left_gravity = true)
</programlisting>
</para>

<sect3 id="gmmproc-ctor-default">
<title>_CTOR_DEFAULT</title>
<para lang="en">This macro creates a default constructor with no arguments.
</para>
</sect3>

<sect3 id="gmmproc-wrap-ctor">
<title>_WRAP_CTOR</title>
<para lang="en">This macro creates a constructor with arguments, equivalent to a
  <function>*_new()</function> C function. It won't actually call the
  <function>*_new()</function> function, but will simply create an equivalent
  constructor with the same argument types. It takes a C++ constructor
  signature, and a C function name.
</para>

<para lang="en">It also takes an optional extra argument:
  <variablelist>
    <varlistentry>
        <term lang="en">errthrow</term>
        <listitem>
          <para lang="en">This tells gmmproc that the C <function>*_new()</function> has
            a final GError** parameter which should be ignored.</para>
        </listitem>
    </varlistentry>
  </variablelist>
</para>
</sect3>

<sect3 id="gmmproc-ctor-manual">
<title lang="en">Hand-coding constructors</title>
<para lang="en">When a constructor must be partly hand written because, for instance, the
    <function>*_new()</function> C function's parameters do not correspond
    directly to object properties, or because the <function>*_new()</function> C
    function does more than call <function>g_object_new()</function>, the
    <function>_CONSTRUCT()</function> macro may be used in the
    .ccg file to save some work. The <function>_CONSTRUCT</function> macro takes
    a series of property names and values. For instance, from
    <filename>button.ccg</filename>:
<programlisting lang="en">
Button::Button(const Glib::ustring&amp; label, bool mnemonic)
:
  _CONSTRUCT("label", label.c_str(), "use_underline", gboolean(mnemonic))
{}
</programlisting>
</para>
</sect3>

</sect2>

<sect2 id="gmmproc-method-macros">
<title>Métodos macros</title>

<sect3 id="gmmproc-wrap-method">
<title>_WRAP_METHOD</title>
<para lang="en">This macro generates the C++ method to wrap a C function.</para>
<para lang="en"><function>_WRAP_METHOD( C++ method signature, C function name)</function></para>
<para lang="en">For instance, from <filename>entry.hg</filename>:
<programlisting lang="en">
_WRAP_METHOD(void set_text(const Glib::ustring&amp; text), gtk_entry_set_text)
</programlisting>
</para>
<para lang="en">The C function (e.g. <function>gtk_entry_set_text</function>) is described
    more fully in the .defs file, and the <filename>convert*.m4</filename> files
    contain the necessary conversion from the C++ parameter type to the C
    parameter type. This macro also generates doxygen documentation comments
    based on the <filename>*_docs.xml</filename> and
    <filename>*_docs_override.xml</filename> files.</para>
<para lang="en">There are some optional extra arguments:
<variablelist>
    <varlistentry>
        <term lang="en">refreturn</term>
        <listitem>
            <para lang="en">Do an extra <function>reference()</function> on the return value,
                in case the C function does not provide a reference.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">errthrow</term>
        <listitem>
            <para lang="en">Use the last GError** parameter of the C function to
                throw an exception.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">deprecated</term>
        <listitem>
            <para lang="en">Puts the generated code in #ifdef blocks. Text about the
                deprecation can be specified as an optional
                parameter.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">constversion</term>
        <listitem>
            <para lang="en">Just call the non-const version of the same function,
                instead of generating almost duplicate code.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">ifdef</term>
        <listitem>
            <para lang="en">Puts the generated code in #ifdef blocks.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">slot_name</term>
        <listitem>
          <para lang="en">Specifies the name of the slot parameter of the method, if it
            has one.  This enables <command>gmmproc</command> to generate code
            to copy the slot and pass the copy on to the C function in its
            final <literal>gpointer user_data</literal> parameter.  The
            <literal>slot_callback</literal> option must also be used to
            specify the name of the glue callback function to also pass on to
            the C function.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">slot_callback</term>
        <listitem>
          <para lang="en">Used in conjunction with the <literal>slot_name</literal>
            option to specify the name of the glue callback function that
            handles extracting the slot and then calling it.  The address of
            this callback is also passed on to the C function that the method
            wraps.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">no_slot_copy</term>
        <listitem>
          <para lang="en">Tells <command>gmmproc</command> not to pass a copy of the slot
            to the C function, if the method has one.  Instead the slot itself
            is passed.  The slot parameter name and the glue callback function
            must have been specified with the <literal>slot_name</literal> and
            <literal>slot_callbback</literal> options respectively.</para>
        </listitem>
    </varlistentry>
</variablelist>
</para>
<para lang="en">Selecting which C++ types should be used is also important when wrapping
  C API.  Though it's usually obvious what C++ types should be used in the C++
  method, here are some hints:
<itemizedlist>
    <listitem><para lang="en">Objects used via <classname>RefPtr</classname>: Pass the
            <classname>RefPtr</classname> as a const reference. For instance,
            <code>const Glib::RefPtr&lt;Gtk::FileFilter&gt;&amp;
                filter</code>.</para></listitem>
    <listitem><para lang="en">Const Objects used via <classname>RefPtr</classname>: If the
            object should not be changed by the function, then make sure that
            the object is const, even if the <classname>RefPtr</classname> is
            already const. For instance, <code>const Glib::RefPtr&lt;const
            Gtk::FileFilter&gt;&amp; filter</code>.</para></listitem>
<listitem><para lang="en">Wrapping <classname>GList*</classname> and
        <classname>GSList*</classname> parameters: First, you need to discover
        what objects are contained in the list's data field for each item,
        usually by reading the documentation for the C function. The list can
        then be wrapped by a <classname>std::vector</classname> type.
        For instance, <code>std::vector&lt;
        Glib::RefPtr&lt;Gdk::Pixbuf&gt; &gt;</code>.
        You may need to define a Traits type to specify how the C
        and C++ types should be converted.</para></listitem>
<listitem><para lang="en">Wrapping <classname>GList*</classname> and
        <classname>GSList*</classname> return types: You must discover whether
        the caller should free the list and whether it should release the items
        in the list, again by reading the documentation of the C function. With
        this information you can choose the ownership (none, shallow or deep)
        for the m4 conversion rule, which you should probably put directly into
        the .hg file because the ownership depends on the
        function rather than the type. For instance:
<programlisting lang="en">#m4 _CONVERSION(`GSList*',`std::vector&lt;Widget*&gt;',`Glib::SListHandler&lt;Widget*&gt;::slist_to_vector($3, Glib::OWNERSHIP_SHALLOW)')</programlisting></para></listitem>
</itemizedlist>
</para>
</sect3>

<sect3 id="gmmproc-wrap-method-docs-only">
<title lang="en">_WRAP_METHOD_DOCS_ONLY</title>
<para lang="en">This macro is like <function>_WRAP_METHOD()</function>, but it generates
    only the documentation for a  C++ method that wraps a C function. Use this
    when you must hand-code the method, but you want to use the documentation
    that would be generated if the method was generated.</para>
<para lang="en"><function>_WRAP_METHOD_DOCS_ONLY(C function name)</function></para>
<para lang="en">For instance, from <filename>container.hg</filename>:
<programlisting lang="en">
_WRAP_METHOD_DOCS_ONLY(gtk_container_remove)
</programlisting>
</para>
</sect3>

<sect3 id="gmmproc-ignore">
<title>_IGNORE / _IGNORE_SIGNAL</title>
<para lang="en"><command>gmmproc</command> will warn you on stdout about functions and signals that
    you have forgotten to wrap, helping to ensure that you are wrapping the
    complete API. But if you don't want to wrap some functions or signals, or if you chose
    to hand-code some methods then you can use the _IGNORE() or _IGNORE_SIGNAL() macro to make
    <command>gmmproc</command> stop complaining.</para>
<para lang="en"><function>_IGNORE(C function name 1, C function name2, etc)</function></para>
<para lang="en"><function>_IGNORE_SIGNAL(C signal name 1, C signal name2, etc)</function></para>
<para lang="en">For instance, from <filename>buttonbox.hg</filename>:
<programlisting lang="en">
_IGNORE(gtk_button_box_set_spacing, gtk_button_box_get_spacing)
</programlisting>
</para>
</sect3>

<sect3 id="gmmproc-wrap-signal">
<title>_WRAP_SIGNAL</title>
<para lang="en">This macro generates the C++ libsigc++-style signal to wrap a C GObject
    signal. It actually generates a public accessor method, such as
    <function>signal_clicked()</function>, which returns a proxy object.
    <command>gmmproc</command> uses the .defs file to discover the C parameter
    types and the .m4 convert files to discover appropriate type
    conversions.</para>
<para lang="en"><function>_WRAP_SIGNAL( C++ signal handler signature, C signal name)</function></para>
<para lang="en">For instance, from <filename>button.hg</filename>:
<programlisting lang="en">
_WRAP_SIGNAL(void clicked(),"clicked")
</programlisting>
</para>
<para lang="en">Signals usually have function pointers in the GTK struct, with a
    corresponding enum value and a <function>g_signal_new()</function> in the
    .c file.</para>
<para lang="en">There are some optional extra arguments:
<variablelist>
    <varlistentry>
        <term lang="en">no_default_handler</term>
        <listitem>
            <para lang="en">Do not generate an <function>on_something()</function> virtual
                method to allow easy overriding of the default signal handler.
                Use this when adding a signal with a default signal handler
                would break the ABI by increasing the size of the class's
                virtual function table.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">custom_default_handler</term>
        <listitem>
            <para lang="en">Generate a declaration of the <function>on_something()</function>
                virtual method in the <filename>.h</filename> file, but do not
                generate a definition in the <filename>.cc</filename> file.
                Use this when you must generate the definition by hand.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">custom_c_callback</term>
        <listitem>
            <para lang="en">Do not generate a C callback function for the signal.
                Use this when you must generate the callback function by hand.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">refreturn</term>
        <listitem>
            <para lang="en">Do an extra <function>reference()</function> on the return value
                of the <function>on_something()</function> virtual method, in
                case the C function does not provide a reference.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">ifdef</term>
        <listitem>
            <para lang="en">Puts the generated code in #ifdef blocks.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">exception_handler</term>
	      <listitem>
	        <para lang="en">Allows to use custom exception handler instead of default one. Exception might be rethrown by user-defined handler, and it will be catched by default handler.</para>
	      </listitem>
    </varlistentry>
</variablelist>
</para>
</sect3>

<sect3 id="gmmproc-wrap-property">
<title>_WRAP_PROPERTY</title>
<para lang="en">This macro generates the C++ method to wrap a C GObject property. You must
    specify the property name and the wanted C++ type for the property. <command>gmmproc</command>
    uses the .defs file to discover the C type and the .m4 convert files to
    discover appropriate type conversions.</para>
<para lang="en"><function>_WRAP_PROPERTY(C property name, C++ type)</function></para>
<para lang="en">For instance, from <filename>button.hg</filename>:
<programlisting lang="en">
_WRAP_PROPERTY("label", Glib::ustring)
</programlisting>
</para>
</sect3>

<sect3 id="gmmproc-wrap-vfunc">
<title>_WRAP_VFUNC</title>
<para lang="en">This macro generates the C++ method to wrap a virtual C function.</para>
<para lang="en"><function>_WRAP_VFUNC( C++ method signature, C function name)</function></para>
<para lang="en">For instance, from <filename>widget.hg</filename>:
<programlisting lang="en">
_WRAP_VFUNC(SizeRequestMode get_request_mode() const, get_request_mode)
</programlisting>
</para>
<para lang="en">The C function (e.g. <function>get_request_mode</function>) is described
    more fully in the <filename>*_vfuncs.defs</filename> file, and the
    <filename>convert*.m4</filename> files contain the necessary conversion from
    the C++ parameter type to the C parameter type.</para>
<para lang="en">There are some optional extra arguments:
<variablelist>
    <varlistentry>
        <term lang="en">refreturn</term>
        <listitem>
            <para lang="en">Do an extra <function>reference()</function> on the return value
                of the <function>something_vfunc()</function> function,
                in case the virtual C function does not provide a reference.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">refreturn_ctype</term>
        <listitem>
            <para lang="en">Do an extra <function>reference()</function> on the return value
                of an overridden <function>something_vfunc()</function> function
                in the C callback function, in case the calling C function
                expects it to provide a reference.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">errthrow</term>
        <listitem>
            <para lang="en">Use the last GError** parameter of the C virtual function (if
              there is one) to throw an exception.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">custom_vfunc</term>
        <listitem>
            <para lang="en">Do not generate a definition of the vfunc in the
               <filename>.cc</filename> file. Use this when you must generate
               the vfunc by hand.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">custom_vfunc_callback</term>
        <listitem>
            <para lang="en">Do not generate a C callback function for the vfunc.
                Use this when you must generate the callback function by hand.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">ifdef</term>
        <listitem>
            <para lang="en">Puts the generated code in #ifdef blocks.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">slot_name</term>
        <listitem>
          <para lang="en">Specifies the name of the slot parameter of the method, if it
            has one.  This enables <command>gmmproc</command> to generate code
            to copy the slot and pass the copy on to the C function in its
            final <literal>gpointer user_data</literal> parameter.  The
            <literal>slot_callback</literal> option must also be used to
            specify the name of the glue callback function to also pass on to
            the C function.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">slot_callback</term>
        <listitem>
          <para lang="en">Used in conjunction with the <literal>slot_name</literal>
            option to specify the name of the glue callback function that
            handles extracting the slot and then calling it.  The address of
            this callback is also passed on to the C function that the method
            wraps.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">no_slot_copy</term>
        <listitem>
          <para lang="en">Tells <command>gmmproc</command> not to pass a copy of the slot
            to the C function, if the method has one.  Instead the slot itself
            is passed.  The slot parameter name and the glue callback function
            must have been specified with the <literal>slot_name</literal> and
            <literal>slot_callbback</literal> options respectively.</para>
        </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">return_value</term>
	      <listitem>
	        <para lang="en">Defines non-default return value.</para>
	      </listitem>
    </varlistentry>
    <varlistentry>
        <term lang="en">exception_handler</term>
	      <listitem>
	        <para lang="en">Allows to use custom exception handler instead of default one. Exception might be rethrown by user-defined handler, and it will be catched by default handler.</para>
	      </listitem>
    </varlistentry>
</variablelist>
</para>
<para lang="en">A rule to which there may be exceptions: If the virtual C function returns
    a pointer to an object derived from <classname>GObject</classname>, i.e. a
    reference-counted object, then the virtual C++ function shall return a
    <classname>Glib::RefPtr&lt;&gt;</classname> object. One of the extra
    arguments <parameter>refreturn</parameter> or
    <parameter>refreturn_ctype</parameter> is required.</para>
</sect3>

<sect3 id="gmmproc-wrap-child-property">
<title lang="en">_WRAP_CHILD_PROPERTY</title>
<para lang="en">This macro generates the C++ method to wrap a GtkContainer child property.
    (See <ulink url="https://developer.gnome.org/gtk3/stable/GtkContainer.html">
    GtkContainer</ulink> for more information about child properties).
    Similarly to _WRAP_PROPERTY, you must specify the property name and the
    wanted C++ type for the property. <command>gmmproc</command> uses the .defs
    file to discover the C type and the .m4 convert files to discover
    appropriate type conversions.</para>
<para lang="en"><function>_WRAP_CHILD_PROPERTY(C child property name, C++ type)</function></para>
<para lang="en">For instance, from <filename>notebook.hg</filename>:
<programlisting lang="en">
_WRAP_CHILD_PROPERTY("tab-expand", bool)
</programlisting>
</para>
</sect3>

</sect2>

<sect2 id="gmmproc-other-macros">
<title>Outros macros</title>
<sect3 id="gmmproc-implements-interface">
<title>_IMPLEMENTS_INTERFACE</title>
<para>Esta macro gera o código de inicialização para a interface.</para>
<para lang="en"><function>_IMPLEMENTS_INTERFACE(C++ interface name)</function></para>
<para lang="en">For instance, from <filename>button.hg</filename>:
<programlisting lang="en">
_IMPLEMENTS_INTERFACE(Activatable)
</programlisting>
</para>
<para lang="en">There is one optional extra argument:
<variablelist>
    <varlistentry>
        <term lang="en">ifdef</term>
        <listitem>
            <para lang="en">Puts the generated code in #ifdef blocks.</para>
        </listitem>
    </varlistentry>
</variablelist>
</para>
</sect3>

<sect3 id="gmmproc-wrap-enum">
<title>_WRAP_ENUM</title>
<para lang="en">This macro generates a C++ enum to wrap a C enum. You must specify the desired C++ name and
    the name of the underlying C enum.</para>
<para lang="en">For instance, from <filename>enums.hg</filename>:
<programlisting lang="en">
_WRAP_ENUM(WindowType, GtkWindowType)
</programlisting>
</para>
<para lang="en">If the enum is not a <classname>GType</classname>, you must pass a third parameter NO_GTYPE.
  This is the case when there is no <function>*_get_type()</function> function for the C enum, but
  be careful that you don't just need to include an extra header for that function. You should also
  file a bug against the C API, because all enums should be registered as GTypes.</para>
<para lang="en">For example, from <filename>icontheme.hg</filename>:
<programlisting lang="en">
_WRAP_ENUM(IconLookupFlags, GtkIconLookupFlags, NO_GTYPE)
</programlisting>
</para>
</sect3>

<sect3 id="gmmproc-wrap-enum-docs-only">
<title lang="en">_WRAP_ENUM_DOCS_ONLY</title>
<para lang="en">This macro just generates a Doxygen documentationn block for the enum.
  This is useful for enums that can't be wrapped with
  <function>_WRAP_ENUM()</function> because they are complexly defined (maybe
  using C macros) but including the generated enum documentation is still
  desired.  It is used with the same syntax as
  <function>_WRAP_ENUM()</function> and also process the same options (though
  NO_GTYPE is just ignored because it makes no difference when just generating
  the enum's documentation).
</para>
</sect3>

<sect3 id="gmmproc-wrap-gerror">
<title>_WRAP_GERROR</title>
<para lang="en">This macro generates a C++ exception class, derived from Glib::Error, with
a Code enum and a code() method. You must specify the desired C++ name, the name
of the corresponding C enum, and the prefix for the C enum values.</para>
<para lang="en">This exception can then be thrown by methods which are generated from _WRAP_METHOD() with the errthrow option.</para>
<para lang="en">For instance, from <filename>pixbuf.hg</filename>:
<programlisting lang="en">
_WRAP_GERROR(PixbufError, GdkPixbufError, GDK_PIXBUF_ERROR)
</programlisting>
</para>
</sect3>

<sect3 id="gmmproc-member-set-get">
    <title>_MEMBER_GET / _MEMBER_SET</title>
  <para lang="en">
    Use these macros if you're wrapping a simple struct or boxed type that provides
    direct access to its data members, to create getters and setters for the data members.
  </para>
  <para lang="en"><function>_MEMBER_GET(C++ name, C name, C++ type, C type)</function></para>
  <para lang="en"><function>_MEMBER_SET(C++ name, C name, C++ type, C type)</function></para>
  <para lang="en">
    For example, in <filename>rectangle.hg</filename>:
    <programlisting lang="en">_MEMBER_GET(x, x, int, int)</programlisting>
  </para>
</sect3>
<sect3 id="gmmproc-member-get-set-ptr">
  <title>_MEMBER_GET_PTR / _MEMBER_SET_PTR</title>
  <para>Usa essas macros para automaticamente fornecer os método getters e setters para um dado membro que é um tipo ponteiro. Para a função getter, ele irá criar dois métodos, um const e um não-const.</para>
  <para lang="en"><function>_MEMBER_GET_PTR(C++ name, C name, C++ type, C type)</function></para>
  <para lang="en"><function>_MEMBER_SET_PTR(C++ name, C name, C++ type, C type)</function></para>
  <para lang="en">For example, for <classname>Pango::Analysis</classname> in <filename>item.hg</filename>:
<programlisting lang="en">
// _MEMBER_GET_PTR(engine_lang, lang_engine, EngineLang*, PangoEngineLang*)
// It's just a comment. It's difficult to find a real-world example.
</programlisting>
  </para>
</sect3>
<sect3 id="gmmproc-member-get-set-gobject">
  <title>_MEMBER_GET_GOBJECT / _MEMBER_SET_GOBJECT</title>
  <para lang="en">
    Use these macros to provide getters and setters for a data member that is a
    <classname>GObject</classname> type that must be referenced before being
    returned.
  </para>
  <para lang="en"><function>_MEMBER_GET_GOBJECT(C++ name, C name, C++ type, C type)</function></para>
  <para lang="en"><function>_MEMBER_SET_GOBJECT(C++ name, C name, C++ type, C type)</function></para>
  <para lang="en">For example, in Pangomm, <filename>layoutline.hg</filename>:
<programlisting lang="en">
_MEMBER_GET_GOBJECT(layout, layout, Pango::Layout, PangoLayout*)
</programlisting>
  </para>
</sect3>
</sect2>

<sect2 id="gmmproc-parameter-processing">
  <title lang="en">gmmproc Parameter Processing</title>
  <para lang="en"><command>gmmproc</command> allows processing the parameters in a method
    signature for the macros that process method signatures (like
    <function>_WRAP_METHOD()</function>, <function>_WRAP_CTOR()</function> and
    <function>_WRAP_CREATE()</function>) in a variety of ways:
  </para>

  <sect3 id="gmmproc-parameter-reordering">
    <title lang="en">Parameter Reordering</title>
    <para lang="en">
      For all the macros that process method signatures, it is possible to
      specify a different order for the C++ parameters than the existing order
      in the C function, virtual function or signal.  For example, say that the
      following C function were being wrapped as a C++ method for the
      <classname>Gtk::Widget</classname> class:
      <programlisting lang="en">
        void gtk_widget_set_device_events(GtkWidget* widget, GdkDevice* device,
        GdkEventMask events);
      </programlisting>
      However, changing the order of the C++ method's two parameters is
      necessary.  Something like the following would wrap the function as a C++
      method with a different order for the two parameters:
      <programlisting lang="en">
        _WRAP_METHOD(void set_device_events(Gdk::EventMask events{events},
        const Glib::RefPtr&lt;const Gdk::Device&gt;&amp; device{device}),
        gtk_widget_set_device_events)
      </programlisting>
      The <literal>{c_param_name}</literal> following the method parameter
      names tells <command>gmmproc</command> to map the C++ parameter to the
      specified C parameter within the <literal>{}</literal>.  Since the C++
      parameter names correspond to the C ones, the above could be re-written
      as:
      <programlisting lang="en">
        _WRAP_METHOD(void set_device_events(Gdk::EventMask events{.}, const
        Glib::RefPtr&lt;const Gdk::Device&gt;&amp; device{.}),
        gtk_widget_set_device_events)
      </programlisting>
    </para>
    <warning>
      <para lang="en">
        Please note that when reordering parameters for a
        <function>_WRAP_SIGNAL()</function> method signature, the C parameter
        names would always be <literal>p0</literal>, <literal>p1</literal>,
        etc. because the <filename>generate_extra_defs</filename> utility uses those
        parameter names no matter what the C API's parameter names may be.
        It's how the utility is written presently.
      </para>
    </warning>
  </sect3>

  <sect3 id="gmmproc-optional-parameter-processing">
    <title lang="en">Optional Parameter Processing</title>
    <para lang="en">
      For all macros processing method signatures except
      <function>_WRAP_SIGNAL()</function> and
      <function>_WRAP_VFUNC()</function> it is also possible to make the
      parameters optional so that extra C++ methods are generated without the
      specified optional parameter.  For example, say that the following
      <function>*_new()</function> function were being wrapped as a constructor
      in the <classname>Gtk::ToolButton</classname> class:
      <programlisting lang="en">
        GtkToolItem* gtk_tool_button_new(GtkWidget* icon_widget, const gchar*
        label);
      </programlisting>
      Also, say that the C API allowed NULL for the function's
      <parameter>label</parameter> parameter so that that parameter is optional.
      It would be possible to have <command>gmmproc</command> generate the
      original constructor (with all the parameters) along with an additional
      constructor without that optional parameter by appending a
      <literal>{?}</literal> to the parameter name like so:
      <programlisting lang="en">
        _WRAP_CTOR(ToolButton(Widget&amp; icon_widget, const Glib::ustring&amp;
        label{?}), gtk_tool_button_new)
      </programlisting>
      In this case, two constructors would be generated: One with the optional
      parameter and one without it.
    </para>
  </sect3>

  <sect3 id="gmmproc-output-parameter-processing">
    <title lang="en">Output Parameter Processing</title>
    <para lang="en">
      With <function>_WRAP_METHOD()</function> it is also possible for the
      return of the wrapped C function (if it has one) to be placed in an
      output parameter of the C++ method instead of having the C++ method also
      return a value like the C function does.  To do that, simply include the
      output parameter in the C++ method parameter list appending a
      <literal>{OUT}</literal> to the output parameter name.  For example, if
      <function>gtk_widget_get_request_mode()</function> is declared as the
      following:
      <programlisting lang="en">
        GtkSizeRequestMode gtk_widget_get_request_mode(GtkWidget* widget);
      </programlisting>
      And having the C++ method set an output parameter is desired instead of
      returning a <type>SizeRequestMode</type>, something like the following
      could be used:
      <programlisting lang="en">
        _WRAP_METHOD(void get_request_mode(SizeRequestMode&amp; mode{OUT})
        const, gtk_widget_get_request_mode)
      </programlisting>
      The <literal>{OUT}</literal> appended to the name of the
      <parameter>mode</parameter> output parameter tells
      <command>gmmproc</command> to place the return of the C function in that
      output parameter.  In this case, however, a necessary initialization
      macro like the following would also have to be specified:
      <programlisting lang="en">
        _INITIALIZATION(`SizeRequestMode&amp;',`GtkSizeRequestMode',`$3 =
        (SizeRequestMode)($4)')
      </programlisting>
      Which could also be written as:
      <programlisting lang="en">
        _INITIALIZATION(`SizeRequestMode&amp;',`GtkSizeRequestMode',`$3 =
        ($1)($4)')
      </programlisting>
    </para>
    <para lang="en">
      <function>_WRAP_METHOD()</function> also supports setting C++ output
      parameters from C output parameters if the C function being wrapped has
      any.  Suppose, for example, that we want to wrap the following C function
      that returns a value in its C output parameter
      <parameter>rect</parameter>:
      <programlisting lang="en">
        gboolean gtk_icon_view_get_cell_rect(GtkIconView* icon_view,
        GtkTreePath* path, GtkCellRenderer* cell, GdkRectangle* rect);
      </programlisting>
      To have <command>gmmproc</command> place the value returned in the C++
      <parameter>rect</parameter> output parameter, something like the
      following <function>_WRAP_METHOD()</function> directive could be used:
      <programlisting lang="en">
        _WRAP_METHOD(bool get_cell_rect(const TreeModel::Path&amp; path, const
        CellRenderer&amp; cell, Gdk::Rectangle&amp; rect{&gt;&gt;}) const,
        gtk_icon_view_get_cell_rect)
      </programlisting>
      The <literal>{&gt;&gt;}</literal> following the <parameter>rect</parameter>
      parameter name indicates that the C++ output parameter should be set from
      the value returned in the C parameter from the C function.
      <command>gmmproc</command> will generate a declaration of a temporary
      variable in which to store the value of the C output parameter and a
      statement that sets the C++ output parameter from the temporary variable.
      In this case it may be necessary to have an
      <function>_INITIALIZATION()</function> describing how to set a
      <classname>Gdk::Rectangle&amp;</classname> from a
      <classname>GdkRectangle*</classname> such as the following:
      <programlisting lang="en">
        _INITIALIZATION(`Gdk::Rectangle&amp;',`GdkRectangle', `$3 =
        Glib::wrap(&amp;($4))')
      </programlisting>
    </para>
  </sect3>

</sect2>

<sect2 id="gmmproc-basic-types">
  <title>Tipos básicos</title>
  <para lang="en">Some of the basic types that are used in C APIs have better alternatives
    in C++. For example, there's no need for a <type>gboolean</type> type since
    C++ has <type>bool</type>. The following list shows some commonly-used
    types in C APIs and what you might convert them to in a C++ wrapper library.
  </para>
  <segmentedlist><title>Tipos básicos equivalentes</title>
    <?dbhtml list-presentation="table"?>
    <segtitle>Tipo C</segtitle>
    <segtitle>Tipo C++</segtitle>
    <seglistitem><seg lang="en"><type>gboolean</type></seg><seg lang="en"><type>bool</type></seg></seglistitem>
    <seglistitem><seg lang="en"><type>gint</type></seg><seg lang="en"><type>int</type></seg></seglistitem>
    <seglistitem><seg lang="en"><type>guint</type></seg><seg lang="en"><type>guint</type></seg></seglistitem>
    <seglistitem><seg lang="en"><type>gdouble</type></seg><seg lang="en"><type>double</type></seg></seglistitem>
    <seglistitem><seg lang="en"><type>gunichar</type></seg><seg lang="en"><type>gunichar</type></seg></seglistitem>
    <seglistitem><seg lang="en"><type>gchar*</type></seg><seg lang="en"><classname>Glib::ustring</classname> (or <classname>std::string</classname> for filenames)</seg></seglistitem>
  </segmentedlist>
</sect2>
</sect1>


<sect1 id="sec-wrapping-hand-coded-files">
<title lang="en">Hand-coded source files</title>
<para lang="en">You might want to include additional source files that will not be
  generated by <command>gmmproc</command> from <filename>.hg</filename> and
  <filename>.ccg</filename> files. You can simply place these in your
  <filename>libsomething/libsomethingmm</filename> directory and mention them
  in the <filename>Makefile.am</filename> in the
  <varname>files_extra_h</varname> and <varname>files_extra_cc</varname>
  variables.</para>
</sect1>

<sect1 id="sec-wrapping-initialization">
<title>Inicialização</title>
<para lang="en">Your library must be initialized before it can be used, to register the
    new types that it makes available. Also, the C library that you are wrapping
    might have its own initialization function that you should call. You can do
    this in an <function>init()</function> function that you can place in
    hand-coded <filename>init.h</filename> and <filename>init.cc</filename>
    files. This function should initialize your dependencies (such as the C
    function, and <application>gtkmm</application>) and call your generated
    <function>wrap_init()</function> function. For instance:
<programlisting lang="en">
void init()
{
  Gtk::Main::init_gtkmm_internals(); //Sets up the g type system and the Glib::wrap() table.
  wrap_init(); //Tells the Glib::wrap() table about the libsomethingmm classes.
}
</programlisting>
</para>
<para lang="en">The implementation of the <function>wrap_init()</function> method in
    <filename>wrap_init.cc</filename> is generated by
    <filename>generate_wrap_init.pl</filename>, but the declaration in
    <filename>wrap_init.h</filename> is hand-coded, so you will need to adjust
    <filename>wrap_init.h</filename> so that the <function>wrap_init()</function>
    function appears in the correct C++ namespace.</para>
</sect1>

<sect1 id="sec-wrapping-problems">
<title>Problemas na API C.</title>
<para lang="en">You are likely to encounter some problems in the library that you are wrapping, particularly if it is a new project. Here are some common problems, with solutions.</para>
<sect2 id="wrapping-predeclare-structs">
<title lang="en">Unable to predeclare structs</title>
<para lang="en">By convention, structs are declared in glib/GTK+-style headers like so:
<programlisting lang="en">
typedef struct _ExampleWidget ExampleWidget;

struct _ExampleWidget
{
  ...
};
</programlisting>
</para>
<para lang="en">The extra typedef allows the struct to be used in a header without including
  its full definition, simply by predeclaring it, by repeating that typedef.
  This means that you don't have to include the C library's header in your C++ header,
  thus keeping it out of your public API. <command>gmmproc</command> assumes that
  this technique was used, so you will see compiler errors if that is not the case.</para>
<para lang="en">
This compiler error might look like this:
<programlisting lang="en">
example-widget.h:56: error: using typedef-name 'ExampleWidget' after 'struct'
../../libexample/libexamplemm/example-widget.h:34: error: 'ExampleWidget' has a previous declaration here
make[4]: *** [example-widget.lo] Error 1
</programlisting>
or this:
<programlisting lang="en">
example-widget.h:60: error: '_ExampleWidget ExampleWidget' redeclared as different kind of symbol
../../libexample/libexamplemm/example-widget.h:34: error: previous declaration of 'typedef struct _ExampleWidget ExampleWidget'
</programlisting>
</para>
<para lang="en">This is easy to correct in the C library, so do send a patch to the relevant maintainer.</para>
</sect2>

<sect2 id="wrapping-no-properties">
<title>Falta de propriedades</title>
<para lang="en">By convention, glib/GTK+-style objects have <function>*_new()</function>
    functions, such as <function>example_widget_new()</function> that do nothing
    more than call <function>g_object_new()</function> and return the result.
    The input parameters are supplied to <function>g_object_new()</function>
    along with the names of the properties for which they are values. For
    instance,
<programlisting lang="en">
GtkWidget* example_widget_new(int something, const char* thing)
{
        return g_object_new (EXAMPLE_TYPE_WIDGET, "something", something, "thing", thing, NULL);
}
</programlisting>
</para>
<para lang="en">This allows language bindings to implement their own equivalents (such as
    C++ constructors), without using the <function>*_new()</function> function.
    This is often necessary so that they can actually instantiate a derived
    GType, to add their own hooks for signal handlers and vfuncs.</para>
<para lang="en">At the least, the <function>_new()</function> function should not use any
    private API (functions that are only in a .c file). Even when there are no
    functions, we can sometimes reimplement 2 or 3 lines of code in a
    <function>_new()</function> function as long as those lines of code use API
    that is available to us.</para>
<para lang="en">Another workaround is to add a <function>*_construct()</function> function
    that the C++ constructor can call after instantiating its own type. For
    instance,
<programlisting lang="en">
GtkWidget* example_widget_new(int something, const char* thing)
{
        ExampleWidget* widget;
        widget = g_object_new (EXAMPLE_TYPE_WIDGET, NULL);
        example_widget_construct(widget, "something", something, "thing", thing);
}

void example_widget_construct(ExampleWidget* widget, int something, const char* thing)
{
        //Do stuff that uses private API:
        widget-&gt;priv-&gt;thing = thing;
        do_something(something);
}
</programlisting>
</para>
<para lang="en">Adding properties, and ensuring that they interact properly with each
    other, is relatively difficult to correct in the C library, but it is
    possible, so do file a bug and try to send a patch to the relevant
    maintainer.</para>
</sect2>
</sect1>

<sect1 id="sec-wrapping-documentation">
<title>Documentação</title>
<para lang="en">In general, gtkmm-style projects use Doxygen, which reads specially formatted C++ comments and generates HTML documentation. You may write these doxygen comments directly in the header files.</para>

<sect2 id="wrapping-reusing-c-documentation">
<title>Reutilizando documentação C</title>
<para lang="en">You might wish to reuse documentation that exists for the C library that
  you are wrapping. GTK-style C libraries typically use gtk-doc and therefore
  have source code comments formatted for gtk-doc and some extra documentation
  in .sgml and .xml files. The docextract_to_xml.py script, from glibmm's
  <filename>tools/defs_gen</filename> directory, can read these files and
  generate an .xml file that <command>gmmproc</command> can use to generate
  doxygen comments. <command>gmmproc</command> will even try to transform the
  documentation to make it more appropriate for a C++ API.</para>
<para lang="en">
For instance,
<programlisting lang="en">./docextract_to_xml.py -s ~/checkout/gnome/gtk+/gtk/ &gt; gtk_docs.xml
</programlisting>
</para>
<para lang="en">Because this automatic transformation is not always appropriate, you might
    want to provide hand-written text for a particular method. You can do this
    by copying the XML node for the function from your
    <filename>something_docs.xml</filename> file to the
    <filename>something_docs_override.xml</filename> file and changing the
    contents.</para>
</sect2>

<sect2 id="wrapping-documentation-build-structure">
<title>Documentação da estrutura de construção</title>
<para lang="en">If you copied the skeleton source tree in mm-common and substituted the
  placeholder text, then you will already have suitable <filename>Makefile.am</filename>
  and <filename>Doxyfile.in</filename> files. With the mm-common build setup, the list
  of Doxygen input files is not defined in the Doxygen configuration file, but passed
  along from <command>make</command> to the standard input of <command>doxygen</command>.
  The input file list is defined by the <varname>doc_input</varname> variable in the
  <filename>Makefile.am</filename> file.
</para>
</sect2>

</sect1>

</appendix>

</book>
<!-- some vim settings
    vim:ts=2 sw=2 et
-->
