signals and slots

C makes U hang yourself;
C++ even gives U a rope object to hang;
C# scourges U using a rope wrapper!

rarely talk about programming unless it comes to some new idea or something fun. However, in this article, I’m going to summarize a part of experiences in my career, about important concepts that I’ve learned and used: signals and slots. First appear and remain as fundamental concepts in the Qt library (“Qt” pronounced “cute” – which is so cute as a cross-platform application framework), the concepts has been adapted and developed into some other libraries (such as boost) and are being proposed as next standards for C++ language.

Please note that we’re talking C/C++ here, although signals & slots has been brought to many other languages (Java, Python, Ruby, JavaScript, etc.) Every coin has two sides and C/C++ is no exception, it has its own advantages and disadvantages (depend on types of applications). But the thing I like about C/C++ is that its half – civilized nature made it a strong language: the balance between abstraction and comprehensiveness has always been considered as core factor.

Noone want to build general applications using Assembly, and noone want to write lengthy code just for some simple features. To adhere the doctrine, strong – abstraction concepts must be introduced to capture grammar of the language, and simple, clear syntax that would make the code concise and comprehensive.

I came to signals & slots as solution to problems I’ve met when leading the CMS project, a DVRs managing software (client & server) with complicated GUI: a few screens, each screen can have a dozen tabs, each tabs can have hundreds of controls. Events on one control can affect other controls on other tab or screen, events can be user inputs as well as various signals come from dozens of (managed) network client machines.

The overwhelmingly – complicated communications surpass every MPM (message passing method), then signals & slots appeared as a saviour solution. To be simple, signals & slots is a very efficient mean of interaction between objects within a process space. I personally think it would be the next metaphor extension added to C/C++ language. Structure of this post would be as follow:

1. Introduction to signals & slots, from raw to abstract concepts.

2. ISO C++ compliant and cross – compiler, cross – flatform problems (would discuss about delegate and how function pointer has evolved from C to C++).

3. Different implementations of signals & slots: Qt, boost, sigslot, libsigc++

1.   INTRODUCTION

Flow of code is no more than a series of function call, and to perform asynchronous function call, traditional C programming use callback. A callback is a pointer to a function, so if you want a processing function to notify you about some event, you pass a pointer to another function (the callback) to the processing function. Callbacks have two fundamental flaws: firstly, they are not type-safe, we can never be certain that the processing function will call the callback with the correct arguments. Secondly, the callback is strongly coupled to the processing function since the processing function must know which callback to call. In C, to define function pointer, you would write something like this:

float (*my_func_ptr)(int, char *);
typedef float (*MyFuncPtrType)(int, char *);
MyFuncPtrType my_func_ptr;

When move to C++, things are a bit more complicated (note the weird syntax ->* to call a member function through pointer).

float (SomeClass::*my_memfunc_ptr)(int, char *);
my_memfunc_ptr = &SomeClass::some_member_func;
SomeClass *x = new SomeClass;
(x->*my_memfunc_ptr)(6, "Another Arbitrary Parameter");

Though a very strong concept in C, function pointer add little to the language C++. The only two uses of member function pointer in C++ are:

  • Demonstrate the tricky syntax of the language.

  • Help in implementation of delegate.

Now, imagine slots as invisible communication channels, every object can register to listen to some channels by providing delegates (pointer to a member function). The delegate would be invoked when slot is “filled” with a signal. The signals and slots mechanism is type safe: signature of a signal must match signature of the receiving slot. Signals and slots are loosely coupled: a class which emits a signal neither knows nor cares which slots receive the signal. To summarize the benifits:

  • Syntactically neater: signals & slots make for very readable code: you define the signals, you define the slots, then you wire them up.

  • Inherently robust: when either end of a signal/slot connection is destroyed, the connection is automatically removed. It is therefore impossible to emit a signal and have it arrive at a class that has already been deleted. Best of all, you don’t need to write any cleanup code.

  • Easier code reuse: since the thing that has to type-agree is the signal and the slot, not the whole class interface, it is much easier to plug together disparate classes that had never initially been intended to work in that way.

2.   DELEGATE

To summarize section 1: pointer is the root of all evils. Function pointer is the physical of callback method traditionally used in C programming. When evolved to C++, the C++ standard committee failed to address how to define function pointer to a single C++ object. With common-sense knowledge, we know that it take two elements to represent the thing: first is the address of the object itself (the implicit pointer this), second is pointer to the object’s member functions. The undefined land leads to different implementations across various compilers.

Contrary to common belief, the actual physical storage of pointer differs between various compilers, and even differs between types of pointer, e.g: pointer to a single – inheritance object, an multiple – inheritance one or virtual inheritance. The table below shows how many bytes it take to store pointers on different compilers (just make use of the operator sizeof). Then to calculate the actual member function’s address, each compiler uses one kind or another of offset:

struct BorlandMFP
{
        CODEPTR m_func_address;
        int delta, vindex;
};
if (vindex==0) adjustedthis = this + delta;
else adjustedthis = *(this + vindex –1) + delta;
C++
compiler
void*
pointer
function
pointer
single
inheritance
multiple
inheritance
virtual
inheritance
MS VC++ 4 4 4 8 12
GNU G++ 4 4 8 8 8
Borland C++ 4 4 12 12 12

So, delegate is just the new name for pointer to (an object’s) member function. The hard part really is that: since each compiler stores different type of pointers differently, there’s need for a way to store delegate in a universal manner: cross compilers and cross flatforms. Various techniques have been proposed by excellent programmers. Please refer to the articles below for specific techniques. I personally would prefer the method of Quynh Nguyen, an engineer at Global Cybersoft (Vietnam) Ltd.

3.   IMPLEMENTATIONS

To make those obscured concepts above clearer, I would go into some detailed implementations of signals & slots with the emphasize on the sigslot library, for this is really a compact lib: everything is contained in just one header file. Suppose you have a server that would receive some signal from network (tcp socket), then parse the received data and trigger some processing (display on GUI, store to disk…). We would define the “network signal” as follow (please note any number of parameters can be defined, we use an int and a char* here just for the example):

// the temmplate ‘signal2’ denote for
// a signal with 2 parameters

signal2<int, char*>m_netSig;

Then, at the place you want to process that event, e.g some class CDisplayForm, you would need to provide a function to process the signal:

DisplayForm::OnNetSig (int cmd, char* data)
{
  // the delegate would be invoked
  // when the signal is recieved

}

Please note that multiple objects can register to a same signal slot (and vice versa), e.g some class CRecordThread would also need to log that event to database. Then the listening objects would just register with the signal slot using a connect function:

// we pass the function pointer
// here to be called later

m_netSig.connect (this, &CDisplayForm::OnNetSig);

When the network signal arrive, e.g in some class CAsyncSocket, we would fire the signal and get it populated to all connected objects:

// emit the signal with it’s data
m_netSig.emit (NETSIG_DATA_RECEIVE, xmlStr);

Then the CDisplayForm and CRecordThread object would both receive the signal. Please note that when either end of the communication channel go out of scope, the connection is automatically removed, you don’t have to write any cleanup code. Just define the signal, the slot and wire them up! Any unrelated classes can be wired up in this type-safe manner without any pre-defined relation within them.

Speaking as an ex-hardware designer, I’d like software components to have pins around their edges, like ICs, so they can be ‘wired up’, but otherwise should be well behaved… I don’t want to know how that pin is wired internally – I just want to know that it will work when I send a signal into it.
(Sarah Thompson – sigslot library)

lucky luke – 2

ộ truyện tranh Lucky Luke thú vị trong từng chi tiết nhỏ: một lão thợ hớt tóc người Ý (thợ hớt tóc luôn phải là người Ý) mang cái tên Baldini (chẳng phải đã có câu thành ngữ: Never trust a bald barber đó sao) 😀, một tay tướng cướp lấy biệt hiệu là Po-8 (đọc như poet – nhà thơ)… Những nét cá tính và văn hoá Mỹ được mô tả một cách cô đặc, cường điệu và đầy tính hài hước.

Quá khiếp sợ vì 4 anh em nhà Dalton…

Và sáng kiến sửa chữa bánh xe độc đáo…

Ngay cả tiếng ngáy của những con người khác nhau cũng sẽ khác nhau.

Cuộc sống của những cao-bồi, lúc nào cũng canh chừng nhau thế này, ai đó hắt hơi thì sẽ có đổ máu.

Con sư tử mang tên đô đốc Nelson, và những chế giễu trên cái tên.

Thức uống của người và ngựa.

Lập trường nghề nghiệp của tay nhà đòn.

Đạo đức của người và ngựa.

Vận mệnh lớn lao của nước Mỹ qua việc treo cổ một người khác.

ôi những dòng sông nhỏ…

ột trong những bài hát hiếm hoi của Trịnh Công Sơn mà tôi thích, nhất là khi nghe không lời. Một trong số ít ỏi những bản nhạc của ông ăn sâu vào tâm hồn tôi như là kỷ niệm… Những trình bày khác nhau của bản nhạc, một hòa tấu piano, một độc tấu guitar (Võ Tá Hân), và một qua giọng hát khá thuyết phục của Trần Thu Hà (với guitar đệm thật đáng yêu). Một vài bìa nhạc Trịnh Công Sơn:

Tình xa - Piano (?) 
Tình xa - Guitar (Võ Tá Hân) 
Tình xa - Trần Thu Hà 

lucky luke – 1

ột bộ truyện tranh theo tôi là hay nhất trong tất cả những truyện tranh, Lucky Luke, hay hơn cả những truyện nổi tiếng khác như Asterix & Obelix hay Tintin. Truyện có không gian đa dạng, nhiều vị trí địa lý, nhiều thời điểm lịch sử, nhiều nhân vật của miền viễn Tây nước Mỹ thời gian đầu. Những tình huống được nhìn dưới các quan điểm khác nhau, đôi khi có vẻ “ngớ ngẩn”, nghề nghiệp và các nguyên tắc “bất di bất dịch” của nó… Những ẩn dụ trong Lucky Luke vẫn tiếp tục được trích dẫn rộng rãi trong nhiều tình huống của cuộc sống.

Tài bắn súng của Lucky Luke.

Trở ra từ phòng đánh bài.

Billy the Kid đi ăn cướp.

Anh em nhà Dalton, và thái độ khi bị gọi là “công dân lương thiện”.

Khi tàu sắp mắc cạn, thuyền trưởng không muốn bớt một chút nước nào từ dòng sông.

Thị trấn cờ bạc, nơi thị trưởng, con trai và cả con chó đều bị trét hắc ín và lông chim.

Trong tù, có được khẩu súng thật, Averell Dalton.. đi làm khẩu súng giả.

Mỗi thị trấn đều có một câu slogan và lòng hiếu khách khác nhau.

Về tính khí thất thường của con sông Mississipi.

Lão thợ sắp chữ nhà in và lời chào viết ngược theo đúng tác phong nghề nghiệp.

bang bang

ang Bang (My baby shot me down) is quite a special song: written by Sonny Bono, performed by Cher (1966), covered by Nancy Sinatra (1967), and has been translated to various languages since then. Younger people would recognize the the music as main soundtrack in the film Kill Bill (2003).

Bang bang - Sheila 
Khi xưa ta bé - Mỹ Tâm 
My baby shot me down - Nancy Sinatra 

I actually did thought it was a French song, until I listened to the gentle My baby shot me down, the original soundtrack is really simple, and moving, compared the glamourous French version.

ipix fish-eye camera


the dome camera and it’s Nikon fish-eye lens

Image above: Ipix’s raw format (spherical image). Click to try the Ipix static image viewer in a separate window, which helps to view a single Ipix’s frame, wrapping from raw format to normal rectangular format (not the video).

his is among the most interesting things I’ve ever worked on: Ipix’s CommandView™: fish-eye cameras which provide a 360° x 180° field of vision. This camera and it’s technology were very special and advanced at the time, about 3, 4 years ago, it were so new that the manufacturer could not survive the small market share and went bankruptcy. However, the technology has now revired at http://www.ipix.com. The camera came with some totally new concepts, patents and technologies. Some information on Ipix:

Ceiling or wall-mounted, with thick hard steel cover, the camera is designed to operate indoor or outdoor, and can withstand a temperature range from -40°C to 60°C. It costs about $2100 at the current time, and about $5000 when it first appeared. CommandView™ Dome is an IP camera, having a small Linux computer inside, once plugged onto LAN or WAN, the camera turns into a video server and can stream video in many protocols: http, ftp, rtp, or multicast. There’re 3 ways to control the camera: ssh to the Linux machine, access to it’s web-server or programatically use the XML-RPC interface. The product has a very matured and solid development flatform.

CommandView™ Dome is a mega-pixel camera (2 MB, 3 MB). The unique feature of this product is that it provides a 360° x 180° field of view with no moving parts. See the image beside (on the left – click to view a mega-pixel version), every details in the room is captured on a parabolic sphere (called wrapped image). To have a normal view, a region on the sphere is dewrapped (by software) into usual rectangular plane.

Since a whole 360° space is captured, PTZ (pan / tilt / zoom) is just a matter of dewrapping, there’s no need to motorize the camera for different sighting fields. This special camera has broadened the definition of ‘panorama’ and has many applications in security surveillance as well as photography. I myself found it very interesting to apply the concepts and softwares to demonstration and show-case purposes (search for ‘ipix’, the name has gone far beyond just a type of camera).

gió mùa xuân tới

hời tiết càng năm càng lạ, mới giữa tháng 11 mà Sài Gòn đã có những sáng se se lạnh, còn Hà Nội đã phải mặc áo ấm. Sáng sáng ra đường có cảm giác như mùa xuân sắp về, phóng xe ào ào trên đường, tưởng đâu đây có mùi nhang khói. Trong lòng không khỏi có chút sảng khoái, nôn nao như lúc giao mùa. Ở mãi cái xứ phương Nam bốn mùa chẳng mấy khác biệt này, giao mùa là một đặc ân mà không phải lúc nào cũng cảm nhận được. Không gian, thời gian, tất cả bối cảnh xung quanh như nhắc thầm: hãy để những đổi thay nho nhỏ len vào tâm hồn, hãy cố cảm nhận chúng, tích cóp chúng, để tự làm mới mình trong mọi điều nhỏ nhoi như thế!

tiếc thu

ôi chẳng phải là người hoài cổ, nhưng những âm thanh đã nghe lúc nhỏ thì chẳng mấy khi quên. Nhớ lại mà thấy buồn cười, hàng ngày cắp sách đến trường thì toàn hát: Cùng nhau ta đi lên, theo bước đoàn thanh niên đi lên, Cố gắng xứng đáng cháu ngoan Bác Hồ…, mà về nhà thì chỉ toàn nghe những thứ nhạc như thế này thôi.

Tình khúc mùa đông (Tiếc thu) - Thanh Trang - Lệ Thu 

Chỉ lớn lên mới thấy điều khập khiễng, chứ khi nhỏ thì cái gì cũng “tự nhiên”. Chẳng hiểu vì lý do nào lại thích bài nhạc ít người biết này: giai điệu, lời ca… chỉ nhớ khi nhỏ mỗi lần nghe bài này là chỉ nghe thấy tiếng triangle lảnh lót bên dưới.

album: con tạo xoay vần


Chiều nao nơi bãi hoang, lại ghé thăm mộ nàng, nhặt đóa hoa rụng vàng, thế thôi ngủ ngon em nhé, một giấc mơ màng. Nhìn hàng cây liễu dương, chạy suốt muôn dặm đường, chạnh nhớ câu đoạn trường. Cố nhân vừa rũ áo, về với vô thường. Chiếc bóng khoác nón ra đi cuối nơi con đường.

ốn dĩ tính không thích giải thích, nên chọn cách nói bằng nhạc. Hôm nay xem lại những post của mình, cảm giác: tệ! nói (viết) nhiều mà chẳng có nhiều điều mới! Nếu làm tư liệu thì đã có khối những web khác, nếu là tâm sự cá nhân thì hơi lang bang. Muốn diễn đạt điều gì mới (cho dù là trong những thứ cũ) nhưng sợ không có người đồng cảm.

Hoàng hạc tịch dương - Mai Hương 
Nguyên tác: Dolente immagine di Fille mia – Vincenzo Bellini.

Dạ hương thiên lý - Thái Hiền 
Nguyên tác: Memory (từ vở opera Cats) – Adrew Lloyd Webber.

Đặt lời Việt cho nhạc cổ điển không phải là điều gì mới, nhạc sĩ Phạm Duy và những nhạc sĩ khác đã đặt lời cho rất nhiều nhạc phẩm cổ điển: Dòng sông xanh, Sóng nước biếc, Vũ nữ thân gầy, Trở về Soriento, Khúc ban chiều .v.v.

Album Con tạo xoay vần sau đây thì thật sự mới lạ: đem ý Đường-thi phổ vào nhạc cổ điển phương Tây. Đem ý thơ của Lý Bạch, Bạch Cư Dị, Tiết Đào, Lý Hạ… phổ vào nhạc của Offenbach, Tchaikovsky, Bellini… đem tinh yếu của Đông và Tây hòa lẫn vào nhau. Hòa âm đơn giản, chỉ có một piano đệm, và các giọng hát được thu âm trực tiếp bằng kỹ thuật thu âm nổi, không qua xử lý bằng máy tính.

Album này theo tôi là hay và tinh tế hơn nhiều so với Chat với Mozart của Mỹ Linh. Trong album của Mỹ Linh, phần lời chưa ăn khớp được vào giai điệu và tiết tấu. Với album này, những giai điệu nhẹ nhàng được chọn từ các bản opera nổi tiếng, với lời nhạc lấy ý từ Đường-thi, tất cả tạo nên một loại âm nhạc vừa cao sang, vừa gần gũi. Kỹ thuật thu âm càng giúp cho hơi nhạc giản dị, tự nhiên đi vào lòng người.

abba – the piper – remixed

ìm thấy bài rất yêu thích này trong một remixed – collection của ABBA, 2006. Rất mê bài này không chỉ vì phần nhạc mà còn vì phần lời: rất hiểu và cũng chẳng hiểu gì cả về phần lời đầy ẩn dụ, nhiều người đã bàn cãi nhưng vẫn không làm rõ được lời hát ám chỉ điều gì.

The piper - Remixed version 
The piper - Original version 

Bài hát sử dụng một thành ngữ Latin: sub luna saltamus – nhảy múa dưới ánh trăng; Chúng ta đều đi theo theo những giai điệu lạ kỳ, chúng ta đều bị hiệu triệu bởi một âm điệu nào đó, chúng ta đi theo người thổi sáo, rồi chúng ta nhảy múa dưới ánh trăng. Tuy chưa hiểu The piper ám chỉ điều gì, nhưng chính bài hát đã là một The piper, nó đã seduce rất nhiều người nghe.

Trên tầng nghĩa đơn giản nhất, lời bài hát cũng đã có một sức diễn tả mạnh: chúng ta ai cũng đi theo một giai điệu lạ kỳ nào đó mà ngay cả chúng ta cũng không hiểu nổi, đuổi theo những fantasies thoáng qua trong cuộc đời để rồi trong một phút tĩnh tại nào đó của tâm hồn, dừng lại để nghĩ về đời mình, vẫn thấy mình tự do và không có gì để hối tiếc…