Archive for the ‘Tools’ Category

The first tips you’ll need before start programming for Symbian using Qt

Friday, January 13th, 2012

Last weekend I made my first Qt/Symbian mobile application. It was a very simple project, and its only purpose was to learn how to program for Symbian platform. I made a small application to search information about movies in TheMovieDb, and its source code is available at my github profile.

A Qt/Symbian app is something very close to a normal Qt-based application for desktop, but there are some little differences that can make you confused and some tips you may need, here are my advices for some pitfalls I’ve found.

Instead of showing widgets, add them to a QStackedWidget

(that’s the best solution I’ve found, but it seems to have other solutions)

In desktop Qt, you create a new QWidget and call show() to create a new window containing that widget. This won’t work with Symbian. When you do that, all you’ll get is a small, transparent widget at the corner of your screen.

The solution is to get the QMainWindow of your application, add a QStackedWidget as its central widget and add your new widgets into this QStackedWidget.

Every new widget must be added to QStackedWidget. It sounds painful, but Qt documentation tells us that when a widget is added to a QStackedWidget, the QStackedWidget becomes its parent.

When you create the first widget and add it to the stack, our QStackedWidget becomes its parent. So, to create a second widget and add it to the stack, you create your new widget as you do normally and asks the parent of the first widget – the QStackWidget! – to add it to the stack.

// Create your widget
QWidget *someWidget = new QWidget(parent());

// Get the reference to our QStackedWidget casting the widget parent
QStackedWidget *stackedWidget = (QStackedWidget*) parent();

// Add the widget
stackedWidget->addWidget(someWidget);
stackedWidget->setCurrentWidget(someWidget);

Creating menus and associating to positive and negative buttons

Nokia cell phones, even the cheaper ones, have options associated to the positive and negative buttons. Take a look on this picture of an old N70:

In the picture above, the positive action is Options, the negative option is Back. Creating options like these for your widget is quite simple.

In your widget’s source code, put the following lines in your constructor. Behold the lines where we use setSoftKeyRole to associate the action to a key. In my example, I have a “Back” shortcut and a “Details” shortcut, that access some slots.

// Register the negative action
QAction *backToMainScreenAction = new QAction("Back", this);
backToMainScreenAction->setSoftKeyRole(QAction::NegativeSoftKey);
connect(backToMainScreenAction, SIGNAL(triggered()), SLOT(removeWidget()));
addAction(backToMainScreenAction);

// Register the negative action
QAction *selectResultAction = new QAction("Details", this);
selectResultAction->setSoftKeyRole(QAction::PositiveSoftKey);
connect(selectResultAction, SIGNAL(triggered()), SLOT(showDetailsAboutTheCurrentItem()));
addAction(selectResultAction);

This code will register the action of each widget. But to make the options show in the screen, we must make the widget’s container – the QStackedWidget! – register these actions in the menu every time the widget is created. I put the following lines in the same file where’s my main window containing the QStackedWidget. First we create the following slot:

// This is a slot!
void MainWindow::updateActions() {
    QWidget *currentWidget = stackedWidget->currentWidget();
    menuBar()->clear();
    menuBar()->addActions(currentWidget->actions());
}

In the class’s constructor, we connect the stacked widget’s signals that are emmited when a widget is added or removed to the slot above:

connect(stackedWidget, SIGNAL(currentChanged(int)), SLOT(updateActions()));
connect(stackedWidget, SIGNAL(widgetRemoved(int)), SLOT(updateActions()));

Don’t believe the Nokia simulator

It’s still experimental. Sometimes you may think you made a mistake and have a bug, but you don’t. The simulator sometimes is confused with menus and soft buttons. If you get lost with your code and can’t find the causes of some obscure bug, try your application with a real device.

Good luck with the Remote Compiler

It’s still experimental too. When I tried to use it, I got some short error messages whose source I couldn’t discover. So, if you don’t use Windows (like me), prepare a virtual machine running Qt SDK on Windows.

Using Automator to make your life with Transmission easier

Saturday, July 9th, 2011

I have two computers: a Macbook with Snow Leopard, that sometimes I carry with me, and a computer at home with an Atom processor and running Linux that is my media server and downloader. If I need to download something that will take too much time, I put this second computer to download: it has a good connection and it’s always online.

It has Transmission running with its great web interface activated. If I need to download some torrent file, I open its web interface and upload the .torrent file. Good, but… it could be easier.

If you download torrent files very often, the easiest way is to use the watch-dir feature from Transmission: every torrent that you put at some directory is automatically downloaded by Transmission. So, all I needed to do was copying the torrent files from my Macbook to my home server, using SFTP.

To configure your Transmission watch-dir, you must stop the Transmission service (I’m running the transmission-daemon version) and edit the settings.json file, inserting the following settings:

"watch-dir": "/home/mediaserver/transmission/watch",
"watch-dir-enabled": true

Remember: you must stop Transmission service, edit the file and start it again!

It works, but… It can be even easier, I thought. And I remembered of Automator, a good piece of software that comes with Snow Leopard, and that I knew but never used before.

The idea was: every time a new .torrent file is written at my laptop’s download directory, it should be copied to my home server.

So I opened Automator and created a new Folder Action:

At the top of the new workflow, I selected my Downloads folder:

 The next step in our flow is to create a script to copy our files via SSH to the computer that’s running Transmission. Use Utilities -> Run Shell Script to make it:

Now add the following content as the script’s source code. To make it work automatically, I allow my SSH server to receive connections using keys, not passwords. Don’t forget to change the scp’s destination to your computer’s host and directory:

for f in "$@"
do
	ext=`basename "$f" | awk -F "." '{ print $NF }'`
	if [ "$ext" == "torrent" ]; then
		scp "$f" root@myhostname.asdf.com:/home/transmission/watch
	fi
done

That’s it! Save your workflow and test it. Now, every time you click at a torrent file and download it, Transmission will download it automatically.

Listing the packages on Debian/Ubuntu in one line

Friday, February 4th, 2011

You can use dpkg to list all the packages that are selected on your Debian or Ubuntu system:

# dpkg --get-selections

But today I needed a way to list only the installed packages in just one line, so I could copy their names and use apt-get to install the same packages on another system. So I used the following command:

# dpkg --get-selections | grep "[ \t]*install$" | sed 's/[ \t]*install$//g' | awk 'BEGIN { packages = "" } { packages = packages " " $1 } END { print packages }'
acpi-support-base acpid adduser apt apt-utils [...] long list of packages [...] xsltproc xz-utils yelp zenity zlib1g zlib1g-dev

You can use the output above to easily install the same packages on another system using apt-get install <packages>.

Cool tools to avoid suffering with Windows

Monday, October 11th, 2010

After two years working only with Linux and Mac OS, I received a new task that requires using Windows for two months (only two months, happily). It’s hard to get back to this bugful, unstable and confusing world: I do believe Linux and Mac OS are easier to use than Windows, that big world of icons that lead to icons that lead to icons that lead to nowhere, but I’m doing my best.

I tried to find a set of useful and free (as in “free beer” and/or as in “free speech”) tools to make my work easier. They are:

Classic Shell Setup

I don’t know why Microsoft removed the toolbar from Windows Explorer since Windows Vista, but this application tries to put it back there. It also allows you to get some customisation of Start Menu, and get a simple, fast and useful menu like the Windows 9x/ME/2000 times.

Notepad++

I like gedit and kate, and the native alternative for Windows is Notepad++: a good editor for plain text files, like source code.

Pidgin

With support for MSN/Live/whatever network, Google Talk, ICQ, etc. Pidgin is one of the best chat clients. I’d rather use it than the fancy MSN Live Messenger.

Winamp

Why use iTunes or the suffering Windows Media Player if you can use Winamp? It has a clean interface, a good way to organise library (although it’s a little bit iTunesy) and a simple playlist, everything in the same screen. I really love the good and old Winamp.

VLC

Winamp can play some videos, but I think VLC is a better tool for this job. Besides, it has a great support for a huge range  of video formats and features for users with any needs and all experience levels.

Why I chose Qt

Thursday, May 13th, 2010

A few months ago, I planned to learn some graphic toolkit. As a GNOME user, GTK was my natural choice. Although I’m a Python lover, I chose C++ because I just wanted to learn a new language and stop being afraid of pointers. So I started to read the gtkmm documentation, like tutorials and API, and to program a simple music player. I was learning gtkmm and it all seemed okay.

But I read a little about Qt and, after talking with some friends about the pros and cons of GTK and Qt, I decided to do with Qt the same things that I’ve already done with GTK up to that point. So I would know what choice was better for me. Notice that I’m not saying that Qt is better for everybody and that GTK must die, but that Qt looked better for me and my personal project. After this disclaimer, and can tell my reasons:

  • Look & feel. I’m a look&feel fanatic, and sometimes I move from GNOME to KDE only to check its new features. But I hate how GTK applications look in KDE. You can use gtk-qt-engine, but you’ll still notice the differences. You can set GTK to use the excellent QtCurve theme, that have identical versions to Qt and GTK, but you’ll get tied to a theme. But look what you have if you run a Qt application in GNOME (gedit is a GTK-based application and Picard is a Qt-based application):

    Thanks to QGtkStyle, Qt applications detect if you are in GNOME and your Qt application gets an almost perfect GTK look & feel. And yeah, it includes open and save dialogs.
  • Documentation. Qt has a very, very rich and well-organised documentation, with tutorials, API references, and examples. gtkmm also have all these items, but they didn’t look very friendly to me. And the documentation of Qt 4.7, still in development, will be even better.
  • A simple, but good IDE. A good programmer must not be dependent on IDEs, but they really help you. I tried to use Anjuta (unstable sometimes), MonoDevelop (very good for .NET platform, but not a good IDE for C/C++ development) and Netbeans as IDE when I was using gtkmm, and I was not satisfied with them. But Qt has its official IDE, Qt Creator:

    Qt Creator is clean, simple, and complete. It has quick access to documentation, breakpoints, project configuration, native support for CVS, Subversion and Git, good code completion, a good GUI designer (like the GTK’s Glade), among other features.
  • Runs well on many platforms. Qt is smart enough to run well – and with native look & feel, I really like this – in Linux, Mac, Windows, and others.

But Qt still has some cons:

  • Users should have it installed to run Qt applications, and this is not very usual in Linux environments based on GNOME, neither on Windows systems.
  • Qt is free only if you’re using it in a free project. For commercial applications, you must obtain a commercial Qt licenceUpdate: this is not exactly a con. You still can use Qt under LGPL in commercial applications, but if you make any change to Qt you must publish them or purchase a commercial Qt licence (thanks, krok, for the comment).

If you’re beginning to learn to program for graphical environments or you’re looking for a good graphical library to use in your project, you really should give Qt a try, implement some examples and feel which option is better for you.


Conectando o PHP ao Oracle

Saturday, April 24th, 2010

Nota: fiz esse tutorial há 3 anos, não garanto que ele continue funcionando!

Depois de muito apanhar, aprendi uma maneira fácil de pôr o PHP pra se comunicar com o Oracle. A maioria das soluções que achei envolvia recompilar o PHP, mudar variáveis de ambiente, scripts de inicialização etc. Uma delas até deu certo, mas mudar as variáveis de ambiente fez o suporte a LDAP do PHP parar de funcionar, por razões que desconheço.

A solução que explico abaixo faz a mesma coisa, mas sem recompilar pacotes ou fazer gambiarras. Deu certo milagrosamente, após juntar a solução proposta por vários sites. O máximo que será feito é compilar a extensão oci8 para o PHP do Debian ou Ubuntu, que é feito automaticamente e em poucos segundos. A parte chata é baixar os arquivos do site do Oracle, que exige criação de conta.

Todos os comandos abaixo são executados como root. Boa sorte! :)

  1. No site de downloads do Oracle para Linux, baixe os arquivos instantclient-basic-linux32-10.2.0.3-20061115.zipinstantclient-sdk-linux32-10.2.0.3-20061115.zip. Você vai precisar criar uma conta no site da Oracle para isso. Após o download, extraia-os para o diretório /usr/local/oracle.
  2. Em /usr/local/oracle, crie o seguinte link: # ln -s libclntsh.so.10.1 libclntsh.so
  3. Instale os pacotes php5-devphp5-pear pelo apt-get ou aptitude (aptitude install php5-dev php5-pear). Caso não exista o php5-pear, procure por php-pear.
  4. Agora execute (lembre-se: sempre como root): # pecl install oci8
  5. Surgirá um prompt perguntando onde estão as bibliotecas do Oracle. Sua resposta será instantclient,/usr/local/oracle , como no exemplo:Please provide the path to ORACLE_HOME dir. Use ”instantclient,/path/to/instant/client/lib” if you”re compiling against Oracle Instant Client [autodetect] : instantclient,/usr/local/oracle
  6. No diretório /etc/php5/conf.d , crie um arquivo oci8.ini, com o seguinte conteúdo:extension=oci8.so
  7. O PHP deverá estar com suporte a Oracle (extensão oci8). Reinicie o seu servidor web (caso seja o Apache, apache2ctl restart).

Fontes: Installing PHP and the Oracle 10g Instant Client for Linux and WindowsHow to: Installing Oracle XE on Ubuntu with PHP

Dicas de ffmpeg

Sunday, April 11th, 2010

Precisei recentemente pegar um vídeo de música, tirar o áudio dele e colocar em outro vídeo. Para o serviço, usei o ffmpeg, o canivete suíço de edição de vídeo em linha de comando.

Os três passos foram:

1. Retirar o áudio do primeiro vídeo

ffmpeg -i danca_do_gorila.flv -ab 128 -ar 44100 gorila.mp3

2. Acrescentar o áudio retirado do primeiro vídeo no outro vídeo

ffmpeg -i video1.mp4 -i gorila.mp3 video_gorila.mp4

3. Selecionar um trecho de um vídeo com 2 minutos, a partir do instante 00:00:02

ffmpeg -i video_gorila.mp4 -ss 00:00:02 -t 00:02:00 video_final.mp4

GNOME 2.30

Friday, April 2nd, 2010

O GNOME 2.30 foi lançado nesse 1º de abril, e os pacotes rapidamente foram disponibilizados pro Arch Linux. :) Assim que atualizei o sistema, aproveitei pra conferir algumas das novidades. A maioria delas, na minha opinião, foram discretas.

Talvez a maior exceção seja o Nautilus, de interface renovada. Agora é possível dividir a visualização em duas, o que facilita muito a troca de arquivos entre dois locais diferentes. O Konqueror faz isso há alguns anos, e era uma funcionalidade que fazia falta no Nautilus.

Dois bugs que me enchiam o saco há algum tempo também parecem ter sido resolvidos. Ao usar dois monitores, alguns applets trocavam de lugar ao iniciar o GNOME e o papel de parede da área de trabalho era esticado entre os dois monitores. Agora o papel de parede é simplesmente replicado para os dois monitores.

Mais detalhes das mudanças na nova versão estão presentes no site do GNOME. Como todo mundo gosta de screenshots, aqui vai um da minha área de trabalho:

Cheat sheets do git

Thursday, March 25th, 2010

Cheat sheets são as melhores amigas de quem precisa fazer tarefas repetitivas no computador mas não quer perder tempo olhando o tempo todo pra guias de consulta rápida. Pra quem gosta do git (mais pessoas deveriam gostar do git…), aqui vão duas cheat sheets ótimas.

A primeira, de apenas uma folha mas bastante útil, está disponível no site do autor da mesmano próprio wiki do git. Ela traz um fluxo de uso do git que pode ser muito útil, que mostra quais passos você efetuar a cada comando do git executado:

A segunda, de duas folhas, também traz um fluxo. Na primeira página traz explicações gerais sobre git e na segunda os comandos que você precisa:

Baixando pacotes pré-compilados no FreeBSD

Wednesday, March 17th, 2010

Após instalar o FreeBSD 8.0 no meu modesto computador para tarefas rotineiras, veio a necessidade de instalar alguns pacotes. O FreeBSD tem duas modalidades de instalação de pacotes:

  • O sistema de ports, que automatiza a tarefa de baixar código-fonte e compilá-lo, além de adaptar alguns pacotes ao seu gosto: o sistema ajuda você a habilitar ou desabilitar opções de vários pacotes, como suporte a Unicode, X11, bibliotecas adicionais etc.
  • Pacotes binários pré-compilados, familiares pra quem vem do Linux (como eu).

O FreeBSD possui uma ferramenta simpática chamada pkg_add que lembra o apt-get, pacman ou yum do Linux, baixando pacotes nos repositórios do FreeBSD. Porém, ao pedir pro pkg_add instalar alguns pacotes, como o Transmission, ele instalou versões mais antigas. Fuçando no FTP do FreeBSD, achei pacotes mais recentes dos pacotes. A próxima briga foi pra fazer o pkg_add usar apenas esses pacotes mais novos (dum diretório amigavelmente chamado Latest).

O truque é simples: quando você executa pkg_add -r nomedopacote, o pkg_add busca por $PACKAGESITE/nomedopacote.tbz. Se você fuçar pelos diretórios dos mirrors do FreeBSD vai perceber que os pacotes normalmente se chamam nomedopacote-versão.tbz, exceto os do diretório Latest, que instalam automaticamente a última versão disponível. Nos comandos abaixo, reparem que usei o sistema para arquitetura 64 bits (amd64), se sua instalação for para x86 32 bits, troque amd64 por i386.

Assim, pra instalar o vim, usei o seguinte comando no bash:

[root@tinhoso /home/esdras]# export PACKAGESITE="ftp://ftp4.freebsd.org/pub/FreeBSD/ports/amd64/packages-8-stable/Latest/"
[root@tinhoso /home/esdras]# pkg_add -r vim

Você pode, ainda, acrescentar o comando do export no seu arquivo ~/.profile, o que fará o comando ser executado automaticamente a cada login:

[root@tinhoso ~]# echo export PACKAGESITE=\"ftp://ftp4.freebsd.org/pub/FreeBSD/ports/amd64/packages-8-stable/Latest/\" &gt;&gt; ~/.profile

Caso você use csh (shell padrão no FreeBSD!), o comando muda:

tinhoso# setenv PACKAGESITE ftp://ftp4.freebsd.org/pub/FreeBSD/ports/amd64/packages-8-stable/Latest/
tinhoso# pkg_add -r nano
Para tornar a variável permanente, acrescente esse comando no arquivo ~/.cshrc:

tinhoso# echo setenv PACKAGESITE ftp://ftp4.freebsd.org/pub/FreeBSD/ports/amd64/packages-8-stable/Latest/ >> ~/.cshrc

Fontes