<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>pygtk &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/pygtk/</link>
	<description>Feed of posts on WordPress.com tagged "pygtk"</description>
	<pubDate>Mon, 13 Oct 2008 02:24:18 +0000</pubDate>

	<generator>http://wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Nuovo blog su Python e GTK]]></title>
<link>http://ubuntrucchi.wordpress.com/?p=845</link>
<pubDate>Sat, 11 Oct 2008 23:32:29 +0000</pubDate>
<dc:creator>Muflone</dc:creator>
<guid>http://ubuntrucchi.pl.wordpress.com/2008/10/12/nuovo-blog-su-python-e-gtk/</guid>
<description><![CDATA[Da un po&#8217; di tempo mi sono avvicinato alla programmazione mediante Python e GTK. Essendo il ma]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">Da un po' di tempo mi sono avvicinato alla programmazione mediante Python e GTK. Essendo il materiale informativo scarso ho deciso di raccogliere un po' di appunti in un nuovo blog, per dare una mano a chi si approccia al mondo PyGTK.</p>
<p style="text-align:justify;">L'indirizzo del nuovo blog PyGTK è <a title="PyGTK" href="http://pygtk.wordpress.com/" target="_blank">http://pygtk.wordpress.com/</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[how to install gtksourceview2 on windows]]></title>
<link>http://nilleb.wordpress.com/?p=67</link>
<pubDate>Wed, 08 Oct 2008 09:05:52 +0000</pubDate>
<dc:creator>Ivo</dc:creator>
<guid>http://nilleb.pl.wordpress.com/2008/10/08/how-to-install-gtksourceview2-on-windows/</guid>
<description><![CDATA[download and install all the following components:
gtk runtime installer (easier than take all the b]]></description>
<content:encoded><![CDATA[<p>download and install all the following components:</p>
<p>gtk runtime installer (easier than take all the binaries and put them together)<br />
<a href="http://sourceforge.net/projects/gtk-win/">http://sourceforge.net/projects/gtk-win/</a></p>
<p>gtksourceview2.4 binaries for win32<br />
<a href="http://ftp.gnome.org/pub/gnome/binaries/win32/gtksourceview/2.4/">http://ftp.gnome.org/pub/gnome/binaries/win32/gtksourceview/2.4/</a><br />
put them in the gtk runtime lib folder (or somewhere in your path)</p>
<p>pygtksourceview2 installer for win32<br />
<a href="http://ftp.gnome.org/pub/gnome/binaries/win32/pygtksourceview/">http://ftp.gnome.org/pub/gnome/binaries/win32/pygtksourceview/</a></p>
<p>libxml2, latest version binaries (really take the latest version)<br />
<a href="ftp://xmlsoft.org/libxml2/win32/">ftp://xmlsoft.org/libxml2/win32/</a><br />
put them in the gtk runtime lib folder (or somewhere in your path)</p>
<p>ok, now you can take the code in the previous post and execute it successfully.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[up-to-date sample code for gtksourceview2 (from the svn)]]></title>
<link>http://nilleb.wordpress.com/?p=65</link>
<pubDate>Wed, 08 Oct 2008 08:58:41 +0000</pubDate>
<dc:creator>Ivo</dc:creator>
<guid>http://nilleb.pl.wordpress.com/2008/10/08/up-to-date-code-for-gtksourceview-from-the-svn/</guid>
<description><![CDATA[#CREDITS
#http://www.progbox.co.uk/wordpress/?p=300
#DEPENDS: gtksourceview2 and libxml2
import gtk
]]></description>
<content:encoded><![CDATA[<p>#CREDITS<br />
#http://www.progbox.co.uk/wordpress/?p=300<br />
#DEPENDS: gtksourceview2 and libxml2</p>
<p>import gtk<br />
import gtksourceview2</p>
<p>win = gtk.Window()</p>
<p>bufferS = gtksourceview2.Buffer()<br />
manager = gtksourceview2.LanguageManager()<br />
language = manager.get_language("xml")<br />
#langS.set_mime_types(["text/x-python"])<br />
bufferS.set_language(language)<br />
bufferS.set_highlight_syntax(True)<br />
view = gtksourceview2.View(bufferS)<br />
view.set_show_line_numbers(True)<br />
win.resize(400,400)<br />
win.add(view)</p>
<p>win.show_all()<br />
gtk.main()</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[cpConverter: a code page converter for the Linux environment]]></title>
<link>http://gomputor.wordpress.com/?p=132</link>
<pubDate>Tue, 07 Oct 2008 19:39:12 +0000</pubDate>
<dc:creator>gomputor</dc:creator>
<guid>http://gomputor.pl.wordpress.com/2008/10/07/cpconverter-a-code-page-converter-for-the-linux-environment/</guid>
<description><![CDATA[cpConverter
cpConverter is a simple utility to change the code page of plain text based files (text ]]></description>
<content:encoded><![CDATA[[caption id="" align="aligncenter" width="444" caption="cpConverter"]<a href="http://gomputor.files.wordpress.com/2008/10/cpconverter.png" target="_blank"><img title="cpConverter" src="http://gomputor.files.wordpress.com/2008/10/cpconverter.png" alt="cpConverter" width="444" height="251" /></a>[/caption]
<p style="text-align:justify;">cpConverter is a simple utility to change the code page of plain text based files (text files, subtitle files, source code files etc.) aimed for the Linux gnome environment.</p>
<p style="text-align:justify;">You can convert to and from any of the 84 code pages the program supports (UTF, Latin 1, Greek, Japanese, Chinese, Russian, etc.)</p>
<p style="text-align:justify;">It supports multiple files selection, making a backup of your files before converting, and preview  of the files in a separate multitab window to check if you have selected the proper encoding.</p>
<p style="text-align:justify;">It is released under the Gnu GPL lisense, that means it is free software.</p>
<p style="text-align:justify;">For more info and download link, head to the program's page <a href="http://gomputor.wordpress.com/cpconverter/" target="_self">here</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[news from the SVN]]></title>
<link>http://nilleb.wordpress.com/?p=52</link>
<pubDate>Fri, 03 Oct 2008 14:24:35 +0000</pubDate>
<dc:creator>Ivo</dc:creator>
<guid>http://nilleb.pl.wordpress.com/2008/10/03/news-from-the-svn/</guid>
<description><![CDATA[this week&#8217;s edition of &#8220;news from the SVN&#8221; follows:
- XMLFinder: a graphical xpath]]></description>
<content:encoded><![CDATA[<p>this week's edition of "news from the SVN" follows:</p>
<p>- XMLFinder: a graphical xpath evaluator (PyGTK)<br />
- XMLFindTool and XMLTreeView: two classes which implement the Gino and XMLFinder cores; XMLFinder uses both the classes<br />
- something doesn't work in the CompressedFile class; under investigation</p>
<p>no binary distributions of these tools are provided, for now</p>
<p>notice: we have moved, once more. this blog is now available also on <a href="http://tec.nilleb.com">tec.nilleb.com</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[extASCee 0.5 is out]]></title>
<link>http://gomputor.wordpress.com/?p=117</link>
<pubDate>Thu, 02 Oct 2008 11:29:35 +0000</pubDate>
<dc:creator>gomputor</dc:creator>
<guid>http://gomputor.pl.wordpress.com/2008/10/02/extascee-05-is-out/</guid>
<description><![CDATA[extASCee (displayed ascii art by m0lo-)
extASCee is a simple ascii-art, .nfo file viewer for the Lin]]></description>
<content:encoded><![CDATA[[caption id="" align="aligncenter" width="442" caption="extASCee (displayed ascii art by m0lo-)"]<a href="http://gomputor.files.wordpress.com/2008/10/extascee.png" target="_blank"><img title="extascee" src="http://gomputor.files.wordpress.com/2008/10/extascee.png" alt="extASCee (displayed ascii art by m0lo-)" width="442" height="350" /></a>[/caption]
<p style="text-align:justify;"><strong>extASCee</strong> is a simple ascii-art, .nfo file viewer for the Linux gnome environment. With <strong>extASCee</strong> you can view  both  simple  and  high-ascii  art (no editing  though) and  the supported file formats are .txt, .nfo, .diz  and .asc<br />
Actually this is the first public release despite the '0.5' in the name. For more info and download link go to the program's page <a href="http://gomputor.wordpress.com/extascee/" target="_self">here</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[gtkBuild2Py 0.2 Released]]></title>
<link>http://gomputor.wordpress.com/?p=84</link>
<pubDate>Sun, 28 Sep 2008 16:05:03 +0000</pubDate>
<dc:creator>gomputor</dc:creator>
<guid>http://gomputor.pl.wordpress.com/2008/09/28/gtkbuild2py-02-released/</guid>
<description><![CDATA[I&#8217;ve just released version 0.2 of the gtkBuild2Py utility today. Nothing special to be found i]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">I've just released version 0.2 of the gtkBuild2Py utility today. Nothing special to be found in this release. Just a small bug fix and 2-3 improvements of the original code.</p>
<p style="text-align:justify;">If you are interested to find out about gtkBuild2Py and where to download it, just head to the program's page <a href="http://gomputor.wordpress.com/gtkbuild2py/" target="_self">here</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[gtkBuild2Py 0.1 Released]]></title>
<link>http://gomputor.wordpress.com/?p=51</link>
<pubDate>Wed, 24 Sep 2008 21:02:46 +0000</pubDate>
<dc:creator>gomputor</dc:creator>
<guid>http://gomputor.pl.wordpress.com/2008/09/25/gtkbuild2py-01-released/</guid>
<description><![CDATA[gtkBuild2Py is a small utility written by me that auto-generates python code from an .xml file creat]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">gtkBuild2Py is a small utility written by me that auto-generates python code from an .xml file created with GtkBuilder. It just parses that .xml file and generates python code that it's ready for you to use, with all your widgets and the signals inserted.</p>
<p style="text-align:justify;">gtkBuild2Py is released under the GNU GPL license, that means it is free software.</p>
[caption id="" align="aligncenter" width="436" caption="gtkBuild2Py"]<img title="gtkBuild2Py 0.1" src="http://gomputor.files.wordpress.com/2008/09/screenshot1.png" alt="gtkBuild2Py" width="436" height="233" />[/caption]
<p>For more info go to the program's page <a href="http://gomputor.wordpress.com/gtkbuild2py/" target="_self">here.</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[python: GUI; graphical user interface]]></title>
<link>http://pystart.wordpress.com/?p=7</link>
<pubDate>Tue, 23 Sep 2008 00:34:13 +0000</pubDate>
<dc:creator>root4is2</dc:creator>
<guid>http://pystart.pl.wordpress.com/2008/09/23/python-gui-graphical-user-interface/</guid>
<description><![CDATA[In the past I have used several types of python GUI libraries. I started with Tkinter - it&#8217;s a]]></description>
<content:encoded><![CDATA[<p>In the past I have used several types of python GUI libraries. I started with Tkinter - it's a good GUI, comes with the windows' version of python and is not very difficult to learn. Then after surfing online for some codes I was introduced to pyGTK (the python version of GTK+). It's scientifically better. In addition to beeing more powerful, more flexible, linux-compatible, it also looks very good. Anytime i'll be posting up some code with GUI, it will always be with pyGTK. So if you havent done so already, go learn it!</p>
<p>Some great online (easy to find, with a google search) tutorials are:</p>
<p><em>pyGTK 2.0 Tutorial by John Finlay</em></p>
<ul>
<li>http://www.pygtk.org/pygtk2tutorial/index.html</li>
</ul>
<p><em>And the pyGTK docs (mostly useful for widget references)</em></p>
<ul>
<li>http://www.pygtk.org/pygtk2tutorial/index.html</li>
</ul>
<p>:)</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[How to find if a specific font is installed in a user's system (with PyGtk)]]></title>
<link>http://gomputor.wordpress.com/?p=35</link>
<pubDate>Sun, 21 Sep 2008 20:49:13 +0000</pubDate>
<dc:creator>gomputor</dc:creator>
<guid>http://gomputor.pl.wordpress.com/2008/09/21/how-to-find-if-a-specific-font-is-installed-in-a-users-system-with-pygtk/</guid>
<description><![CDATA[As i wrote in my first post, after 10 years of working on Windows I recently switched to Linux and e]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">As i wrote in my first post, after 10 years of working on Windows I recently switched to Linux and especially Ubuntu ('working' is not the right word 'cause actually I don't work with a pc and I'm not a professional programmer, I learned programming by myself and for the fun of it. I just use my pc for fun, entertainment and to broaden my knowledge on various fields.)<br />
But I found myself that so far in Ubuntu I'm missing a lot of things from Windows. No, I don't miss Windows as an OS, not at all, but I do miss a lot of applications written for that specific OS (and I don't want to use <a href="http://www.winehq.org/" target="_blank">Wine</a> to run them in Ubuntu, I want native applications.)<br />
So, I found that Linux lacks a decent <a href="http://en.wikipedia.org/wiki/.nfo" target="_blank">.nfo</a> and <a href="http://en.wikipedia.org/wiki/ASCII_art" target="_blank">ascii art</a> viewer. Well I know that there is <a href="http://home.gna.org/nfoview/" target="_blank">NFO Viewer</a>, but you must download it first and then compile it and then install it. Ok, I did that, it's a very descent program, but I'm not fully satisfied with it. So what can I do? Write an <a href="http://en.wikipedia.org/wiki/.nfo" target="_blank">.nfo</a> viewer myself of course! Even for the fun of it and for learning a lot of things in the process, both for pyGtk and Linux (and Python.)<br />
So, I started. But I came across my first problem. That is, <a href="http://en.wikipedia.org/wiki/.nfo" target="_blank">.nfo</a> files and <a href="http://en.wikipedia.org/wiki/ASCII_art" target="_blank">ascii art</a> in general use codepage cp437 (or IBM437) for the encoding and in Windows to view it properly you must select the Terminal font in your application, a fixed-size font used in the Windows command line with special characters that an <a href="http://en.wikipedia.org/wiki/.nfo" target="_blank">.nfo</a> file use. But there isn't in Ubuntu a font that is close to the Windows Terminal font. All the native Ubuntu fixed-size fonts are way too far from the Windows one. I think the most close native font is <em>DejaVu Sans Mono</em>, but still it lacks a lot to view <a href="http://en.wikipedia.org/wiki/.nfo" target="_blank">.nfo</a> and <a href="http://en.wikipedia.org/wiki/ASCII_art" target="_blank">ascii art</a> properly.<br />
But I searched... and found at last the <a href="http://www.is-vn.bg/hamster/" target="_blank">Terminus</a> font. A font that I must say is almost identicall to the Windows one. But you must download it and install it if you wanna use it. And as far as regarding my program, I don't want to force the user to download it and install it (a hypothetical story of course, if I ever gonna release that program.)<br />
So back to code and to my problem, I wanted to check if the user has that specific font in his/her system and then load it. If I don't find it then set another font as the default one so as to keep the user close to see what <a href="http://en.wikipedia.org/wiki/ASCII_art" target="_blank">ascii art</a> is. And all of these because the default font that gtk+ and pango use is not a fixed-size one (I think it uses one from the <em>Sans </em>family).<br />
But how to check if the user has that font? I didn't know, so I started googling first and reading the docs, both pyGtk ones and Python. I posted also in a couple of forums my question. But I didn't get any answer. Something was missing. What was that? Well, the answer was simple after all, and it was lying inside the pango docs that I didn't read carefully at first. So I read it all over again and found the answer (and realized for once more that first I must read the docs carefully.)</p>
<p style="text-align:justify;">And here it is if you ever need to search for a specific font in the user's system and set it as the default for your application if found, or otherwise set a secondary as default:</p>
<p>[sourcecode language='python']</p>
<p># first you must import pango of course<br />
import pango</p>
<p># The get_pango_context() method returns the pango.Context with<br />
# the appropriate colormap, font description and base direction<br />
# for the selected widget (text_view in our case, assuming<br />
# text_view is your gtk.TextView)</p>
<p>context = text_view.get_pango_context()</p>
<p># list_families() returns a tuple containing a set of the fonts<br />
# that pango can use with the selected widget</p>
<p>fonts = context.list_families()</p>
<p># so we iterate in the font tuple<br />
for font in fonts:<br />
    # if our font is found (get_name returns a string)<br />
    if font.get_name() == 'Terminus':<br />
        # set that font for our text_view and break the loop<br />
        text_view.modify_font(pango.FontDescription('Terminus 8'))<br />
        break<br />
    else:<br />
        # else set our second choice font<br />
        text_view.modify_font(pango.FontDescription('DejaVu Sans Mono 8'))</p>
<p>[/sourcecode]</p>
<p>Pretty simple, isn't it?</p>
<p>Hope it'll help someone as it did to me.</p>
<p style="text-align:justify;">[PS: First I must apologize for the long, boring and tiring story just to present 9 lines of code and second I must apologize for my bad english. But you see, english is not my native language.]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Criando uma ListStore em Python]]></title>
<link>http://philss.wordpress.com/?p=44</link>
<pubDate>Sat, 20 Sep 2008 22:53:00 +0000</pubDate>
<dc:creator>Philip Sampaio</dc:creator>
<guid>http://philss.pl.wordpress.com/2008/09/20/criando-uma-liststore-em-python/</guid>
<description><![CDATA[Neste tutorial irei ensinar como criar uma ListStore em Python, utilizando o criador de interfaces G]]></description>
<content:encoded><![CDATA[<p>Neste tutorial irei ensinar como criar uma ListStore em Python, utilizando o criador de interfaces Glade e PyGTK.</p>
<p style="text-align:left;">Primeiro crie uma interface como esta:<br />
<a href="http://philss.wordpress.com/files/2008/09/captura_da_tela-9.png"><img class="size-full wp-image-45 aligncenter" title="Interface do programa ListStore_tuto" src="http://philss.wordpress.com/files/2008/09/captura_da_tela-9.png" alt="" width="510" height="248" /></a></p>
<p style="text-align:left;">Salve com o nome que você quiser(no meu exemplo, eu salvei como Exemplo1.glade).</p>
<p>Em seguida crie os sinais da interface:<br />
<a href="http://philss.wordpress.com/files/2008/09/captura_da_tela-111.png"><img class="alignnone size-full wp-image-48" title="Sinal da janela" src="http://philss.wordpress.com/files/2008/09/captura_da_tela-111.png" alt="" width="432" height="291" /></a><a href="http://philss.wordpress.com/files/2008/09/captura_da_tela-121.png"><img class="size-full wp-image-49 alignnone" style="padding-left:5px;" title="Sinal do botão adicionar" src="http://philss.wordpress.com/files/2008/09/captura_da_tela-121.png" alt="" width="369" height="195" /></a></p>
<p>Feito isso, abra seu editor/IDE e insira o código comentado:<br />
<!-- Trecho com o código do programa. Syntax HighLighting do site http://www.tohtml.com/python. --></p>
<pre style="background:#f6f8ff none repeat scroll 0 0;overflow:auto;width:500px;color:#000020;"><span style="color:#595979;">#!/usr/bin/env python</span>
<span style="color:#595979;">#-*- encoding: utf8 -*-</span>

<span style="color:#595979;">#Criação de uma liststore em Python, com PyGTK e Glade.</span>
<span style="color:#595979;">#Autor: Philip Sampaio</span>

<span style="font-weight:bold;color:#200080;">import</span> gtk
<span style="font-weight:bold;color:#200080;">import</span> gtk<span style="color:#308080;">.</span>glade
<span style="font-weight:bold;color:#200080;">import</span> pygtk

pygtk<span style="color:#308080;">.</span>require<span style="color:#308080;">(</span><span style="color:#1060b6;">"2.0"</span><span style="color:#308080;">)</span>

<span style="font-weight:bold;color:#200080;">class</span> ListStoreSimples<span style="color:#308080;">(</span>object<span style="color:#308080;">)</span><span style="color:#308080;">:</span>
    <span style="font-weight:bold;color:#200080;">def</span> <span style="color:#e34adc;">__init__</span><span style="color:#308080;">(</span>self<span style="color:#308080;">)</span><span style="color:#308080;">:</span>
        <span style="color:#595979;">#Função de início.. é a primeira a ser carregada</span>
        interface             <span style="color:#308080;">=</span>     gtk<span style="color:#308080;">.</span>glade<span style="color:#308080;">.</span>XML<span style="color:#308080;">(</span><span style="color:#1060b6;">"Exemplo1.glade"</span><span style="color:#308080;">)</span>
        self<span style="color:#308080;">.</span>winListStoreSimples    <span style="color:#308080;">=</span>    interface<span style="color:#308080;">.</span>get_widget<span style="color:#308080;">(</span><span style="color:#1060b6;">"winListStoreSimples"</span><span style="color:#308080;">)</span>
        self<span style="color:#308080;">.</span>entNome                <span style="color:#308080;">=</span>    interface<span style="color:#308080;">.</span>get_widget<span style="color:#308080;">(</span><span style="color:#1060b6;">"entNome"</span><span style="color:#308080;">)</span>
        self<span style="color:#308080;">.</span>entEmail            <span style="color:#308080;">=</span>    interface<span style="color:#308080;">.</span>get_widget<span style="color:#308080;">(</span><span style="color:#1060b6;">"entEmail"</span><span style="color:#308080;">)</span>
        self<span style="color:#308080;">.</span>trvListStore        <span style="color:#308080;">=</span>    interface<span style="color:#308080;">.</span>get_widget<span style="color:#308080;">(</span><span style="color:#1060b6;">"trvListStore"</span><span style="color:#308080;">)</span>

        <span style="color:#595979;">#Montando a ListStore(ou tabela, como quiser)</span>
        <span style="color:#595979;">#A linha abaixo diz cria um modelo de liststore com 2 colunas, ambas sendo strings</span>
        self<span style="color:#308080;">.</span>mdlListStore <span style="color:#308080;">=</span> gtk<span style="color:#308080;">.</span>ListStore<span style="color:#308080;">(</span> <span style="color:#e34adc;">str</span><span style="color:#308080;">,</span> <span style="color:#e34adc;">str</span><span style="color:#308080;">)</span>
        <span style="color:#595979;">#A linha abaixo configura o modelo da treeview com o modelo acima</span>
        self<span style="color:#308080;">.</span>trvListStore<span style="color:#308080;">.</span>set_model<span style="color:#308080;">(</span>self<span style="color:#308080;">.</span>mdlListStore<span style="color:#308080;">)</span>

        <span style="color:#595979;">#Colocando as colunas</span>
        colunaNome     <span style="color:#308080;">=</span> gtk<span style="color:#308080;">.</span>TreeViewColumn<span style="color:#308080;">(</span><span style="color:#1060b6;">"Nome"</span><span style="color:#308080;">,</span>gtk<span style="color:#308080;">.</span>CellRendererText<span style="color:#308080;">(</span><span style="color:#308080;">)</span><span style="color:#308080;">,</span> text<span style="color:#308080;">=</span><span style="color:#008c00;">0</span><span style="color:#308080;">)</span>
        colunaEmail    <span style="color:#308080;">=</span> gtk<span style="color:#308080;">.</span>TreeViewColumn<span style="color:#308080;">(</span><span style="color:#1060b6;">"Email"</span><span style="color:#308080;">,</span>gtk<span style="color:#308080;">.</span>CellRendererText<span style="color:#308080;">(</span><span style="color:#308080;">)</span><span style="color:#308080;">,</span> text<span style="color:#308080;">=</span><span style="color:#008c00;">1</span><span style="color:#308080;">)</span>
        <span style="color:#595979;">#Adiciona à nossa treeview (trvListStore)</span>
        self<span style="color:#308080;">.</span>trvListStore<span style="color:#308080;">.</span>append_column<span style="color:#308080;">(</span>colunaNome<span style="color:#308080;">)</span>
        self<span style="color:#308080;">.</span>trvListStore<span style="color:#308080;">.</span>append_column<span style="color:#308080;">(</span>colunaEmail<span style="color:#308080;">)</span>

        <span style="color:#595979;">#Dicionário de conexões</span>
        dic <span style="color:#308080;">=</span> <span style="color:#406080;">{</span>
            <span style="color:#1060b6;">'on_winListStoreSimples_destroy'</span> <span style="color:#308080;">:</span> <span style="color:#308080;">(</span> self<span style="color:#308080;">.</span>on_winListStoreSimples_destroy <span style="color:#308080;">)</span><span style="color:#308080;">,</span>
            <span style="color:#1060b6;">'on_btnAdicionar_clicked'</span>         <span style="color:#308080;">:</span> <span style="color:#308080;">(</span> self<span style="color:#308080;">.</span>on_btnAdicionar_clicked<span style="color:#308080;">)</span>
            <span style="color:#406080;">}</span>

        <span style="color:#595979;">#Conecta os sinais</span>
        interface<span style="color:#308080;">.</span>signal_autoconnect<span style="color:#308080;">(</span>dic<span style="color:#308080;">)</span>
    <span style="font-weight:bold;color:#200080;">def</span> main<span style="color:#308080;">(</span>self<span style="color:#308080;">)</span><span style="color:#308080;">:</span>
        <span style="color:#595979;">#Inicia o loop GTK</span>
        self<span style="color:#308080;">.</span>winListStoreSimples<span style="color:#308080;">.</span>show_all<span style="color:#308080;">(</span><span style="color:#308080;">)</span>
        gtk<span style="color:#308080;">.</span>main<span style="color:#308080;">(</span><span style="color:#308080;">)</span>

    <span style="font-weight:bold;color:#200080;">def</span> on_btnAdicionar_clicked<span style="color:#308080;">(</span>self<span style="color:#308080;">,</span>widget<span style="color:#308080;">)</span><span style="color:#308080;">:</span>
        <span style="color:#595979;">#Sinal de clique do btnAdicionar</span>
        nome     <span style="color:#308080;">=</span> self<span style="color:#308080;">.</span>entNome<span style="color:#308080;">.</span>get_text<span style="color:#308080;">(</span><span style="color:#308080;">)</span>
        email     <span style="color:#308080;">=</span> self<span style="color:#308080;">.</span>entEmail<span style="color:#308080;">.</span>get_text<span style="color:#308080;">(</span><span style="color:#308080;">)</span>
        <span style="color:#595979;">#Preste atenção: você irá adicionar os dados no MODELO</span>
        self<span style="color:#308080;">.</span>mdlListStore<span style="color:#308080;">.</span>append<span style="color:#308080;">(</span><span style="color:#308080;">[</span> nome<span style="color:#308080;">,</span> email<span style="color:#308080;">]</span><span style="color:#308080;">)</span>

        <span style="color:#595979;">#As linhas comentadas abaixo são de exemplo.</span>
        <span style="color:#595979;">"""info = [("Philip Sampaio","</span><span style="color:#7144c4;">philip.sampaio@gmail.com</span><span style="color:#595979;">"),</span>
<span style="color:#595979;">                ("Fulano"         ,"</span><span style="color:#7144c4;">fulano@gmail.com</span><span style="color:#595979;">"),</span>
<span style="color:#595979;">                ("Maria"         ,"</span><span style="color:#7144c4;">Maria@gmail.com</span><span style="color:#595979;">"),</span>
<span style="color:#595979;">                ("João"             ,"</span><span style="color:#7144c4;">Joao@gmail.com</span><span style="color:#595979;">")]</span>
<span style="color:#595979;">        for coluna in info:</span>
<span style="color:#595979;">            print coluna[0], coluna[1]</span>
<span style="color:#595979;">        """</span>
    <span style="font-weight:bold;color:#200080;">def</span> on_winListStoreSimples_destroy<span style="color:#308080;">(</span>self<span style="color:#308080;">,</span>widget<span style="color:#308080;">)</span><span style="color:#308080;">:</span>
        <span style="color:#595979;">#funcao para parar o loop gtk e encerrar o programa</span>
        self<span style="color:#308080;">.</span>winListStoreSimples<span style="color:#308080;">.</span>hide_all<span style="color:#308080;">(</span><span style="color:#308080;">)</span>
        gtk<span style="color:#308080;">.</span>main_quit<span style="color:#308080;">(</span><span style="color:#308080;">)</span>

<span style="font-weight:bold;color:#200080;">if</span> <span style="color:#e34adc;">__name__</span> <span style="color:#308080;">=</span><span style="color:#308080;">=</span> <span style="color:#1060b6;">'__main__'</span><span style="color:#308080;">:</span>
    teste <span style="color:#308080;">=</span> ListStoreSimples<span style="color:#308080;">(</span><span style="color:#308080;">)</span>
    teste<span style="color:#308080;">.</span>main<span style="color:#308080;">(</span><span style="color:#308080;">)</span></pre>
<p>O resultado deve ser algo como isto:<br />
<a href="http://philss.wordpress.com/files/2008/09/captura_da_tela-131.png"><img class="aligncenter size-full wp-image-50" title="Resultado" src="http://philss.wordpress.com/files/2008/09/captura_da_tela-131.png" alt="" width="351" height="247" /></a>Fácil, não?<br />
Teste e <span style="font-weight:bold;">estude o código</span>! Pergunte se precisar de ajuda!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Filesystem Changes Monitor (FSCM) 0.1]]></title>
<link>http://nilleb.wordpress.com/?p=48</link>
<pubDate>Fri, 19 Sep 2008 12:13:15 +0000</pubDate>
<dc:creator>Ivo</dc:creator>
<guid>http://nilleb.pl.wordpress.com/2008/09/19/filesystem-changes-monitor-fscm/</guid>
<description><![CDATA[The filesystem changes monitor (fscm) is a systray applet which allows you to inspect a set of files]]></description>
<content:encoded><![CDATA[<p>The filesystem changes monitor (fscm) is a systray applet which allows you to inspect a set of filesystem entities for changes. when any change is detected, it changes its appearance.<br />
it's the ideal companion for a quality assurance engineer who wants to be notified upon the creation of new memory dumps/exceptions stacks/logs updates/etc.</p>
<p>It has hit the svn yesterday. It's available for download from assembla.com. As usual, it is licensed under the GPL.</p>
<p>It uses icons found on the net (no license found for these icons), a systray icon code based on pywin32 (found on the net this too, no license as well), and pygtk. The watchdog code is mine, I haven't found anything suitable.</p>
<p><strong>Links:</strong></p>
<ul>
<li>etools project <a href="http://www.assembla.com/wiki/show/etools">§</a></li>
<li>fscm download page <a href="http://www.assembla.com/spaces/etools/documents/afYRTiHKqr3B0Gab7jnrAJ">§</a></li>
</ul>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Access F-Spot tags with Python and Gtk]]></title>
<link>http://chrysovalantis.wordpress.com/?p=109</link>
<pubDate>Wed, 17 Sep 2008 19:09:18 +0000</pubDate>
<dc:creator>chrysovalantis</dc:creator>
<guid>http://chrysovalantis.pl.wordpress.com/2008/09/17/access-f-spot-tags-with-python-and-gtk/</guid>
<description><![CDATA[
Recently I needed access to the F-Spot database in Python and since I could not find anything on th]]></description>
<content:encoded><![CDATA[<p><img class="alignleft" style="margin:5px;" src="http://farm4.static.flickr.com/3118/2865313563_7b779e88ae_o.png" alt="" width="125" height="340" /></p>
<p>Recently I needed access to the F-Spot database in Python and since I could not find anything on the internet, I decided to fire up Vim and started hacking the F-Spot database. If you are not familiar with F-Spot, F-Spot is the default GNOME Photo manager and it ships with your favourite Linux Distribution Ubuntu. The following PyGTK module FSpot.py provides an simple interface to the F-Spot database.</p>
<p>The module contains the class TagStore and FSpot. The class TagStore holds the F-Spot structure and the paths to your photos, while the FSpot class is used to read the F-Spot database, build the recursive TagStore structure and provide an gtk.TreeView widget in order to display the F-Spot tags. An sample application is also included, in order to test the module.</p>
<p>This is just an quick and dirty hack, thus it is not perfect and may contain errors or bugs.</p>
<p>[sourcecode language='python']<br />
#!/usr/bin/env python<br />
# FSpot.py</p>
<p># A Python F-Spot module</p>
<p># author: Chrys Emmanouilidis, www.chrysovalantis.wordpress.com<br />
# date: 17 September 2008</p>
<p>try:<br />
    import psyco<br />
    psyco.full()<br />
except ImportError:<br />
    pass</p>
<p>import sqlite3<br />
import os<br />
import sys<br />
import gtk<br />
import gobject</p>
<p>from base64 import *</p>
<p>class TagStore(object):<br />
    count = 0<br />
    level = ''<br />
    def __init__(self):<br />
        TagStore.count += 1<br />
        self.name = ''<br />
        self.icon = ''<br />
        self.photos = []<br />
        self.childs = []<br />
        self.curchild = -1</p>
<p>    def __add__(self, child):<br />
        if type(child) is not TagStore:<br />
            raise TypeError</p>
<p>        self.childs.append(child)</p>
<p>    def __iter__(self):<br />
        return self</p>
<p>    def next(self):<br />
        c = None</p>
<p>        if self.curchild == -1:<br />
            c = self<br />
        elif self.curchild < len(self.childs):<br />
            c = self.childs[self.curchild]<br />
        elif self.curchild >= len(self.childs):<br />
            self.curchild = -1<br />
            raise StopIteration</p>
<p>        self.curchild += 1</p>
<p>        return c</p>
<p>    def __str__(self):<br />
        str = '%s%s has %d photos' % (TagStore.level, self.name, len(self.photos))</p>
<p>        if self.childs is not None:<br />
            TagStore.level += '    '<br />
            for c in self.childs:<br />
                str += '%s\n%s' % (TagStore.level, c)<br />
            TagStore.level = TagStore.level[0:len(TagStore.level)-4]</p>
<p>        return str </p>
<p>class FSpot(object):<br />
    def __init__(self):<br />
        self.photosdb = '%s/.gnome2/f-spot/photos.db' % os.environ['HOME']<br />
        self.treeview_media_photos = gtk.TreeView()<br />
        self.icon_theme = gtk.icon_theme_get_default()</p>
<p>    def get_widget(self):<br />
        self.treeview_media_photos.set_model(self.__get_media_photos_model())<br />
        img_cell = gtk.CellRendererPixbuf()<br />
        text_cell = gtk.CellRendererText()</p>
<p>        column = gtk.TreeViewColumn()<br />
        column.pack_start(img_cell, False)<br />
        column.pack_start(text_cell,True)</p>
<p>        column.add_attribute(img_cell, "pixbuf",0)<br />
        column.add_attribute(text_cell, "text", 1)<br />
        column.set_attributes(text_cell, markup=1) </p>
<p>        self.treeview_media_photos.append_column(column)</p>
<p>        return self.treeview_media_photos</p>
<p>    def get_tagstore(self, category=0, tstore=None):<br />
        tstore = TagStore()<br />
        tstore.name  = 'F-Spot'<br />
        tstore.icon = pixbuf = self.icon_theme.load_icon('f-spot', 32, 0)<br />
        tstore.photos = self.__get_photos()<br />
        tstore.childs = self.__get_childs()</p>
<p>        return tstore</p>
<p>    def __get_media_photos_model(self):<br />
        model = gtk.TreeStore(gtk.gdk.Pixbuf, str, object)</p>
<p>        tagstore = self.get_tagstore()<br />
        parent = model.append(None, [tagstore.icon, tagstore.name, tagstore])</p>
<p>        for tag in tagstore.childs:<br />
            self.__append_tag_to_model(model, tag, parent)</p>
<p>        return model</p>
<p>    def __append_tag_to_model(self, model, tag, parent=None):<br />
        iter = model.append(parent, [tag.icon, tag.name, tag])<br />
        for c in tag.childs:<br />
            self.__append_tag_to_model(model, c, iter)</p>
<p>        return iter</p>
<p>    def __get_childs(self, category=0):<br />
        childs = []</p>
<p>        sql = 'SELECT id, name, icon, category_id FROM tags where category_id = %d' % int(category)<br />
        res = self.__execute_sql(sql)<br />
        icon_theme = gtk.icon_theme_get_default()</p>
<p>        for row in res:<br />
            child = TagStore()<br />
            child.name = row[1]</p>
<p>            pixbuf = None<br />
            try:<br />
                if "emblem" not in  row[2]:<br />
                    stream = b64decode(row[2])<br />
                    length = len(stream)</p>
<p>                    pixbuf = gtk.gdk.pixbuf_new_from_inline(length, stream, False)<br />
                else:<br />
                    name = row[2][11:]</p>
<p>                    try:<br />
                        pixbuf = self.icon_theme.load_icon(name, 32, 0)<br />
                    except gobject.GError, exc:<br />
                        pixbuf = gtk.gdk.pixbuf_new_from_file("/usr/share/f-spot/icons/hicolor/scalable/emblems/%s.svg" % name)</p>
<p>            except Exception, e:<br />
                pixbuf = icon_theme.load_icon('unknown', 32, 0)</p>
<p>            pixbuf = pixbuf.scale_simple(32, 32, gtk.gdk.INTERP_BILINEAR)<br />
            child.icon = pixbuf<br />
            child.photos = self.__get_photos(row[0])<br />
            child.childs = self.__get_childs(row[0])</p>
<p>            childs.append(child)</p>
<p>        return childs</p>
<p>    def __get_photos(self, tagid=None):<br />
        photos = []</p>
<p>        if tagid is None:<br />
            sql = 'SELECT p.uri FROM photo_tags AS pt JOIN photos AS p ON (p.id = pt.photo_id)'<br />
        else:<br />
            sql = 'SELECT p.uri FROM photo_tags AS pt JOIN photos AS p ON (p.id = pt.photo_id) WHERE pt.tag_id = %d' % int(tagid)</p>
<p>        photos = self.__execute_sql(sql)</p>
<p>        return photos</p>
<p>    def __execute_sql(self, sql):<br />
        results = []</p>
<p>        con = sqlite3.connect(self.photosdb)<br />
        cursor = con.cursor()<br />
        cursor.execute(sql)<br />
        results = [r for r in cursor]<br />
        con.close() </p>
<p>        return results</p>
<p>if __name__ == '__main__':<br />
    def OnDestroy(widget):<br />
        gtk.main_quit()</p>
<p>    app = gtk.Window(gtk.WINDOW_TOPLEVEL)<br />
    app.set_title("PyGTK FSpot")</p>
<p>    fspot = FSpot()</p>
<p>    scroll = gtk.ScrolledWindow()<br />
    scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)<br />
    scroll.add(fspot.get_widget())</p>
<p>    app.add(scroll)<br />
    app.connect("destroy", OnDestroy)</p>
<p>    app.show_all()<br />
    gtk.main()<br />
    sys.exit(0)<br />
[/sourcecode]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Gestore stampanti alternativo in pygtk!]]></title>
<link>http://adrinux.wordpress.com/?p=320</link>
<pubDate>Wed, 17 Sep 2008 16:54:25 +0000</pubDate>
<dc:creator>adriano</dc:creator>
<guid>http://adrinux.pl.wordpress.com/2008/09/17/gestore-stampanti-alternativo-in-pygtk/</guid>
<description><![CDATA[Per coloro che come me utilizzano un Windows Manager e vogliono evitare le dipendenze di Gnome, oggi]]></description>
<content:encoded><![CDATA[<p>Per coloro che come me utilizzano un Windows Manager e vogliono evitare le dipendenze di Gnome, oggi vi presento <strong>system-config-printer</strong>, un software programmato in pygtk che si integra perfettamente con un desktop gtk ed è una valida alternativa a Gnome Cups Manager, il gestore di stampanti di Gnome. Ha un'interfaccia molto intuitiva, permette l'autorilevazione del dispositivo di stampa, la scelta e l'installazione del driver, nonchè il settaggio di una serie di opzioni utili. Provatelo!</p>
<blockquote><p><em>Archlinux: sudo pacman -S system-config-printer<br />
Debian: sudo apt-get install system-config-printer</em></p></blockquote>
<p>Per avviarlo basta digitare da terminale, da root <em>system-config-printer</em><br />
<em></em></p>
<p><em></p>
[caption id="attachment_321" align="aligncenter" width="300" caption="System Config Printer"]<a href="http://adrinux.files.wordpress.com/2008/09/mc2300-ss01.png"><img class="size-medium wp-image-321" title="mc2300-ss01" src="http://adrinux.wordpress.com/files/2008/09/mc2300-ss01.png?w=300" alt="System Config Printer" width="300" height="197" /></a>[/caption]
<p></em></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Programming with Python]]></title>
<link>http://fluteflute.wordpress.com/?p=11</link>
<pubDate>Mon, 08 Sep 2008 18:21:02 +0000</pubDate>
<dc:creator>fluteflute</dc:creator>
<guid>http://fluteflute.pl.wordpress.com/2008/09/08/programming-with-python/</guid>
<description><![CDATA[I&#8217;ve always had an interest in programming. I started with PHP, because prior to that I had le]]></description>
<content:encoded><![CDATA[<p>I've always had an interest in programming. I started with PHP, because prior to that I had learnt HTML. Also this was back in 'the Windows days' so I would upload my work to a free web host without the effort of having to download and install a program to compile and then run my code. Of course finding a decent free webhost was never easy!</p>
<p>Anyway, PHP (with MySQL as a database) is great for developing websites. However it is not widly used for developing desktop applications - and thats what I decided I wanted to have a go at.</p>
<p>Enter <a href="http://en.wikipedia.org/wiki/Python_(programming_language)">Python</a>. It does not require compiling (similar to PHP); allows for object orientated programming (something I hear is the future); has an unusual clean syntax {no more curly braces} and seems to be very popular for linux desktop programming.</p>
<p>So, I installed it (<em>aptitude install python</em> - although you'll probably find it's installed already on your machine).</p>
<p>The best thing I've found about it, is that you are able to use the libraries available for it. In particular <a href="http://www.pygtk.org/">PyGTK</a> (for Gnome/GTK style programs) and <a href="http://en.wikipedia.org/wiki/GStreamer">GStreamer</a> (for sound output - as used by Rhythmbox, Banshee, Totem, etc). </p>
<p>So to help me learn python I'm creating a media player. I have some ideas which are rather different to the current media players available, so watch out! Currently it does very little (I mean practically nothing), but it's being a great learning experience for me. Perhaps I'll even post a few tutorials here!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Custom Python timer using GObject]]></title>
<link>http://chrysovalantis.wordpress.com/?p=87</link>
<pubDate>Thu, 04 Sep 2008 17:42:49 +0000</pubDate>
<dc:creator>chrysovalantis</dc:creator>
<guid>http://chrysovalantis.pl.wordpress.com/2008/09/04/pygtk-timer-class/</guid>
<description><![CDATA[The following Python module timer.py is a simple implementation for a timer by sub-classing GObject.]]></description>
<content:encoded><![CDATA[<p>The following Python module timer.py is a simple implementation for a timer by sub-classing GObject. You can use this timer for any time depending task, e.g. a clock widget like the famous <a href="http://www.pygtk.org/articles/cairo-pygtk-widgets/cairo-pygtk-widgets.htm">cairo clock</a>.</p>
<p>[sourcecode language='python']<br />
#!/usr/bin/env python<br />
# timer.py</p>
<p>#Python timer implementation</p>
<p># author: Chrys Emmanouilidis, www.chrysovalantis.wordpress.com<br />
# date: 04 September 2008</p>
<p>import gobject</p>
<p>class Timer(gobject.GObject):<br />
    #define a custom signal<br />
    __gsignals__ = dict(tick=(gobject.SIGNAL_RUN_FIRST,<br />
        gobject.TYPE_NONE, (gobject.TYPE_INT,)))</p>
<p>    def __init__(self):<br />
        super(Timer, self).__init__()<br />
        self.__interval = 1000<br />
        self.__timer_id = None<br />
        self.__tick = 0</p>
<p>    def start(self):<br />
        self.__tick = 0<br />
        self.__timer_id = gobject.timeout_add(self.__interval, self.__update)</p>
<p>    def stop(self):<br />
        gobject.source_remove(self.__timer_id)<br />
        self.__timer_id = None<br />
        self.__tick = 0</p>
<p>    def __get_interval(self):<br />
        return self.__interval</p>
<p>    def __set_interval(self, value):<br />
        try:<br />
            self.__interval = int(value)<br />
        except:<br />
            pass<br />
    interval = property(__get_interval, __set_interval)</p>
<p>    def __get_tick(self):<br />
        return self.__tick<br />
    tick = property(__get_tick, None)</p>
<p>    def __update(self):<br />
        self.__tick += 1<br />
        tick_again = False</p>
<p>        if self.__timer_id is not None:<br />
            self.emit('tick', self.__tick)<br />
            tick_again = True</p>
<p>        return tick_again</p>
<p>#Test the Timer class<br />
if __name__ == '__main__':<br />
    import gtk<br />
    import signal</p>
<p>    #^C exits the application<br />
    signal.signal(signal.SIGINT, signal.SIG_DFL) </p>
<p>    def OnTick(sender, args):<br />
        print args<br />
        if int(args) >= 10:<br />
            sender.stop()<br />
            gtk.main_quit()</p>
<p>    timer = Timer()<br />
    timer.interval = 500</p>
<p>    timer.connect('tick', OnTick)</p>
<p>    timer.start()<br />
    gtk.main()<br />
[/sourcecode]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Gino 0.2]]></title>
<link>http://nilleb.wordpress.com/?p=41</link>
<pubDate>Fri, 29 Aug 2008 15:46:16 +0000</pubDate>
<dc:creator>Ivo</dc:creator>
<guid>http://nilleb.pl.wordpress.com/2008/08/29/gino-02/</guid>
<description><![CDATA[Gino 0.2 has hit the SVN. (What&#8217;s Gino? http://www.assembla.com/wiki/show/etools/Gino)
It is d]]></description>
<content:encoded><![CDATA[<p>Gino 0.2 has hit the SVN. (What's Gino? <a href="http://www.assembla.com/wiki/show/etools/Gino">http://www.assembla.com/wiki/show/etools/Gino</a>)<br />
It is delivered with a nice setup.py. With the help of py2exe, it is possible to make it a windows binary, easily portable.<br />
The next steps? fix some(many) bugs, and prepare a Inno setup to deploy it.</p>
<p>If you want to try it, you can get the sources from assembla.com (http://svn2.assembla.com/svn/etools). (What are the etools? <a href="http://www.assembla.com/wiki/show/etools/Gino">http://www.assembla.com/wiki/show/etools/Gino</a>).</p>
<p>This project has been written with eclipse and pydev extensions. It isn't clear which kind of license it will use, yet.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Fun with BSNL Modem and SNMP]]></title>
<link>http://balajirrao.wordpress.com/?p=61</link>
<pubDate>Sat, 16 Aug 2008 02:29:05 +0000</pubDate>
<dc:creator>balajirrao</dc:creator>
<guid>http://balajirrao.pl.wordpress.com/2008/08/16/snmp-fun/</guid>
<description><![CDATA[When surfing my ADSL modem&#8217;s web console, I came across a page on SNMP daemon, which read
Simp]]></description>
<content:encoded><![CDATA[<p>When surfing my ADSL modem's web console, I came across a page on SNMP daemon, which read</p>
<blockquote><p>Simple Network Management Protocol (SNMP) allows a management application to              retrieve statistics and status from the SNMP agent in this device.</p></blockquote>
[caption id="attachment_62" align="alignnone" width="544" caption="ADSL Router - SNMP Agent"]<a href="http://balajirrao.wordpress.com/files/2008/08/screenshot-dsl-router-mozilla-firefox.png"><img class="size-full wp-image-62" src="http://balajirrao.wordpress.com/files/2008/08/screenshot-dsl-router-mozilla-firefox.png" alt="ADSL Router - SNMP Agent" width="544" height="519" /></a>[/caption]
<p>Immediately the phrase "allows a management application to              retrieve statistics" caught my attention. "How about a nice GNOME panel applet that reports the unaccounted statistics dirrectly from the browser ?" - I thought.. Sounds exciting for sure. I decided to do it.</p>
<p>The first step is to read about SNMP. I began searching for a book, and finally got one linux administration book in my hand which seemed to have a couple of pages long description about SNMP, but I skimmed through them quickly, as I wanted a quick and dirty solution!.</p>
<p>I figured out that I need to install net-smp packages and did a yum install. I god a utility called tkmib which  is GUI for net-snmp.</p>
<p><a href="http://balajirrao.wordpress.com/files/2008/08/screenshot-tkmib.png"><img class="alignnone size-full wp-image-63" src="http://balajirrao.wordpress.com/files/2008/08/screenshot-tkmib.png" alt="" width="544" height="603" /></a></p>
<p>I figured out from the list below that the interface I am interested in is No.5, as shown from .iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifDescr.5 = br0</p>
<p>I now decieded to hack up a shell script that prints the unaccounted usage accounted in the router.</p>
<pre>#!/bin/bash
out=`snmpget -v1 -c public  modem interfaces.ifTable.ifEntry.ifOutOctets.5 -Oq &#124; cut -d " " -f 2`
in=`snmpget -v1 -c public  modem interfaces.ifTable.ifEntry.ifInOctets.5 -Oq &#124; cut -d " " -f 2`
tot1=`expr \( $in + $out \)`
out=`snmpget -v1 -c public  modem interfaces.ifTable.ifEntry.ifOutOctets.3 -Oq &#124; cut -d " " -f 2`
in=`snmpget -v1 -c public  modem interfaces.ifTable.ifEntry.ifInOctets.3 -Oq &#124; cut -d " " -f 2`
tot2=`expr \( $in + $out \)`
echo -e "Ashwin : \t" $tot2 "MB"
tot=`expr $tot1 - $tot2`
echo -e "Balaji : \t" $tot "MB"
echo -e "Total : \t" $tot1 "MB"</pre>
<p>It worked very well. Now, how about writing a gnome applet to display the utilization in real time ?  Here's how I did it.</p>
<p>[sourcecode language='python']<br />
#!/usr/bin/env python</p>
<p>import pygtk<br />
pygtk.require('2.0' )</p>
<p>import gtk<br />
import gnomeapplet<br />
import time<br />
from pysnmp import role, v1, asn1<br />
from fpformat import fix<br />
from string import Template<br />
import gobject</p>
<p>tr = role.manager(('modem', 161))</p>
<p>req = v1.GETREQUEST()<br />
rsp = v1.GETRESPONSE()</p>
<p>msg = Template(' Ashwin = $ash Balaji = $bal' )</p>
<p>class ModemApplet(gnomeapplet.Applet):</p>
<p>lbl = None<br />
def __init__ (self, applet, iid):<br />
self.lbl = gtk.Label("Please Wait.." )<br />
applet.add(self.lbl)<br />
xx = gobject.timeout_add(10000, self.update)<br />
applet.show_all()</p>
<p>def update (self):<br />
req['encoded_oids'] = [ asn1.OBJECTID().encode('1.3.6.1.2.1.2.2.1.10.5' ) ]<br />
(rawrsp, src) = tr.send_and_receive(req.encode())<br />
rsp.decode(rawrsp)<br />
vals = map(lambda x: x[0](), map(asn1.decode, rsp['encoded_vals']))<br />
ino = vals[0]</p>
<p>req['encoded_oids'] = [ asn1.OBJECTID().encode('1.3.6.1.2.1.2.2.1.16.5 ' ) ]<br />
(rawrsp, src) = tr.send_and_receive(req.encode())<br />
rsp.decode(rawrsp)<br />
vals = map(lambda x: x[0](), map(asn1.decode, rsp['encoded_vals ']))<br />
outo = vals[0]<br />
wan_tot = (ino + outo) / (1024.0 * 1024.0)</p>
<p>req['encoded_oids'] = [ asn1.OBJECTID().encode('1.3.6.1.2.1.2.2.1.10.3' ) ]<br />
(rawrsp, src) = tr.send_and_receive(req.encode())<br />
rsp.decode(rawrsp)<br />
vals = map(lambda x: x[0](), map(asn1.decode, rsp['encoded_vals']))<br />
ino = vals[0]<br />
req['encoded_oids'] = [ asn1.OBJECTID().encode('1.3.6.1.2.1.2.2.1.16.3' ) ]<br />
(rawrsp, src) = tr.send_and_receive(req.encode())<br />
rsp.decode(rawrsp)<br />
vals = map(lambda x: x[0](), map(asn1.decode, rsp['encoded_vals' ]))</p>
<p>outo = vals[0]<br />
wlan_tot = (ino + outo) / (1024.0 * 1024.0)<br />
self.lbl.set_label(msg.substitute(ash = str(fix(wlan_tot, 3)), bal = str(fix(wan_tot - wlan_tot, 3))))<br />
return True</p>
<p>def modem_factory(applet, iid):<br />
ModemApplet(applet, iid);<br />
return gtk.TRUE</p>
<p>gobject.type_register(ModemApplet)</p>
<p>if __name__ == '__main__':<br />
gnomeapplet.bonobo_factory("OAFIID:GNOME_ModemSNMP_Factory", ModemApplet.__gtype__, "modem", "1", modem_factory)<br />
[/sourcecode]</p>
<p>Its now a applet at the top. Doesn't it look cool ? :)<br />
<a href="http://balajirrao.wordpress.com/files/2008/08/snap1.jpeg"><img class="alignnone size-full wp-image-75" src="http://balajirrao.wordpress.com/files/2008/08/snap1.jpeg" alt="" width="544" height="77" /></a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Threads com PyGTK]]></title>
<link>http://medeubranco.wordpress.com/?p=64</link>
<pubDate>Thu, 17 Jul 2008 03:39:04 +0000</pubDate>
<dc:creator>medeubranco</dc:creator>
<guid>http://medeubranco.pl.wordpress.com/2008/07/17/threads-com-pygtk/</guid>
<description><![CDATA[Já falei um pouco de thread em python; agora vamos falar de threads com pygtk.
Como uma introduçã]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">Já falei um pouco de thread em python; agora vamos falar de threads com pygtk.</p>
<p style="text-align:justify;">Como uma introdução, analise o código abaixo. Veja se lhe parece correto.</p>
<p>[sourcecode language='python']</p>
<p>#! /usr/bin/env python<br />
# -.- coding: utf-8 -.-<br />
import gtk<br />
import pygtk</p>
<p>continua=None<br />
def iniciar(botao, texto):<br />
    global continua<br />
    continua=True<br />
    x=0<br />
    while continua:<br />
        texto.set_text(str(x))<br />
        x+=1</p>
<p>def parar(botao):<br />
    global continua<br />
    continua=False</p>
<p># criando os componentes<br />
win=gtk.Window()<br />
box=gtk.VBox()<br />
texto=gtk.Entry()<br />
btinicia=gtk.Button("iniciar" )<br />
btpara=gtk.Button("interromper" )</p>
<p># ativando os eventos<br />
btinicia.connect("clicked", iniciar, texto)<br />
btpara.connect("clicked", parar)<br />
win.connect("destroy",gtk.main_quit)</p>
<p># encaixotando tudo<br />
box.pack_start(texto)<br />
box.pack_start(btinicia)<br />
box.pack_start(btpara)<br />
win.add(box)</p>
<p># exibindo tudo<br />
win.show_all()</p>
<p># iniciando o loop principal do GTK<br />
gtk.main()</p>
<p>[/sourcecode]</p>
<p style="text-align:justify;">O que deveria acontecer ao executar esse código? Uma janela com uma caixa de texto, um botão "iniciar" e um botão "interromper".</p>
<p style="text-align:justify;">Clicando no "iniciar", um loop inicia e começa a mudar o conteúdo da caixa de texto para "1", "2" e assim por diante até que se clique em "interromper".</p>
<p style="text-align:justify;">Se quiser executar o código, fique à vontade. Mas vou adiantar aqui que isso não vai dar certo. Ao clicar em "iniciar", o controle do programa passa para o loop sem fim, e você nem vê a caixa de texto sendo atualizada e nem consegue mais clicar no botão "interromper". Simplesmente seu programa pára de responder.</p>
<p style="text-align:justify;"><!--more-->Para que o programa funcione como esperado, é necessário criar uma thread onde será executada a função iniciar. A função então vai rodar em paralelo, e você assume de novo  o controle do programa.</p>
<p style="text-align:justify;"><span style="color:#ff0000;">************</span></p>
<p style="text-align:justify;">Atualização!</p>
<p style="text-align:justify;">Conforme o comentário do <a href="http://matias.archlinux-br.org/">thotypous</a>, é possível fazer esse código funcionar mesmo sem threads.</p>
<p style="text-align:justify;">Basta usar <code>while gtk.events_pending():gtk.main_iteration() </code> dentro do loop:</p>
<p style="text-align:justify;">
<p>[sourcecode language='python']</p>
<p>    while continua:<br />
        while gtk.events_pending():gtk.main_iteration()<br />
        texto.set_text(str(x))<br />
        x+=1<br />
[/sourcecode]</p>
<p style="text-align:justify;">Como o objetivo deste artigo é mostrar o uso de threads com pygtk, vamos tocar o barco.</p>
<p style="text-align:justify;"><span style="color:#ff0000;">************</span></p>
<p style="text-align:justify;">
<p style="text-align:justify;">Para utilizar threads em pygtk, além do que já aprendeu sobre threads  você vai ter que lembrar de duas coisinhas:</p>
<ul>
<li>iniciar threads do gtk com <a href="http://www.pygtk.org/docs/pygtk/gdk-functions.html#function-gdk--threads-init">gtk.gdk.threads_init</a></li>
<li>usar <a href="http://www.pygtk.org/docs/pygobject/gobject-functions.html#function-gobject--idle-add">gobject.idle_add</a> para permitir que códigos externos ao gtk.main_loop  possam modificar sua interface em pygtk.</li>
</ul>
<p><em>( referência: <a href="http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html">Using threads in PyGTK</a> )</em></p>
<p style="text-align:justify;">A função <code class="function">gobject.idle_add</code>( <em class="parameter"><code>callback, [argumentos para callback] </code></em>) adiciona uma função (especificada por <em class="parameter"><code>callback</code></em>) a ser chamada sempre que não houver eventos de prioridade mais alta para o main loop. Os argumentos para a função  <em class="parameter"><code>callback </code></em>são passados como argumentos adicionais de gobject.idle_add(). <em>(livre tradução da definição em <a href="http://www.pygtk.org/docs/pygobject/gobject-functions.html#function-gobject--idle-add">gobject.idle_add</a> )</em></p>
<p style="text-align:justify;">Vamos ver então como fazer o código apresentado lá em cima funcionar direito:</p>
<p>[sourcecode language='python']</p>
<p>from threading import Thread<br />
import time<br />
import gtk, gobject<br />
gtk.gdk.threads_init()<br />
a_thread=None</p>
<p>def iniciar(botao, texto):<br />
    global a_thread<br />
    #iniciando a thread<br />
    a_thread=Thread(target=nosso_loop, args=(texto,botao))<br />
    a_thread.morta=False<br />
    a_thread.start()</p>
<p>def nosso_loop(texto, botao):<br />
    # desabilitando o botao "iniciar"<br />
    # para que o usuario nao possa<br />
    # iniciar novas threads enquanto<br />
    # esta continuar<br />
    botao.set_sensitive(0)</p>
<p>    z=0<br />
    while not a_thread.morta:<br />
        z+=1<br />
        # chamando a funcao atualiza_texto<br />
        # com o idle_add<br />
        gobject.idle_add(atualiza_texto,texto, z)</p>
<p>        time.sleep(0.00001)<br />
    # o loop terminou<br />
    # o botao vai poder agora<br />
    # ser clicado de no:vo<br />
    botao.set_sensitive(1)</p>
<p>def atualiza_texto(texto, valor):<br />
    texto.set_text(str(valor))</p>
<p>def interromper(botao=None):<br />
    a_thread.morta=True</p>
<p>def sair(win):<br />
    interromper()<br />
    gtk.main_quit()</p>
<p>#criando os componentes<br />
win=gtk.Window()<br />
box=gtk.VBox()<br />
texto=gtk.Entry()<br />
botao=gtk.Button("iniciar" )<br />
btmata=gtk.Button("interromper" )</p>
<p>#ativando os eventos<br />
botao.connect("clicked", iniciar, texto)<br />
btmata.connect("clicked", interromper)<br />
win.connect("destroy",sair)</p>
<p>#encaixotando tudo<br />
box.pack_start(texto)<br />
box.pack_start(botao)<br />
box.pack_start(btmata)<br />
win.add(box)</p>
<p>#exibindo tudo<br />
win.show_all()</p>
<p>#iniciando o loop principal do GTK<br />
gtk.main()<br />
[/sourcecode]</p>
<p align="justify">Incluimos a thread neste código. A função "iniciar()" agora simplesmente inicia a thread. O loop infinito foi transferido para a função "nosso_loop()", que será executada pela thread.</p>
<p align="justify">A atualização da caixa de texto foi transferida para  a função "atualiza_texto()", que é executada com "gobject.idle_Add()".</p>
<p align="justify">Pode executar este código. Vai funcionar.</p>
<p align="justify">
]]></content:encoded>
</item>
<item>
<title><![CDATA[PyGtk text entry dialog]]></title>
<link>http://ardoris.wordpress.com/?p=16</link>
<pubDate>Sat, 05 Jul 2008 20:23:44 +0000</pubDate>
<dc:creator>jebavarde</dc:creator>
<guid>http://ardoris.pl.wordpress.com/2008/07/05/pygtk-text-entry-dialog/</guid>
<description><![CDATA[PyGtk doesn&#8217;t come with a pre-made prompt-for-a-string dialog, so I rolled my own.
Text entry ]]></description>
<content:encoded><![CDATA[<p>PyGtk doesn't come with a pre-made prompt-for-a-string dialog, so I rolled my own.</p>
[wp_caption id="attachment_17" align="alignnone" width="382" caption="Text entry dialog"]<a href="http://ardoris.files.wordpress.com/2008/07/dialog.png"><img src="http://ardoris.wordpress.com/files/2008/07/dialog.png" alt="Text entry dialog" width="382" height="173" class="size-full wp-image-17" /></a>[/wp_caption]
<p>The code follows:<br />
<!--more--><br />
[sourcecode language='python']<br />
#!/usr/bin/env python<br />
import gtk<br />
def responseToDialog(entry, dialog, response):<br />
	dialog.response(response)<br />
def getText():<br />
	#base this on a message dialog<br />
	dialog = gtk.MessageDialog(<br />
		None,<br />
		gtk.DIALOG_MODAL &#124; gtk.DIALOG_DESTROY_WITH_PARENT,<br />
		gtk.MESSAGE_QUESTION,<br />
		gtk.BUTTONS_OK,<br />
		None)<br />
	dialog.set_markup('Please enter your <b>name</b>:')<br />
	#create the text input field<br />
	entry = gtk.Entry()<br />
	#allow the user to press enter to do ok<br />
	entry.connect("activate", responseToDialog, dialog, gtk.RESPONSE_OK)<br />
	#create a horizontal box to pack the entry and a label<br />
	hbox = gtk.HBox()<br />
	hbox.pack_start(gtk.Label("Name:"), False, 5, 5)<br />
	hbox.pack_end(entry)<br />
	#some secondary text<br />
	dialog.format_secondary_markup("This will be used for <i>identification</i> purposes")<br />
	#add it and show it<br />
	dialog.vbox.pack_end(hbox, True, True, 0)<br />
	dialog.show_all()<br />
	#go go go<br />
	dialog.run()<br />
	text = entry.get_text()<br />
	dialog.destroy()<br />
	return text<br />
if __name__ == '__main__':<br />
	print "The name was %s" % getText()<br />
	gtk.main()<br />
[/sourcecode]</p>
<p>In order to turn this into a password dialog, add in the part in bold:<br />
<code><br />
entry = gtk.Entry()<br />
<strong>entry.set_visibility(False)</strong><br />
#allow the user to press enter to do ok<br />
</code></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[PyGameHouseAdmin sistema gerenciador de "casas de games"]]></title>
<link>http://codigobr.wordpress.com/?p=19</link>
<pubDate>Fri, 04 Jul 2008 02:21:09 +0000</pubDate>
<dc:creator>Carlos Marques</dc:creator>
<guid>http://codigobr.pl.wordpress.com/2008/07/03/pygamehouseadmin-sistema-gerenciador-de-casas-de-games/</guid>
<description><![CDATA[Hoje adicionei mais um software na minha pagina de projetos pessoais, é um software pequeno escrito]]></description>
<content:encoded><![CDATA[<p>Hoje adicionei mais um software na minha pagina de projetos pessoais, é um software pequeno escrito em PyGTK, com banco de dados SQLite.</p>
<p>Para fins de administração de "games house", ainda está em faze inicial, mas já é funcional, até onde foi escrito.</p>
<p>O próximo passo é colocar alguma documentação, e melhorar um um pouco os recursos, acho que logo terei uma versão final.</p>
<p>aos interessados fiquem de olho na pagina do projeto no Google Code</p>
<p>http://code.google.com/p/pygamehouseadmin/</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Remote Clipboard]]></title>
<link>http://balajirrao.wordpress.com/?p=55</link>
<pubDate>Wed, 02 Jul 2008 20:26:50 +0000</pubDate>
<dc:creator>balajirrao</dc:creator>
<guid>http://balajirrao.pl.wordpress.com/2008/07/03/clipboard-fun/</guid>
<description><![CDATA[When I was using my GNOME desktop from inside a guest running on top of KVM, suddenly an idea struck]]></description>
<content:encoded><![CDATA[<p>When I was using my GNOME desktop from inside a guest running on top of <a href="http://kvm.qumranet.com/kvmwiki">KVM</a>, suddenly an idea struck me, about a couple of hours ago - "To allow copy and paste between the guest and the host". It would be a very valuable feature to have, I thought.</p>
<p>Deciding to hack a quick solution, I came up with the following in around two hours. It works only one way for the moment. The guest(virtual machine) is the server and the host is the client i.e, you will only be able to copy from the host and paste it into the guest. And it works only with text now.</p>
<p>In the guest, ( please change the IP address appropriately )</p>
<p>[sourcecode language='python']<br />
#!/usr/bin/python<br />
#Run this in the guest<br />
import socket,gtk</p>
<p>clip = gtk.Clipboard(display=gtk.gdk.display_get_default(), selection="CLIPBOARD" )</p>
<p>serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br />
serversocket.bind(("192.168.1.2", 7070))<br />
serversocket.listen(1)</p>
<p>while (True):<br />
	(clientsocket, address) = serversocket.accept()<br />
	clip.set_text(clientsocket.recv(100));<br />
	clip.store()<br />
	clientsocket.close();</p>
<p>serversocket.close()<br />
[/sourcecode]</p>
<p>And in the host,</p>
<p>[sourcecode language='python']<br />
#!/usr/bin/python<br />
import gtk,time,socket</p>
<p>clip = gtk.Clipboard(display=gtk.gdk.display_get_default(), selection="CLIPBOARD" )<br />
while (True):<br />
	prev = clip.wait_for_text()<br />
	while (prev == (clip.wait_for_text())):<br />
		time.sleep(1)</p>
<p>	prev = clip.wait_for_text()<br />
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br />
	s.connect(("192.168.1.2", 7070))<br />
	s.send(prev)<br />
	s.close()<br />
s.close()<br />
[/sourcecode]</p>
<p>With this program, I've copy-pasted across two machines in a network! Very powerful isn't it ? Its really surprising too see what around 35 lines of python can do. Though I had studied a bit of python a few years ago, this one small hack has made me fall into love with python again. Its an awesome language. Extremely powerful.</p>
<p>This program uses something called pygtk, which are python extensions for GTK. You can write GTK programs using python.</p>
<p>I wish to develop this further to the extent of copying files, images and other rich content across machine boundaries. Though it probably will be criticised for being bad from a security point of view, it will definitely be useful for users of KVM, XEN and other users of virtual machine monitors.</p>
<p>Happy hacking!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Mais DrawingArea, Orientação a objetos e herança (e glade)]]></title>
<link>http://medeubranco.wordpress.com/?p=38</link>
<pubDate>Mon, 30 Jun 2008 03:14:50 +0000</pubDate>
<dc:creator>medeubranco</dc:creator>
<guid>http://medeubranco.pl.wordpress.com/2008/06/30/mais-drawingarea-orientacao-a-objetos-e-heranca-e-glade/</guid>
<description><![CDATA[
Este artigo mistura um pouco de tudo o que foi visto nos artigos anteriores:
Criando uma simples ja]]></description>
<content:encoded><![CDATA[<p><img class="aligncenter size-full wp-image-45" src="http://medeubranco.wordpress.com/files/2008/06/desenho.png" alt="" /></p>
<p>Este artigo mistura um pouco de tudo o que foi visto nos artigos anteriores:</p>
<p><a href="http://medeubranco.wordpress.com/2008/06/07/criando-uma-simples-janela-com-pygtk/">Criando uma simples janela em PyGTK</a><br />
<a href="http://medeubranco.wordpress.com/2008/06/10/criando-uma-simples-janela-em-pygtk-parte-ii/">Criando uma simples janela em PyGTK - parte II</a><br />
<a href="http://medeubranco.wordpress.com/2008/06/15/drawingarea-desenhando-na-tela-com-pygtk/">DrawingArea - Desenhando na tela com PyGTK</a><br />
<a href="http://medeubranco.wordpress.com/2008/06/22/orientacao-a-objetos-com-python-para-iniciantes/">Orientação a Objetos com python</a><br />
<a href="http://medeubranco.wordpress.com/2008/06/22/heranca-orientacao-a-objetos-com-python/">Orientação a Objetos - Herança</a></p>
<p>Como aqui vamos usar o Glade, recomendo também uma visita ao blog do OgMaciel:</p>
<p><a href="http://blog.ogmaciel.com/?p=413">Vídeo Aula: Programando com Python e Glade</a></p>
<p><a href="http://blog.ogmaciel.com/?p=415">Vídeo Aula: Trabalhando com o Glade</a></p>
<p>Não deixe de ver também <a href="http://www.cin.ufpe.br/~cinlug/wiki/index.php/Mantendo_A_Sanidade_Com_O_Glade">Mantendo A Sanidade Com O Glade</a>.</p>
<p>Neste artigo vamos criar um programa em que você pode desenhar um polígono desenhando com o mouse.</p>
<p>Para isso, vamos estender a classe gtk.DrawingArea através da herança. Nossa classe estendida vai ser um DrawingArea com recursos que nós vamos adicionar.</p>
<p>Paralelamente, vamos fazer uma janela com o glade, um código que vai exibir a janela inserindo nela a nossa classe filha de DrawingArea.</p>
<p>A nossa classe tela herdando de DrawingArea:</p>
<p>[sourcecode language='python']</p>
<p>import gtk</p>
<p># do modulo gtk, importamos DrawingArea e vamos chamar de 'DA'<br />
from gtk import DrawingArea as DA</p>
<p>class tela(DA):<br />
    def __init__(self):<br />
        # executanto o construtor da classe pai (DrawingArea)<br />
        DA.__init__(self)<br />
[/sourcecode]</p>
<p>Agora temos uma classe que faz tudo o que um DrawingArea faz. Podemos acrescentar recursos a ela.</p>
<p>Enquanto isso, vamos fazer a GUI no glade:<br />
- crie uma janela;</p>
<p>- adicione uma "Caixa Vertical" (<strong>Vbox</strong>) com três itens;</p>
<p>- adicione um Rótulo (<strong>Label</strong>) na primeira seção da Caixa Vertical;</p>
<p>- em<strong> <em>Empacotamento</em></strong>, mude para <strong>"não</strong>" as opções <strong><em>Expandir</em></strong> e <strong><em>Preencher</em></strong>;</p>
<p>- adicione um botão e em Geral mude o nome para 'botão1' (é, poderia ter ficado Button1 mesmo);</p>
<p>- em<strong> <em>Empacotamento</em></strong>, mude para <strong>"não</strong>" as opções <strong><em>Expandir</em></strong> e <strong><em>Preencher</em></strong>;</p>
<p>- no espaço do meio, adicione  uma 'Porta de Visualização'  (ViewPort) ;</p>
<p>- mude o nome da ViewPort para 'caixatela'</p>
<p>- explore as outras opções de configuração dos widgets</p>
<p style="text-align:center;">Sua janela deve ficar quase assim:<br />
<a href="http://medeubranco.wordpress.com/files/2008/06/gladebglade.png"><img class="aligncenter size-medium wp-image-44" src="http://medeubranco.wordpress.com/files/2008/06/gladebglade.png?w=300" alt="" width="448" height="305" /></a></p>
<p><a href="http://medeubranco.wordpress.com/files/2008/06/glade-02.png"><br />
</a></p>
<p>Voltemos à nossa classe.</p>
<p>O nosso widget será usado da seguinte forma:</p>
<p>Você pressiona o botão esquerdo do mouse sobre o widget e mantém pressionado. Arrasta então o ponteiro do mouse pela tela; uma linha será desenhada por onde passar o ponteiro. Ao soltar o botão do mouse, a linha se fechará em um polígono.</p>
<p>Ao Rolar a 'rodinha' do mouse, os últimos pontos do polígono serão removidos; continue rolando a rodinha que o polígono desaparecerá.</p>
<p>Temos então três eventos envolvidos na criação do desenho: botão pressionado, movimento do mouse e botão solto (<em>'button-press-event'</em>, <em>'button-release-event'</em> e<em> 'motion-notify-event'</em> ). Um quarto evento, o de rolagem da rodinha ('scroll-event' ), está envolvido na operação de remover pontos do polígono.</p>
<p>[sourcecode language='python']</p>
<p>class tela(DA):<br />
    def __init__(self):<br />
        DA.__init__(self)<br />
        self.definecores()</p>
<p>        # atributo que determina se o botão está pressionado<br />
        self.apertou=False</p>
<p>        # conectando o expose-event a uma função<br />
        # que vai pedir que a tela seja redesenhada<br />
        self.connect('expose-event',self.expose)</p>
<p>        # adicionando os eventos de mouse<br />
        self.add_events(gtk.gdk.BUTTON_PRESS_MASK &#124;<br />
            gtk.gdk.BUTTON_RELEASE_MASK &#124;<br />
            gtk.gdk.MOTION_NOTIFY &#124;<br />
            gtk.gdk.POINTER_MOTION_MASK<br />
            )</p>
<p>        # conectando cada evento à sua função correspondente</p>
<p>        # botão de mouse pressionado<br />
        self.connect('button-press-event',self.clica)<br />
        # soltando o botão<br />
        self.connect('button-release-event',self.solta)<br />
        # movimento de mouse<br />
        self.connect('motion-notify-event',self.arrasta)<br />
        # rolando a 'rodinha'<br />
        self.connect('scroll-event',self.rolou)</p>
<p>        # criando uma lista vazia<br />
        # que vai conter os pontos da linha a ser desenhada<br />
        # ou o polígono<br />
        # cada ponto será uma tupla<br />
        # com as coordenadas (x,y)<br />
        self.linha=[]</p>
<p>[/sourcecode]</p>
<p>Olhe o código acima, nas linhas 23, 25, 27 e 29. Quatro funções terão que ser definidas. Vejamos o que cada uma deve fazer:</p>
<p>-<strong> self.clica</strong></p>
<ul>
<li>mudar a variável <em>self.apertou</em> para <em>True</em></li>
<li>adicionar o primeiro ponto (as coordenadas do clique) à lista self.linha</li>
</ul>
<p>- <strong>self.arrasta</strong></p>
<ul>
<li>se self.apertou é True, adiciona mais um ponto À lista e desenha o último segmento.</li>
</ul>
<p>- <strong>self.solta</strong></p>
<ul>
<li>mudar a variável <em>self.apertou</em> para <em>False</em></li>
</ul>
<p><strong>- self.rolou</strong></p>
<ul>
<li>remover o último ponto da lista e mandar a tela ser redesenhada</li>
</ul>
<p>[sourcecode language='python']<br />
    def solta(self, tela, evento):<br />
        self.apertou=False<br />
        self.desenha()</p>
<p>    def clica(self, tela, evento):<br />
        if evento.button==3:<br />
            self.linha.pop()<br />
            return<br />
        self.linha.append((evento.x,evento.y))<br />
        self.apertou=True</p>
<p>    def rolou(self,tela,evento):<br />
        try:<br />
            self.linha.pop()<br />
            self.desenha()<br />
        except:<br />
            pass</p>
<p>    def arrasta(self,tela,evento):<br />
        if self.apertou:<br />
            self.linha.append((evento.x,evento.y))</p>
<p>[/sourcecode]</p>
<p style="text-align:center;">Movendo o mouse com o botão pressionado<a href="http://medeubranco.wordpress.com/files/2008/06/pintor1.png"><img class="aligncenter size-medium wp-image-42" src="http://medeubranco.wordpress.com/files/2008/06/pintor1.png?w=300" alt="" width="396" height="306" /></a></p>
<p style="text-align:center;">
<p style="text-align:center;">Após soltar o botão<a href="http://medeubranco.wordpress.com/files/2008/06/pintor2.png"><img class="aligncenter size-medium wp-image-43" src="http://medeubranco.wordpress.com/files/2008/06/pintor2.png?w=300" alt="" width="392" height="303" /></a></p>
<p style="text-align:center;">
<p style="text-align:left;">O código completo da classe:</p>
<p style="text-align:left;">
<p>[sourcecode language='python']</p>
<p>import gtk<br />
from gtk import DrawingArea as DA</p>
<p>class tela(DA):<br />
    def __init__(self):<br />
        DA.__init__(self)<br />
        self.definecores()</p>
<p>        self.apertou=False<br />
        self.connect('expose-event',self.expose)<br />
        self.add_events(gtk.gdk.BUTTON_PRESS_MASK &#124;<br />
            gtk.gdk.BUTTON_RELEASE_MASK &#124;<br />
            gtk.gdk.MOTION_NOTIFY &#124;<br />
            gtk.gdk.POINTER_MOTION_MASK<br />
            )<br />
        self.connect('button-press-event',self.clica)<br />
        self.connect('button-release-event',self.solta)<br />
        self.connect('motion-notify-event',self.arrasta)<br />
        self.connect('scroll-event',self.rolou)<br />
        self.linha=[]</p>
<p>    def definecores(self):<br />
        self.verde=gtk.gdk.Color(0,48255,0,0)<br />
        self.preto=gtk.gdk.Color(0,0,0,0)<br />
        self.branco=gtk.gdk.Color(65535,65535,65535,0)<br />
        self.vermelho=gtk.gdk.Color(65535,0,0,0)<br />
        self.amarelinho=gtk.gdk.Color(35535,65333,15000,0)<br />
        self.outra=gtk.gdk.Color(0,65535,65535,0)<br />
        self.azul=gtk.gdk.Color(0,0,65535,0)</p>
<p>    def desenhaultimo(self):<br />
        if len(self.linha)>1:<br />
            x1=int(self.linha[-2][0])<br />
            y1=int(self.linha[-2][1])<br />
            x2=int(self.linha[-1][0])<br />
            y2=int(self.linha[-1][1])</p>
<p>            self.gc.set_rgb_fg_color(self.vermelho)<br />
            self.window.draw_line(self.gc,x1,y1,x2,y2)</p>
<p>            self.gc.set_rgb_fg_color(self.preto)<br />
            self.window.draw_rectangle(self.gc,False,x1-1,y1-1,2,2,)<br />
            self.window.draw_rectangle(self.gc,False,x2-1,y2-1,2,2,)</p>
<p>    def solta(self, tela, evento):<br />
        self.apertou=False<br />
        self.desenha()</p>
<p>    def clica(self, tela, evento):<br />
        if evento.button==3:<br />
            self.linha.pop()<br />
            return<br />
        self.linha.append((evento.x,evento.y))<br />
        self.apertou=True</p>
<p>    def rolou(self,tela,evento):<br />
        try:<br />
            self.linha.pop()<br />
            self.desenha()<br />
        except:<br />
            pass</p>
<p>    def arrasta(self,tela,evento):<br />
        if self.apertou:<br />
            self.linha.append((evento.x,evento.y))<br />
            self.desenhaultimo()</p>
<p>    def apaga(self):<br />
        for pt in self.linha:<br />
            print pt<br />
        self.linha=[]<br />
        self.desenha()</p>
<p>    def desenha(self):<br />
        a,b,c,d = self.get_allocation()<br />
        self.gc.set_rgb_fg_color(self.branco)<br />
        self.window.draw_rectangle(self.gc,True,0,0,c-1,d-1)</p>
<p>        if len(self.linha)>0:<br />
            self.gc.set_rgb_fg_color(self.amarelinho)<br />
            self.window.draw_polygon(self.gc,True, self.linha)<br />
            self.gc.set_rgb_fg_color(self.preto)<br />
            self.window.draw_polygon(self.gc,False, self.linha)</p>
<p>        self.gc.set_rgb_fg_color(self.preto)<br />
        self.window.draw_rectangle(self.gc, False,2,2,c-4,d-4 )<br />
        for pt in self.linha:<br />
            self.window.draw_rectangle(self.gc, False,pt[0]-1, pt[1]-1,2,2)</p>
<p>    def expose(self,tela, evento):<br />
        self.gc=self.get_style().fg_gc[gtk.STATE_NORMAL]<br />
        self.gc.set_rgb_fg_color(self.branco)<br />
        self.desenha()</p>
<p>[/sourcecode]</p>
<p style="text-align:left;">Para entender as operações de desenho, veja o artigo anterior: <a href="http://medeubranco.wordpress.com/2008/06/15/drawingarea-desenhando-na-tela-com-pygtk/">DrawingArea - Desenhando na tela com PyGTK</a></p>
<p style="text-align:left;">Salve este código como desenha.py</p>
<p style="text-align:left;">Salve seu projeto no Glade como parapintar.glade</p>
<p style="text-align:left;">E execute o código abaixo, que vai reunir tudo:</p>
<p>[sourcecode language='python']</p>
<p>#!/usr/bin/env python<br />
# -*- coding: utf-8 -*-<br />
"""<br />
Código parcialmente reaproveitado<br />
do código exemplo do OgMaciel<br />
em http://blog.ogmaciel.com/?p=413<br />
"""</p>
<p>import desenha<br />
try:<br />
    import pygtk<br />
    pygtk.require( "2.0" )<br />
except:<br />
    pass<br />
try:<br />
    import gtk<br />
    import gtk.glade<br />
except:<br />
    sys.exit(1)</p>
<p>class Janelao(object):<br />
    """<br />
    Janela criada com o Glade<br />
    """</p>
<p>    def __init__(self):<br />
        self.xml = gtk.glade.XML( "parapintar.glade" )<br />
        self.xml.signal_autoconnect(self)</p>
<p>        self.mainWindow = self.xml.get_widget( 'window1' )<br />
        self.mainWindow.set_title( "Pintor" )</p>
<p>        # puxando a ViewPort criado no glade<br />
        self.caixa=self.xml.get_widget( 'caixatela' )<br />
        self.mainWindow.connect('destroy', gtk.main_quit)</p>
<p>        self.botao = self.xml.get_widget( 'botao1' )</p>
<p>        # criando uma instancia do nosso objeto<br />
        self.tela=desenha.tela()<br />
        #inserindo nosso objeto na viewport<br />
        self.caixa.add(self.tela)</p>
<p>        self.botao.connect("clicked",self.apagar_tela)<br />
        self.tela.show()<br />
        self.mainWindow.show_all()</p>
<p>    def apagar_tela(self,botao):<br />
        self.tela.apaga()</p>
<p>if __name__ == "__main__":<br />
    w = Janelao()<br />
    gtk.main()<br />
[/sourcecode]</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[PyL2Catalogo - Arquivo de senhas]]></title>
<link>http://codigobr.wordpress.com/?p=14</link>
<pubDate>Thu, 26 Jun 2008 13:26:51 +0000</pubDate>
<dc:creator>Carlos Marques</dc:creator>
<guid>http://codigobr.pl.wordpress.com/2008/06/26/pyl2catalogo-arquivo-se-senhas/</guid>
<description><![CDATA[Quando comecei a aprender PyGTK eu pensei em criar um programa simples para salvar os dados de Login]]></description>
<content:encoded><![CDATA[<p>Quando comecei a aprender PyGTK eu pensei em criar um programa simples para salvar os dados de Login e Senha dos vários servidores de Lineage 2 que eu jogava, como eram vários servidores e varias contas de usuário por servidor era fácil de esquecer.</p>
<p>Então comecei um projeto chamado PyL2Catalogo, criei uma interface no Glade e comecei a escrever o código, isso ja faz algum tempo e o programa esta perdido dentro de um pendrive, mas agora vou disponibilizar eles para que quem quiser aprender a usar PyGTK com Glade possa aproveitar.<br />
Como não é possivel upar um arquivo compactado para o wordpress, vou colocar o arquivo no grupo PyGTK-Brasil e vou deixar só o link aqui para quem quiser pegar.</p>
<p><a title="PyL2Catalogo.zip" href="http://pygtk-brasil.googlegroups.com/web/PyL2Catalogo.zip">PyL2Catalogo.zip</a></p>
<p>E um screenshot para quem quiser conferir antes de baixar</p>
<p><a href="http://codigobr.wordpress.com/files/2008/06/pyl2catalogo.png"><img class="aligncenter size-full wp-image-15" src="http://codigobr.wordpress.com/files/2008/06/pyl2catalogo.png" alt="" width="499" height="269" /></a></p>
]]></content:encoded>
</item>

</channel>
</rss>
