Sunday, December 2, 2012

Automation for C++ COM pointers

This week I was working on a C++ program which used a lot of COM pointers. I remembered I’ve seen an automation class somewhere, and after some searching I found it, it’s Microsoft’s ComPtr template class. Although I liked the concept, it had too much fuss to me, so I was displeased in using it.

Oh well, here we go again: I wrote my own COM pointer automation class. Here it goes the full code of it, which I now share with the world:
#pragma once
#include <Windows.h>
#include <ObjBase.h>

template<typename T> class ComPtr {
public:
	ComPtr()                    : _ptr(NULL) { }
	ComPtr(const ComPtr& other) : _ptr(NULL) { operator=(other); }
	~ComPtr()                   { this->release(); }
	ComPtr& operator=(const ComPtr& other) {
		if(this != &other) {
			this->~ComPtr();
			_ptr = other._ptr;
			if(_ptr) _ptr->AddRef();
		}
		return *this;
	}
	void release() {
		if(_ptr) {
			_ptr->Release();
			_ptr = NULL;
		}
	}
	bool coCreateInstance(REFCLSID rclsid) {
		return _ptr ? false :
			SUCCEEDED(::CoCreateInstance(rclsid, 0, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&_ptr)));
	}
	bool coCreateInstance(REFCLSID rclsid, REFIID riid) {
		return _ptr ? false :
			SUCCEEDED(::CoCreateInstance(rclsid, 0, CLSCTX_INPROC_SERVER, riid, (void**)&_ptr));
	}
	template<typename COM_INTERFACE> bool queryInterface(REFIID riid, COM_INTERFACE **comPtr) {
		return !_ptr ? false :
			SUCCEEDED(_ptr->QueryInterface(riid, (void**)comPtr));
	}
	bool isNull() const { return _ptr == NULL; }
	T&   operator*()    { return *_ptr; }
	T*   operator->()   { return _ptr; }
	T**  operator&()    { return &_ptr; }
	operator T*() const { return _ptr; }
private:
	T *_ptr;
};
Basically, by using this class I don’t have to worry about calling the Release method. Most interestingly, I added two shorhand methods to ease my life, coCreateInstance and queryInterface. Here are an example illustrating the use of the ComPtr class, along with the cited methods:
{
	ComPtr<IGraphBuilder> graph;
	if(!graph.coCreateInstance(CLSID_FilterGraph))
		OutputDebugString(L"Failed!");

	ComPtr<IMediaControl> mediaCtrl;
	if(!graph.queryInterface(IID_IMediaControl, &mediaCtrl))
		OutputDebugString(L"Failed!");

	graph->RenderFile(L"foo.avi", NULL); // sweet!
}
If you’re wondering about the usefulness of this ComPtr class, try to write the code above without it.

Tuesday, November 27, 2012

HTML DTD: strict vs loose

I’ve been writing some HTML5 code lately, and at some point I faced some miscalculations of dimensions through CSS. After some research, I discovered I had my page being rendered in quirks mode. I’ve heard this expression before, but never really bothered much. What happens is that standards compliant pages should have a doctype declaration, which tells the browser the page should be rendered that way, otherwise the HTML will be rendered in a Neanderthal form, the so-called “quirks mode”. I never bothered using a doctype, because I didn’t know the real meaning of it. Until now.

Then, convinced to use a doctype, I faced another problem. There were two types for me:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
	"http://www.w3.org/TR/html4/strict.dtd">

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
	"http://www.w3.org/TR/html4/loose.dtd">
The first is called “strict”, the second is “transitional”. The strict cuts away all the deprecated tags, while the transitional is the same strict plus some stuff like iframe, which I’m using at my project. So, my page is a transitional one, and I finally found my DTD.

Good references here and here.

Friday, November 23, 2012

A JavaScript and HTML5 tree graph

Following the previous post, I needed a graphical representation of a tree graph to put on an HTML page. I thought it would be a great opportunity to learn this HTML5 thingy, which everyone is talking about these days. I ended up writing a full implementation of a tree graph using only HTML5 and pure JavaScript, thus avoiding any third-party JavaScript libraries.

However, I faced some problems. I had to plot more than 2,000 nodes, although not all at the same time, sometimes I had hundreds of them being shown. So I had to run into a series of optimizations of the algorithm, not only to speed up the internal calculations, but also the page rendering itself. On my first implementation, each node was a DIV, and the lines were drawn upon a canvas. Then at some point I decided to purely draw the whole monster on canvas, and I rewrote everything, taking the opportunity to add animation effects.

Since I consider it to be good and clean code, and believing that it could be useful to someone else, I published the whole code on GitHub at rodrigocfd/html5-tree-graph, along with an example file.

A hard work and a great experience, indeed.

Monday, November 12, 2012

A jQuery popup modal dialog

These days I needed to display a form in HTML. The simplest way to do this would be just go to another page, where the form would be displayed, then go back to the previous page after the submit. But the form had only a couple fields to use a whole page, and also it felt too cumbersome to go back and forth with the pages. Or I could use an ordinary window popup, but since it’s a modeless window, problems would easily arise.

So, with the aid of jQuery, I wrote a small jQuery plugin to use an ordinary hidden DIV as a popup modal dialog, so that I’d just have to keep the form into a DIV, and it would be shown without leave the current page. At some point, it saw that the OK and Cancel buttons could be automated themselves, so my form would need just the fields.

I also took the opportunity and used the same engine to generate automatic OK and OK/Cancel dialogs, thus beautifying the alert and confirm JavaScript stock functions. Worth mentioning that the popup can be stacked, that is, a modal popup can open another modal popup, and so on.

It ended up helping me a lot, so I published it on GitHub at rodrigocfd/jquery-modalForm, along with an example file.

Wednesday, September 12, 2012

Singly linked list in C++

These days I needed a clean implementation of a singly linked list in C++. I found some ones around, but none of them was functional and clean and the same time. So I wrote my own, using nothing but pure C++ with templates, and here I’m publishing the full implementation.

First, the header. I chose to put the node class nested into the linked list class, because this approach allows me to have another node class which can belong to another kind of structure, if I need to. There are a couple of methods beyond the basics, I needed them to have a functional data structure that worked for me.
template<typename T> class LinkedList {
public:
	class Node {
	public:
		      Node()                     : _next(NULL) { }
		      Node(const T& data)        : _data(data), _next(NULL) { }
		Node* insertAfter();
		Node* insertAfter(const T& data) { return &(*this->insertAfter() = data); }
		Node* removeAfter();
		T&    data()                     { return _data; }
		Node& operator=(const T& data)   { this->_data = data; return *this; }
		Node* next(int howMany=1);
		int   countAfter() const;
	private:
		T     _data;
		Node *_next;
	friend class LinkedList;
	};

public:
	      LinkedList()          : _first(NULL) { }
	     ~LinkedList();
	int   count() const         { return !this->_first ? 0 : this->_first->countAfter() + 1; }
	Node* operator[](int index) { return !this->_first ? NULL : this->_first->next(index); }
	Node* append();
	Node* append(const T& data) { return &(*this->append() = data); }
	void  removeFirst();
	Node* insertFirst();
	Node* insertFirst(const T& data) { return &(*this->insertFirst() = data); }
private:
	Node *_first;
};
The node class implementation:
template<typename T> typename LinkedList<T>::Node* LinkedList<T>::Node::insertAfter() {
	Node *tmp = new Node;
	tmp->_next = this->_next; // move our next ahead
	this->_next = tmp; // new is our next now
	return this->_next; // return newly inserted node
}

template<typename T> typename LinkedList<T>::Node* LinkedList<T>::Node::removeAfter() {
	if(this->_next) {
		Node *nodebye = this->_next;
		if(this->_next->_next) this->_next = this->_next->_next;
		delete nodebye;
	}
	return this; // return itself
}

template<typename T> typename LinkedList<T>::Node* LinkedList<T>::Node::next(int howMany) {
	Node *ret = this;
	for(int i = 0; i < howMany; ++i) {
		ret = ret->_next;
		if(!ret) break;
	}
	return ret; // howMany=0 returns itself
}

template<typename T> int LinkedList<T>::Node::countAfter() const {
	int ret = NULL;
	Node *no = this->_next;
	while(no) { no = no->_next; ++ret; }
	return ret; // how many nodes exist after us
}
And the linked list implementation:
template<typename T> LinkedList<T>::~LinkedList() {
	Node *node = this->_first;
	while(node) {
		Node *tmpNode = node->next();
		delete node;
		node = tmpNode;
	}
}

template<typename T> typename LinkedList<T>::Node* LinkedList<T>::append() {
	if(!this->_first)
		return ( this->_first = new Node ); // return first and only
	Node *node = this->_first;
	while(node->next()) node = node->next();
	return node->insertAfter(); // return newly inserted node
}

template<typename T> void LinkedList<T>::removeFirst() {
	Node *nodebye = this->_first;
	if(this->_first->next()) this->_first = this->_first->next();
	delete nodebye;
}

template<typename T> typename LinkedList<T>::Node* LinkedList<T>::insertFirst() {
	Node *newly = new Node;
	if(this->_first) newly->_next = this->_first; // only case of FRIEND use
	return this->_first = newly; // return newly inserted node
}
The machinery is pretty straightforward to use, I believe. You just need to declare one instance of the LinkedList class, and all the node manipulation will be done through it and the node pointers returned by the methods, which allows operations on the nodes themselves. You’ll never have to alloc/dealloc any node. Here’s an example, with some operations and then printing all elements:
#include <stdio.h>
int main() {
	LinkedList<int> list;
	list.append(33)->insertAfter(80);
	list.insertFirst(4)->removeAfter();

	LinkedList<int>::Node *node = list[0];
	while(node) {
		printf("%d\n", node->data()); // print each value
		node = node->next();
	}
	return 0;
}

Friday, July 27, 2012

Bringing back the favicon on Firefox 14

On its way to chromify Firefox, Mozilla removed the favicon from the URL bar on Firefox 14. I agree with their reason, saying that one could use the favicon to emulate the secure connection padlock, but in my opinion it should be disabled by default, being optional to bring it back. Not all Firefox users are newbies or morons.

Fortunately, a guy called jooliaan published an addon to bring the favicon back to the URL bar, and it works just like it should. The addon is called Favicon Restorer, and I highly recommend it.

The way it goes, Mozilla is killing Firefox version after version. We love Firefox for what it is; if we wanted something that looks like Chrome, we would just use Chrome. Wake up, Mozilla.

Thursday, July 5, 2012

A trick to auto hide Chrome download bar

If you make a quick search, you’ll find how many people are annoyed by Chrome’s download bar, which doesn’t hide itself automatically, and requires you to manually hit the “X” button. There is no way to automate this through the extensions API, nor the browser gives you any option.

However, I found a simple trick to close the download bar, and it’s so simple that it’s hard to imagine how no one had this idea before – I didn’t see it anywhere, by the way. Not exactly automatic, but it’s better than click that “X” button.

Here’s how: you’ll have to use two shortcut keystrokes. The first one is Ctrl+J, which opens the download tab. The silver bullet is that this download tab displays the download progress, thus automatically closing the download bar. Then, once you have the download tab opened, just hit Ctrl+W, which closes the current tab, and it’s done.

So, by hitting Ctrl+J and Ctrl+W in succession, you’ll be free from clicking the “X” button on the download bar.

Sunday, June 17, 2012

Linus Torvalds is my hero

I’m a big fan of Linus Torvalds, not only for what he did with Linux, but also for his figure, particularly his lack of tenderness. His thoughts about C++ are legendary already, and that impressed me to the point that today I’m writing mostly ANSI C code.

Now, during a talk at Aalto University in Finland, he voiced about the lack of support Nvidia has given Linux, and his zero-diplomacy balls have striked loudly again. For my personal delight, I must admit, since I had a problem with a Nvidia video card driver on my Ubuntu just a couple months ago, to which I simply shrugged after days of pain.

Listen to the man:


And Nvidia, fuck you!

Saturday, June 2, 2012

Nu Sans programming font

I’ve just discovered out the Nu Sans monospace font on a Reddit discussion regarding the Mensch font – which is also a good font. However, Nu Sans caught my attention when I tested it on Visual Studio 2008 because it has that Lucida Console feel: a large font within small line height. And this is good for programming, because you can fit more lines on the screen. The TTF of the link above is a demo without accents, but it’s pretty usable.

So I just found a new font for my programming font collection.

Sunday, May 13, 2012

FLAC and LAME frontend

I use the FLAC and LAME command line tools, and I’ve tried many FLAC and LAME frontends. And I disliked all them. One day I decided to write my own, with a parallel multithreaded handling of the files, so all the files are converted at once, taking advantage of multicore CPUs.

Today I’ve just published it as open source on GitHub. It’s pure C and Win32. I hope it can be useful to someone – not only the program itself, but also my C programming techniques. It can be found at rodrigocfd/flac-lame-gui.

Saturday, May 12, 2012

My first program on GitHub

That’s a simple C Win32 program to shrink down padding bytes from ID3v2 tags on MP3 files. Maybe the most important thing, I think it showcases my style of C programming, and I’m glad to share it with the world. I hope it can be useful to someone someday.

It can be browsed at rodrigocfd/id3-padding-remover.

Thursday, April 19, 2012

I hate the new Gmail look

I’ve managed to keep the classic Gmail look until today, when all of a sudden Gmail morphed irreversibly into the horrendous new interface, gray and white, without colors or contrast. The option to revert to the old good look cannot be found anymore, so that I’m stuck into this ominous thing! And the built-in themes don’t help!

I’m about to install Stylish addon and slap some CSS over this ugly interface, which I hate with passion. Let me say it again: I hate the new Gmail interface, which seems to have been inspired by the nothing.

Google is becoming more evil day after day.