Sunday, December 13, 2009

Qt4/OpenGL: Pose Editor

Last week I've published an automated "Puppet Animation" to show how Skeletal Animation and OpenGL works. Today, I've made something more to help you in the Animation Design Process.

The Qt code is really simple, it was just an UI with some slider connected to the Model Bones Matrix to performs Rotations and Translations and a QGLWidget that displays the OpenGL that you've already seen in the last post. I've also added a Useful ListWidget to display textures that are loaded by the model.

To get some cool models you can start by checking Blender's Open Projects that allows you to download models from Elephants Dream (see the screenshot above), Big Buck Bunny or Yo Frankie!. I'm still working on a better way to export Bones from Blender, If you've already tried and want to share some information, give me a mail! (thanks).

For this example, I've made a Big Package that contains the OpenGL engine that allows you to load and drows models and the Qt4 Pose Editor Tool that you can easily find in tools/ folder. The Source code is available here: Qt4/OpenGL Pose Editor Source Code.

Saturday, December 12, 2009

Backups and Files Deduplication

Yesterday, I've heard about a "No Space Left" on Backup Machine, obviously the first solutions arrived was like "Buy a new disk, they don't cost so much" or "Try this ultra branded backup product"... and then there's my custom and easy solution that was rejected. :)

So, If you're a little bit brave and you're able to write a couple of lines in Python you can have a very flexible backup system with files deduplication.

The main idea is...

  • Foreach home directory that you've to backup, store a key/value list with file_path/shasum (or an hash function that you trust).

  • Foreach file in the home directory check if the file is already on the backup server (Store files on Backup Server with shasum as name). If the file was not present upload it.


In this way on the Backup server there're "two folders" one that contains all the backed-up files (storing by shasum, means that one file was on server just once), and one that contains home-th30z-10-Nov-2009.list, home-th30z-11-Nov-2009.list, and so on.

In this way you can say... Hei, fully restore my home at "specified date" or just peek a file that you've in another specified date.. and maybe all the features that you want.

This is a easy and flexible way to store your backup, without wasting space and have a great granularity level of restore...

If you've really groked the idea, you can start your start-up company focused on backups. :D

Sunday, December 6, 2009

OpenGL: Skeletal Animation

Drawing meshes with OpenGL is really nice, but animating it's even funnier!


I've published the source code at gitHub git://github.com/matteobertozzi/GDEngine.git it's incomplete and buggy but it works for this kind of experiments.

Sunday, November 22, 2009

OpenGL: Collision Detection

Still experimenting with OpenGL, Today's example is about Collision Detection. As you can see from the screenshot... There's two crates and a wire sphere (I've no texture for that).. from the post title, you can imagine that the sphere moves in the direction of a crate and when it collided with the crate it changes its direction.
All the magic is under the hood, in the hit.c engine file. I've implemented a couple of methods that test collision between Box and Box, Box and Sphere, Box and Point, Sphere and Sphere, Sphere and Box, Sphere and Point. In this way you can easily handle the most common meshes, just checking glDataHitCollision(obj1, obj2).

The Source code is available here: GLData Collision Detection Example Source Code. Just type python build.py to build and run (Linux, Mac).

Nokia Certified Qt Developer!

Friday, I've received the congratulations mail to have successfully passed the Qt Essential exam, with the nice logo that you can see below... so, this post is just to place this sticker somewhere. I still prefer the Qt T-Shirt and the QtCentre paper of the Qt Centre Programming Contest.


Thanks to Giovanni Bajo and Develer, for the opportunity.

Sunday, November 1, 2009

OpenGL: Walk Around Camera

Again, another week spent on OpenGL. I don't know why but I cannot stop to experiment with Meshes, Vertexes, Faces and Textures. It's too amusing! But Todays, post it's just an update of GLData, the small gl data library that I use for my experiments.

The new features, for this update are: Speed-up in GL throughput, and Camera. I've adjusted data structure to use directly glVertexPointer() and related gl*Pointer() functions. The main.c file was adjusted to handle direction keys (Up, Down, Left, Right) to allows you to walk in your 3d world, like any First-Person shooter video game.

You can download the GLData Walk Around Source Code it. (Mesh not Included)

PS: For my Qt followers, and for those which they are waiting for my File-System/Distributed Computational System: I haven't forget Qt and the lovely memset(); I'm just exploring a bit (give me some week), a world that I've completely ignored.

Saturday, October 17, 2009

OpenGL meets Blender: Meshes and Textures

As you can see from the bigger Screenshot below, Today is time to put some characters on the OpenGL stage. And the two guys below are two of the characters of Yo Frankie! (http://www.yofrankie.org/). Following the preview post I've extended my GLData Library adding support for Textures and using another source format as Input File, I've also made a simple Blender-Export Script that allows you to easily export blender meshes with textures, vertexes and faces.
If you are, as me, fan of black and white command lines, The result is stunning. And there're just few lines of code. The code can be downloaded from here: GLData Blender Source Code. It contains the source code, textures, meshes and the Blender Export Script.

Sunday, October 11, 2009

OpenGL: Gts Format, Lights and Cameras

During my work, I've found an interesting library GNU Triangulated Surface Library (http://gts.sourceforge.net/) that does, some nice things, like Constrained Delaunay triangulations. But what I was really searching today are just meshes to use in my OpenGL experiments. And there're a some GTS samples available on the GTS website.
The screenshot above represents a GTS sample shape with a simple light effect. Just few lines of code to do it. But what I'm interested in, is create a simple way to load GTS file format, and below you can see the code.




void drawObject (const char *gts_shape_filename) {
  GLDataGts *gts;

  gts = glDataGtsAlloc();
  if (glDataGtsRead(gts, gts_shape_filename)) {
    GLDataSurface *surface;
    GLDataUInt i, count;
    GLDataTriangle *t;

    /* The Surface is an array of Triangles */
    surface = glDataGtsSurface(gts, NULL);
    count = glDataSurfaceCount(surface);
    for (i = 0; i < count; ++i) {
      t = glDataSurfaceGet(surface, i);

      glBegin(GL_LINE_LOOP);
      glVertex3f(t->p1->x, t->p1->y, t->p1->z);
      glVertex3f(t->p2->x, t->p2->y, t->p2->z);
      glVertex3f(t->p3->x, t->p3->y, t->p3->z);
      glEnd();
    }
  }

  glDataGtsRelease(gts);
}


The Source code is available here GLDataGts Source Code, and main.c contains a few comment lines that explain how to compile and run. Check the keyboardHandler() function to learn how to interact with the OpenGL camera and lights.

Thursday, October 8, 2009

OpenCL is for Everyone!

Last night I had a terrible nightmare, where all the apple/mac bloggers says "This app cannot be use used with older macs because it uses OpenCL, so you need the newest NVidia…"

..Fortunately, was just a nightmare. Everyone can use OpenCL, old macs (as my macbook) cannot use GPU, and cannot run faster, but OpenCL code can run on every machine.

You (as developer) need just to keep in mind to get Device in this way. So, if you haven't the latest NVidia you can still use, as always, CPU.


err = clGetDeviceIDs(NULL, CL_DEVICE_TYPE_GPU, 1, &device_id, NULL);
if (err != CL_SUCCESS)
  err = clGetDeviceIDs(NULL, CL_DEVICE_TYPE_CPU, 1, &device_id, NULL);

Saturday, September 26, 2009

[TIP] XCode Header Search Path

For many of you, this sounds like a stupid thing. But for those that just use gcc -I from command line, can be a pain find how to do it.

So, the problem is. How can I specify my Include path in XCode (gcc -I./mypath).


Tap on your project target, and click "Get Info", tap on "Build" tab and search "Path" as showed in the figure above. Then click on the "Header Search Paths" options and add your favorite include paths for selected target.

Saturday, September 5, 2009

Grand Central Dispatch: First Look

In the last years I've always used a "parallel task" approach foreach loops that I've in the code, not always to speedup but even to clean-up the code. How to do it? Wrapping threads and Thread Pool like in this C# Parallel Forech Code.

Snow Leopard has introduced a new BSD-level infrastructure, with simple and efficient API to do this job. Here a little usage preview.

Block objects are a C-based language feature that you can use in your C, Objective-C, and C++ code. Blocks make it easy to define a self-contained unit of work. Blocks are something like Actions (delegate {}) in C#. Very useful to embed function in loops.

Blocks looks like a "private" function pointer, but you can access to the "parent" vars. (If you're a Python coder, you've exactly the same thing).


/* Blocks in Python...
* def main():
*    a = 10
*    def test(k):
*        print a, k
*    test(128)
*/
int main (int argc, const char *argv[]) {
  int a = 12;

  void (^test_block) (int) = ^(int k) {
    printf("A Block: PARENT(%d) ARG(%d)\n", a, k);
  };

  test_block(128);

  return(0);
}


The GCD queue API provides dispatch queues from which threads take tasks to be executed. Because the threads are managed by GCD, Mac OS X can optimize the number of threads based upon available memory, number of currently active CPU cores, and so on. This shifts a great deal of the burden of power and resource management to the operating system itself, freeing your application to focus on the actual work to be accomplished.


#include <dispatch/dispatch.h>
#include <stdlib.h>
#include <stdio.h>

#define ITEM_VMIN       (1)
#define ITEM_VMAX       (200)
#define NR_ITEMS        (100)

static void __fill_item (void *items, size_t n) {
  int *i_items = (int *)items;
  i_items[n] = (ITEM_VMIN + (int)(ITEM_VMAX * ((double)rand() / RAND_MAX)));
}

static void __work_on_item (void *items, size_t n) {
  int *i_items = (int *)items;
  i_items[n] *= 100;  /* Do some Computation on this Item */
}

int main (int argc, const char *argv[]) {
  dispatch_queue_t queue;
  int data[NR_ITEMS];

  /* Get Global Dispatch Queue */
  queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

  /* Initialize data Elements, and run computation on each element */
  dispatch_apply_f(NR_ITEMS, queue, data, __fill_item);
  dispatch_apply_f(NR_ITEMS, queue, data, __work_on_item);

  /* Brief review of the items */
  dispatch_apply(NR_ITEMS, queue, ^(size_t n) {
    printf("Results: Item %lu = %d\n", n, data[n]);
  });

  return(0);
}

File-System and Data Block Back Reference

While I'm thinking and waiting for suggestions on how to improve my file-system block cache algorithm, I've decided to apply some changes to the Raleigh File-System Format (source code is not published yet).

Following the ideas of Valerie Aurora of Repair-driven File System Design, I've decided to add for each block (B*Tree and Data blocks) an head that contains a Magic Number and a CRC Sum of the block. In this way you can easily identify what kind of block you've peeked without scanning all metadata. Another step is to add a back reference (or back pointer) to the data block, in this way you can easily jump back to it's the extent block (and obviously to its OID) so you can easily understand what is the Object owner of this block and you can easily swap two blocks reading at most 4 blocks (2 Data and 2 Extends).

Another idea stolen from Valerie is to double the metadata blocks with a COW-like approach, as explained in this paper "Double the Metadata, Double the Fun: A COW-like Approach to FS Consistency", really useful for personal file-systems but maybe less in a distributed file-system. I'm working on it adding only as an mkfs option.

When the source Code will be online? I don't know.. I've less time to work on it. Maybe at the end of this year I'll publish the File-System and the Distributed System (explained some posts ago).
Double the Metadata, Double the Fun: A COW-like Approach to File

System Consistency"

Saturday, August 29, 2009

iPhone: Voice Mill

Yesterday I've played a bit with AVAudioRecorder, and this is a very small and funny example.
The main Idea is to create something like a wind mill that works with voice instead of wind.

The code below shows you how to record something. Then with the updateMeters() and peakPowerForChannel() you can extract the audio "noise".


NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:44100.0], AVSampleRateKey,
[NSNumber numberWithInt:kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt:1], AVNumberOfChannelsKey,
[NSNumber numberWithInt:AVAudioQualityLow], AVEncoderAudioQualityKey,
nil];

NSError *error;
recorder = [[AVAudioRecorder alloc] initWithURL:url 
settings:settings error:&error];
if (recorder) {
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
[recorder record];
...
}


The SWF Video is available here Voice Mill Video.
The Source Code is available here Cocoa Voice Mill Source Code.

Tuesday, August 25, 2009

Block Cache Algorithm

I need to replace my old filesystem cache algorithm with something more new and efficient. The old one is based on LRU/LFU algorithm. There's a queue of cached blocks and an Hashtable to speedup block lookup.


struct blkcache_buf {
struct blkcache_buf * next; /* Next Queue Item */
struct blkcache_buf * prev; /* Prev Queue Item */
struct blkcache_buf * hash; /* Next Item with the same hash */

xuint16_t count; /* Retain count */
xxx_block_t block; /* Cached Block */
};

typedef struct {
struct blkcache_buf ** buf_hash; /* Bufs Hashtable */
xuint16_t buf_hash_size; /* Bufs Hashtable Size */
xuint16_t buf_used; /* Bufs in use */

struct blkcache_buf * head; /* Head of the Bufs Queue */
struct blkcache_buf * tail; /* Tail of the Bufs Queue */

xxx_device_t * device; /* Block Device used for I/O */
} xxx_blkcache_t;


Above, you can see the cache data structure and below the core of the cache Algorithm.


#define BUFHASH(cache, blocknr) ((blocknr) % (cache)->buf_hash_size)

xxx_block_t *xxx_blkcache_read (xxx_blkcache_t *cache,
xxx_blkptr_t blocknr)
{
struct blkcache_buf *buf;
xuint16_t hash_index;

/* Scan the hash chain for block */
hash_index = BUFHASH(cache, blocknr);
if ((buf = __blkcache_find(cache, blocknr, hash_index)) != NULL) {
buf->count++;

/* Move Buf far from head */
__blkcache_buf_shift(cache, buf);

return(&(buf->block));
}

/* Cache is Full, Remove one Item */
if ((cache->buf_used + 1) > cache->buf_hash_size) {
/* All buffers are in use */
if (cache->head->count > 0)
return(NULL);

/* Remove Least-Frequently Used */
buf = __blkcache_remove_lfu(cache);
cache->buf_used--;
}

/* Desidered block is not on available chain, Read It! */
if ((buf = __blkcache_buf_alloc(cache, buf, blocknr)) == NULL)
return(NULL);

/* Add One Use, Block cannot be removed */
buf->count++;

/* Go get the requested block unless searching or prefetching. */
__blkcache_readwrite(cache, buf, RFALSE);

/* Update Cache Hash */
cache->buf_used++;
buf->hash = cache->buf_hash[hash_index];
cache->buf_hash[hash_index] = buf;

/* Update Cache Queue */
if (cache->head == NULL) {
cache->head = cache->tail = buf;
} else {
buf->prev = cache->tail;
cache->tail->next = buf;
cache->tail = buf;
}

return(&(buf->block));
}


You can download a demo implementation here: lru-block-cache.c, but I'm waiting some ideas or suggestions to improve (or change radically) the Cache Algorithm. Thanks in advance!

Tuesday, August 11, 2009

[TIP] Generic Binary Format

I Love use Binary formats, instead of XML, and JSON. Here is my Generic Binary Format for data transmissions or serializations. Data is composed by three blocks. The first one 1byte that describe all information about the object, like "is a single Int object" or "is a list", then tells you the second block length. The second block contains the size of the third block (The Data-Block) or the Number of Items in List.

Monday, August 10, 2009

[TIP] Generic Key Comparer

I'm back to code on my "Cloud" FileSystem, and distributed tools. And here is a little tip.

When you're working on Data, probably you store it as a Key-Value Pair on a BTree or something similar, and maybe this key is an aggregation of information... Maybe you've one bit of flag, N bytes of ParentKey, and others...

Now, the problem is... How can a "foreign" server sort correctly my keys? The solution is to send to the server the information on how to sort.. or a method to do it... but today, I'm focusing on the first one.



The code below show an implementation in Python of the Generic Key Comparer. At the end of the source code you can find an usage example. The Full Source Code is available here. Generic Key Comparer Source Code.



def __indexOfOne(data, tokens, offset):
  for i in xrange(offset, len(data)):
    if data[i] in tokens:
      return i
  return -1

def rawComparer(data1, data2, comparer):
  typeIds = [ 's', 'u', 'c', 'i', 'f', 'x' ]
  pyBinMap = { 
    ('u', 1): 'B', ('u', 2): 'H', ('u', 4):'L', ('u', 8):'Q',
    ('i', 1): 'b', ('i', 2): 'h', ('i', 4):'l', ('i', 8):'q',
    ('f', 4): 'f', ('f', 8): 'd'
  }

  p = i = 0
  while i < len(comparer):
  nextIdx = __indexOfOne(comparer, typeIds, i + 1)
  if (nextIdx < 0): nextIdx = len(comparer)

    format = None
    length = 1 if (i + 1) == nextIdx else int(comparer[i+1:nextIdx])      
    if comparer[i] == 's':
      format = str(length) + 's'
    elif comparer[i] == 'c':
      format = 'c'
    elif (comparer[i], length) in pyBinMap:
      format = pyBinMap[(comparer[i], length)]         

    if format != None:
      d1 = struct.unpack(format, data1[p:p+length])[0]
      d2 = struct.unpack(format, data2[p:p+length])[0]

     if d1 < d2:
       return -1
     elif d1 > d2:
       return 1 
     p += length
     i = nextIdx
     return 0

# Usage Example
if __name__ == '__main__':
  data1 = struct.pack('4sLch', 'test', 10, 'A', -3)
  data2 = struct.pack('4sLch', 'test', 10, 'A', -3)
  print 'Equal (test 10 A -3)', rawComparer(data1, data2, 's4u4ci2')

  data1 = struct.pack('4sLch', 'test', 10, 'A', 1)
  data2 = struct.pack('4sLch', 'test', 10, 'A', 0)
  print '(test 10 A 1) > (test 10 A 0)', rawComparer(data1, data2, 's4u4ci2')

  data1 = struct.pack('4sLch', 'test', 10, 'A', 0)
  data2 = struct.pack('4sLch', 'test', 10, 'A', 1)
  print '(test 10 A 0) < (test 10 A 1)', rawComparer(data1, data2, 's4u4ci2')

Thursday, August 6, 2009

Unified Notification Service: Avoid The Wheel Reinvention

Every programmer loves to reinvent the wheel, and reinventing the wheel is still my primary hobby. Sometimes you need to reimplement a Network protocol to use with your favorite language/library, sometimes is only for fun, but if you're in the Business World maybe is "better" (faster) to use one of the thousand existing libraries.

In the most cases you need to reimplement a Protocol to embed it in your application, and sometimes you have to reimplement two/three protocols that does the same job like IM Protocols (XMPP, AIM, Yahoo...).

A better solution, that avoid you to reinvent the wheel is to use an existent library to handle the protocol(s) that you need, and build an Abstract Interface, with your data format, that allows you to use a generic way to communicate between various provider. Below you can find a graphical example of what I mean.

You can have many providers, written in different languages. These providers talk with the Notification Service providing an abstract interface for the Apps. In this way, the end App has just to say "Write a Mail To X", "Download Todays Mail", "Send an IM to X"... and you can intercept notification to displays as a popup on your desktop... or something similar.

This solution will be used in MokoTouch Project, to provide Core Services to the Apps. For more information send me a mail.

Tuesday, August 4, 2009

A Bit of Distributed Computation...

In the last months I've worked on various 2D rendering projects, that requires lots of row power to be executed in smallest time as possible.

The rendering result is an aggregation of components (or better, Group of Components) that can be rendered independently of each other in a  process because each components has its own input data and until the aggregation process starts there're no dependencies between components. In a few words, foreach input data I've to call a Render method that returns the "computed" data, that at the end will be aggregated with all the computed values.

So, how speed-up the rendering? The standard answer is using Threads, to take advantage of multi-core system. But I need lots row power and lots of core to be fast enought. Another solution that doesn't require to spent a lot of money for a faster computer it to distribute the computation across different machines. And this is my attempt...

The Master receive an array of elements as input and splits up it according to the number of the available Nodes (Machines), and foreach node assigns its sub-array and sends an "informative message" to the node.

The Node waits for an "informative message" and when it has received it, starts its computation. Foreach Data Item that fetch runs the Computation and sends back the result.

The Master decompose data into equal-size partitions, so each node has  an equal-size queue to process, but if someone finishes its job and there're more data to process (in someone else queue) The Master dequeue couple of items from the slower node queue and add to the queue of the one that has finished its job. In this way you've done your computation faster then ever, and if one machine crashes (slow one case) its job will be taken by someone else that has finished its own.

And this is just a bit of General Theory, but the implementation is really simple. Maybe I'll try to reimplement something more generic in the near future (October, November) when I'll have a bit more of free time. If you've any question send me a mail!

Friday, July 31, 2009

Qt4 Imap API

Pushed in my GitHub repo the first draft of the Qt4 Imap (RFC 3501 Interne Message Access Protocol) Library.
I've implemented a sync communication because it's much easier to use, so if you want to use it in async way you need to implement a thread class that wrap the Imap class and throws the events that you need.


Imap imap;
if (!imap.connectToHost(IMAP_HOST, IMAP_PORT, IMAP_USE_SSL))
IMAP_MAIN_ABORT("connectToHost()", imap.errorString());

if (!imap.login(IMAP_USERNAME, IMAP_PASSWORD, IMAP_LOGIN_TYPE))
IMAP_MAIN_ABORT("login()", imap.errorString());

ImapMailbox *mailbox = imap.select("INBOX");
qDebug() << "INBOX";
qDebug() << " - Exists:" << mailbox->exists();
qDebug() << " - Unseen:" << mailbox->unseen();

QList<int> messageList = imap.searchRecentUnseen();
imap.fetch(mailbox, messageList);
foreach (int msgId, messageList) {
ImapMessage *message = mailbox->findById(msgId);
if (message == NULL) continue;

imap.fetchBodyStructure(message);

qDebug() << "FROM" << message->fromAddress().toString();
foreach (ImapAddress address, message->toAddresses())
qDebug() << " - TO" << address.toString();
qDebug() << "SUBJECT" << message->subject();

for (int i = 0; i < message->bodyPartCount(); ++i) {
ImapMessageBodyPart *bodyPart = message->bodyPartAt(i);
imap.fetchBodyPart(message, i);

qDebug() << bodyPart->isAttachment() << bodyPart->contentType();
qDebug() << bodyPart->data();
}
}

delete mailbox;

imap.logout();
imap.disconnectFromHost();

Thursday, July 23, 2009

Qt4 Google Contacts APIs

Just pushed at GitHub the first draft of the Qt4 Google Contacts Service...

Contacts APIs allows client applications to view and update Contacts content in the form of Google Data API feeds. Your client application can request a list of a user's contacts, edit or delete content in an existing contact.


// Setup Contact
THGoogleContact *contact = new THGoogleContact;
contact->setFullName("John Doe");

THGoogleIm *im = new THGoogleIm;
im->setRel(THGoogleIm::relWork());
im->setAddress("john.doe@aim.com");
im->setProtocol(THGoogleIm::protocolAim());
contact->addImAddress(im);

THGoogleEmail *email = new THGoogleEmail;
email->setAddress("john.doe@mail.com");
email->setRel(THGoogleEmail::relWork());
contact->addEmailAddress(email);

// Insert Contact
THGoogleContactsService *gContacts = new THGoogleContactsService;
gContacts->setAuthToken(...);
gContacts->insertContact(contact);


Take a look at contacttest.cpp for a more complete usage example.

Tuesday, July 14, 2009

OpenGL: 3D Cube, Rotation, Translation and Texts

Second hour with OpenGL, last time I've written a simple 2D example to learn what Vertex are, and now a little step forward using 3D, Rotation, Translation and Texts.

Using GLUT writing 2D texts is really simple, and here is how to do it. Setup Text Color, X and Y Location, pick up a font and set your string, and it's done.


glColor3f(1.0, 0.0, 0.0);
glRasterPos2f(-4.6, 2.3);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24, 'Hello Text');


To handle left, right, up, down keys to move the cube use the glutSpecialFunc() that allows you to handle GLUT_KEY_LEFT, GLUT_KEY_RIGHT, GLUT_KEY_UP, GLUT_KEY_DOWN keys and others. Translation and rotation are made using glTranslatef() and glRotatef().

The source code is available here: Python OpenGL 3D Cube Source Code.

Sunday, July 12, 2009

OpenGL: First Test - 2D Example

I'm not a Computer Graphics fan, but I've spent my the last year working on Report Engine, and User Interfaces... drawLine, drawRect.. setLocation... (I don't know.. I'm a malloc/memset boy).

But I need to learn more about Computer Graphics for the future, and today I've started playing with OpenGL... No more 2D points!!! :D
Below you can see a couple of lines of code that draws the example above...



static void drawTriangle (void) {
glColor3f(0.0f, 0.0f, 1.0f);
glBegin(GL_TRIANGLES);

glVertex3f( 0.0f,  0.6f, 0.0f);
glVertex3f(-0.2f, -0.3f, 0.0f);
glVertex3f( 0.2f, -0.3f, 0.0f);

glEnd();
}

static void drawSquare (void) {
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_TRIANGLE_FAN);

glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(0.5f, 0.0f, 0.0f);
glVertex3f(0.5f, 0.5f, 0.0f);
glVertex3f(0.0f, 0.5f, 0.0f);

glEnd();
}

static void drawSquareMode2 (void) {
const GLfloat squareVertices[] = {
-0.2,  0.2, 0.2, 
-0.2, -0.2, 0.2,
0.2, -0.2, 0.2, 
0.2,  0.2, 0.2 
};

glColor3f(0.0f, 1.0f, 0.0f);
glVertexPointer(3, GL_FLOAT, 0, squareVertices);
glEnableClientState(GL_VERTEX_ARRAY);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}


I've used NSOpenGLView to display the GL, so the drawing code is inside a drawRect method.
- (void)drawRect:(NSRect)bounds {
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);

glTranslatef(-0.2f, 0.0f, 0.0f);
drawTriangle();

glTranslatef(0.2f, 0.0f, 0.0f);
drawSquare();
drawSquareMode2();

glFlush();
}

Sunday, June 28, 2009

Reliable Protocol on Unreliable Channel

When you work with Unreliable communication channel (like UDP), you need to implement your own "Reliable Mechanism" to be sure that packet that you've send was received correctly. Here there's my attempt.

Reliable Transmitter:

The schema below shows the operations that reliable transmitter has to do. "Red" are "error or unexpected operations", Green are "expected operations", Blue are TX Operations.

Transmitter send a packet and waits for the ACK packet (sended by receiver). If ACK doesn't arrive before the Tx Timeout packet is resended. When ACK arrive Tx send the CACK (Confirm ACK) packet and waits for a timeout, if another ACK Arrive TX resend the CACK, this because receiver doesn't have the confirm of transmitter. When TX timeout all is done, and the packet is sended correctly.


Reliable Receiver:

The schema below shows the operations that reliable receiver has to do. "Red" are "error or unexpected operations", Green are "expected operations", Blue are Rx Operations.

When RX receive a Packet sends an ACK, and waits for the CACK, if CACK doesn't arrive before timeout RX resend the ACK. When CACK arrive all is done. We've received the packet and the transmitter knows that we've received it.

Qt4 Canvas Plugins

Today, during my Sunday morning bike trip I've had an Idea on how to simply implement a Canvas Plugins in Qt Applications, to give you an idea of How browser external plugins like flash or others works. The Code is really simple there's a class CanvasPlugin with a couple of Abstract Methods Init, UnInit, Resize, MouseEvent and a signal that says "Hey, Paint this Image!". To give you an Idea of the result below you can see a Window with two Widgets, a CanvasPluginViewer and a Label. Canvas Plugin Viewer load an external Library (.so) passed to the command line as first argument.


You can interact with the canvas like a normal widget (the red square moves along the window and you can stop and resume its animation). But you can extend the sample sending and receiving information from a server, or you can do other crazy external things. (See flash usage for more ideas).

That's all folks, it's lunch time. If you've any question send me a mail or write a comment, and remember that this is just a couple of minutes coded example, so don't use in your highly stable app. :)

The Source Code is Available Here: Qt4 Canvas Plugins Source Code.

Monday, June 22, 2009

OpenSSL: SSL Client/Server Example

I'm experimenting a bit with the new iPhone 3.0 SDK, Core Data, Game Kit, Push Notification Service and so on...

I'm using C, so today a little Example of SSL Client/Server written in C using OpenSSL, I've written a small wrapper for SSL Socket, and here is How to use it.


/* SERVER CODE
* ==============================
*/
SFSocketGlobalInit(); /* Initialize SSL */

/* Alloc Socket, Initialize SSL and Listen */
SFSocket *socket = SFSocketAlloc();
SFSocketInit(socket, CA_FILE, DH_FILE, KEY_FILE, KEY_PASSWORD, NULL);
SFSocketListen(socket, INADDR_ANY, PORT);

do {
SFSocket *clientSocket;
char buffer[64];
int rdSize;

/* Accept Client Connection */
if ((clientSocket = SFSocketAccept(socket)) == NULL)
break;

/* Read Data from Client */
if ((rdSize = SFSocketRead(clientSocket, buffer, 64 - 1)) > 0) {
buffer[rdSize] = '\0';
printf("Client: %s\n", buffer);
}

/* Write to Client */
strcpy(buffer, "Hello Client!");
SFSocketWrite(clientSocket, buffer, strlen(buffer));

/* Disconnect Client */
SFSocketRelease(clientSocket);
} while (1);

/* Close and Release Socket Resources */
SFSocketRelease(socket);


Above you've the simplified server code (without error check!) and below you've the client code. The client try to connects to server, send an "Hello" message and the server reply with other greetings.


/* CLIENT CODE
* ==============================
*/
SFSocketGlobalInit(); /* Initialize SSL */

/* Alloc Socket, Initialize SSL */
SFSocket *socket = SFSocketAlloc();
SFSocketInit(socket, CA_FILE, NULL, KEY_FILE, KEY_PASSWORD, NULL);

/* Connect to Host */
SFSocketConnectToHost(socket, HOSTNAME, PORT);

/* Send Message to Server */
char buffer[64];
strcpy(buffer, "Hello from Client!");
SFSocketWrite(socket, buffer, strlen(buffer));

/* Read Message from Server */
if ((rdSize = SFSocketRead(socket, buffer, 64 - 1)) > 0) {
buffer[rdSize] = '\0';
printf("Server: %s\n", buffer);
}

/* Close and Release Socket Resources */
SFSocketRelease(socket);



Remember that you need to generate, at least, the Authority Certificate, Server Certificate and Clients Certificates. and here is How to do it.


- AUTHORITY Certificate:
openssl genrsa -des3 -out ca.key 1024
openssl req -new -x509 -key ca.key -out ca.crt

- SERVER Certificate
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
openssl x509 -req -in server.csr -out server.crt -sha1 \
-CA ca.crt -CAkey ca.key -CAcreateserial

- CLIENT Certificate
openssl genrsa -des3 -out client.key 1024
openssl req -new -key client.key -out client.csr
openssl x509 -req -in client.csr -out client.crt -sha1 \
-CA ca.crt -CAkey ca.key -CAcreateserial



The Full Source Code is Available Here: SSL Client/Server Example Source Code.

Saturday, June 13, 2009

Qt4 iPhone Like Cut/Copy/Paste Widget

I'm watching the WWDC Keynote podcast, Just finished the Bertrand Serlet Talk, about Snow Leopard. Now before watching Scott Forstall with the new iPhone 3GS, a little break with an example of Cut, Copy and Paste like Widget. (In the Snow Leopard dock demo, I've seen "the same" widget used to do expose)

It's a really simple example but it can be useful to someone to understand how to add actions to a custom shape.

The Source Code is available Here: Qt4 iPhone Like Cut, Copy Paste Source Code.

Thursday, June 11, 2009

Qt4 Geo IP Location

In a time of Google Maps, Geo Location and other services like this... Here an example of Geo IP Location Service (http://www.hostip.info/) is really far from perfect, but it's just an example.

The sample uses QNetworkAccessManager to get the Geo Location of the IP, and Webkit to display the address on the Google Map.

The Source Code is available Here: Qt4 Geo IP Location Source Code.

Friday, May 29, 2009

Tool: IP Packet Sniffer

Today I've implemented a simple IP Packet Sniffer.

Sometimes is useful to know what're the IP packages that transit on your network, for Analyze network problems, Monitor network usage, Debug client/server communications or Debug network protocol implementations.

The tool is very simple, but I think that can be useful to learn something more about IP and TCP packets and Protocols implementation.

Maybe you can extend this Tool to support other Transport Layer Protocol.

Note: You need to run it as Root.

You can find the Source Code Here: IP Packet Sniffer Source Code.

Saturday, May 16, 2009

Qt4 Jump Away Animation

When I've started working on Mac OS X with Core Animation, I was impressed by an Example (I don't remember the link, if someone knows it, post it in the comments! thanks)... Very few lines of code for a great effect.

After a year, or probably more.. this example was came back to my mind, so I've decided to clone using Qt. And below you can see a short Demonstration Video. Your desktop jump away.. full screen is fantastic :)



The Source Code is Available Here: Qt4 Jump Away Animation Source Code.

Friday, May 15, 2009

PyQt4: PyCon3 Photos on Flickr

PyCon3 was finished, Only one week is passed and I already miss it. Guido van Rossum, Alex Martelli, Ariya Hidayat, Raymond Hettinger, David Boddie, Fredrik Lundh... C/C++ and Python Developer not .NET "coders" (I hate even more my boring .NET job).

Following the PyCon week, here a simple example of PyQt4 that allows you to see up to 500 photos tagged PyCon3 on Flickr.

As always the source code is available here: PyQt4 PyCon3 Flickr Source Code.

Monday, May 11, 2009

[TIP] Non Blocking C Read

This is Just a simple code that maybe all the Linux C Developer knows, but if someone is still learning, This is a function that wrap the standard read function adding the non blocking feature. It's Really useful in relation with Sockets.


int nonblock_read (int fd, char *buffer, size_t bufsize, int timeout) {
if (timeout > 0) {
struct timeval tv;
fd_set rfds;

FD_ZERO(&rfds);
FD_SET(fd, &rfds);

tv.tv_sec = 0;
tv.tv_usec = timeout * 1000;

if (select(1, &rfds, NULL, NULL, &tv) <= 0)
return(-ETIME);
}

return(read(fd, buffer, bufsize));
}

Thursday, May 7, 2009

PyCon3 Italia, 8-9-10 May 2009


I will spend the next few days in Florence for PyCon. Probably on Monday, I'll publish some photos and why not, code examples from PyCon.

See you there!

Wednesday, May 6, 2009

Qt4 Touch and Rotate

Alan has asked my How I've implemented the Touch and Rotate feature of the Moko. The answer is very simple, It's all Magic! There're very few lines of code to do it, because all the magic is made by atan2.

Atan2 is a variation of the arctangent function. For any real arguments x and y not both equal to zero, atan2(y, x) is the angle in radians between the positive x-axis of a plane and the point given by the coordinates (x, y) on it.

The Source Code is available here: Qt4 Touch and Rotate Source Code.
OT: PyCon3 (Italia) starts Tomorrow!

Saturday, May 2, 2009

Qt4 JSON Stream Reader

JSON, short for JavaScript Object Notation, is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects).

One way to use JSON with Qt4 is using the QScriptEngine (engine.Evaluate(jsonSource)), But I like Reinventing the wheel, so I've written a simple JSON Stream Reader that works "almost" like the QXmlStreamReader.

You've a readNext() method that read the next token and returns its type, and two properties name() and values() that Returns the name of the Property, Object or Array and the Value of the Property in a QVariant that can be Bool, Int, Double or String.

Below there's an Example of How to use the JSON Stream Reader. Maybe you can use it to create an automatic Object Mapper like the Xml Object Mapper that I've posted a couple of weeks ago.


QFile file("test.json");
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << file.errorString();
return(1);
}

THJsonStreamReader reader(&file);
while (!reader.atEnd()) {
switch (reader.readNext()) {
case THJsonStreamReader::PropertyNumerical:
qDebug() << " - Property Numerical" << reader.name() << reader.value();
break;
case THJsonStreamReader::PropertyString:
qDebug() << " - Property String" << reader.name() << reader.value();
break;
case THJsonStreamReader::PropertyFalse:
qDebug() << " - Property False" << reader.name() << reader.value();
break;
case THJsonStreamReader::PropertyTrue:
qDebug() << " - Property True" << reader.name() << reader.value();
break;
case THJsonStreamReader::PropertyNull:
qDebug() << " - Property Null" << reader.name();
break;
case THJsonStreamReader::Object:
qDebug() << "Object" << reader.name();
break;
case THJsonStreamReader::ObjectEnd:
qDebug() << "Object End";
break;
case THJsonStreamReader::Array:
qDebug() << "Array" << reader.name();
break;
case THJsonStreamReader::ArrayEnd:
qDebug() << "Array End";
break;
}
}

file.close();



The Source Code is Available Here: Qt4 JSON Stream Reader Source Code.

Friday, May 1, 2009

iPhone: Touch, Drag, Hit!

Yesterday, Fredrik has asked me something like "Drag & Drop with Hit Test" on the iPhone. Here's a simple example.  There's a simple UIView class that handles the touch events and a protocol that says that if the "DragMe View" has hit or not the "HitMe View". Below you can see the result and the Source Code Link.

The source code is available here: Touch, Drag, Hit Source Code.

Saturday, April 25, 2009

Qt4 Line Graph

Just back from Bike Trip, It's always inspiring... In the last minutes, I've written a quick Qt Line Graph demo that maybe I'll use in the my next Project, if I find a bit of time.

The code is far (far, far, far...) from perfect but is enough for a Test/Demo :)

The Source code is available here: Qt4 Line Graph Source Code.

Friday, April 24, 2009

C# Oracle for Beginners

In the last two days, at work I had a couple of hours to play with Oracle.
I've made a simple class to Wrap the .NET OracleConnection and here there's a simple example with Connection/Disconnection a couple of CREATE TABLE, INSERT a STORED PROCEDURE and a FUNCTION a couple of SELECT to show JOIN and other operations.


OracleDatabase db = new OracleDatabase();
db.Connect("192.168.3.2", "system", "password");

// Create And Populate Tables
db.ExecuteNonQuery("CREATE TABLE tb1 (a NUMBER NOT NULL, b CHAR(20))");
db.ExecuteNonQuery("INSERT INTO tb1 (a, b) VALUES (10, 'Matteo')");
db.ExecuteNonQuery("INSERT INTO tb1 (a, b) VALUES (20, 'Mauro')");

db.ExecuteNonQuery("CREATE TABLE tb2 (a NUMBER NOT NULL, b CHAR(20))");
db.ExecuteNonQuery("INSERT INTO tb2 (a, b) VALUES (10, 'San Francisco')");
db.ExecuteNonQuery("INSERT INTO tb2 (a, b) VALUES (20, 'Cuppertino')");

// A Store Procedure cannot Return Value
StringBuilder sp1 = new StringBuilder();
sp1.Append("CREATE OR REPLACE PROCEDURE tb2sp1 ");
sp1.Append("IS ");
sp1.Append("BEGIN ");
sp1.Append("INSERT INTO tb1 (a, b) VALUES (30, 'SP1 TEST'); ");
sp1.Append("END; ");
db.ExecuteNonQuery(sp1.ToString());

// A Function can Return a Value
StringBuilder sp2 = new StringBuilder();
sp2.Append("CREATE OR REPLACE function tb2sp2 (idx NUMBER) ");
sp2.Append(" RETURN NUMBER ");
sp2.Append("IS ");
sp2.Append(" var_count NUMBER; ");
sp2.Append("BEGIN ");
sp2.Append(" SELECT COUNT(*) INTO var_count FROM tb1; ");
sp2.Append(" return (var_count + idx); ");
sp2.Append("END; ");
db.ExecuteNonQuery(sp2.ToString());

List<OracleDatabase.DataRecord> r1 = db.Execute("select * from tb1");
List<OracleDatabase.DataRecord> r2 = db.Execute("select a, b, (a * 2 + 1) from tb1");
List<OracleDatabase.DataRecord> r3 = db.Execute("select tb1.a as ID, tb1.b as NAME,
tb2.b as PLACE from tb1 INNER JOIN tb2 ON tb1.a = tb2.a");
db.ExecuteStoredProcedure("tb2sp1");
List<OracleDatabase.DataRecord> r4 = db.Execute("select * from tb1");
object sp2RetVal = db.ExecuteFunction("tb2sp2(10)");

db.ExecuteNonQuery("DROP PROCEDURE tb2sp1");
db.ExecuteNonQuery("DROP FUNCTION tb2sp2");
db.ExecuteNonQuery("DROP TABLE tb2");
db.ExecuteNonQuery("DROP TABLE tb1");

db.Disconnect();


Here you can find the Source Code: Oracle for Beginners Source Code.

[TIP] Words Tokenization

Sometimes is useful to split the input text in a list of words to Indexing or Searching data.
Here is how to extract words from a sentence in C.


char str[] = "Hi, I'm a test. (This is just a test). "
"Join The #qt IRC Channel!"
"GNU/Linux - theo@gmail.com";
char delims[] = " !\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~";

char *result = NULL;
result = strtok(str, delims);
while(result != NULL) {
printf("%s\n", result);
result = strtok(NULL, delims);
}


...and this is the Qt way.


QString str = "Hi, I'm a test. (This is just a test). "
"Join The #qt IRC Channel! GNU/Linux - theo@gmail.com";
QString delim = QRegExp::escape(" !\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~");
QRegExp regexp(QString("[%1]").arg(delim),Qt::CaseSensitive,QRegExp::RegExp2);
qDebug() << str.split(regexp, QString::SkipEmptyParts);

Saturday, April 18, 2009

Bernardo The Smallest HTTPD Ever!

Sometimes I need an HTTP Server that allows me to run C or Python code or other scripts, and I need something that require 0 seconds of configuration. So I've decided to write a small httpd that does this work. (Use only for your test, not on a work machine!).

Bernardo (The name is inspired by the Zorro's servant) is a small HTTPD (Less that 200 lines of code) that allows you to Execute C, Python, Perl, PHP code or just "display" a file.

The Usage is Very simple: bernardo-httpd where www dir will be di root of your server and port is the TCP Port of the Service.

And now a simple code Example. You need to complete the HTTP Response Headers and then you can output your data. http://localhost:8080/test.py will display the "Hello Python" page.


#!/usr/bin/env python

import os

if __name__ == '__main__':
print "Content-Type: text/html"
print

print "<html>"
print "<head><title>Hello Python</title></head>"
print "<body>"
print "<h1>Hello Python</h1>"
print "<p><b>Request Method</b>: ", os.environ['REQUEST_METHOD']
print "<p><b>Query String</b>: ", os.environ['QUERY_STRING']
print "</body>"
print "<html>"



The Source Code is Available Here: Bernardo HTTPD Source Code.

Monday, April 13, 2009

Qt4 Xml Object Mapper

I'm looking at Google App Engine, to realize my Web Services (Obviously with Python). Web Service Response are generally in XML, and in the 90% of the case you'll need to map Xml Response with your Objects.
I've written a simple class that allows you to handle this task in a easy way, and with a quite good flexibility.


class TestObject : public QObject {
Q_OBJECT

Q_PROPERTY(QString surname READ surname WRITE setSurname)
Q_PROPERTY(QUrl website READ website WRITE setWebSite)
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(int age READ age WRITE setAge)

...
};


The First step is writing Objects that inherit from QObject and adding your properties. The Mapper uses the introspection to assign the values.

Mapping and Introspection: Maybe you don't like the Xml Node Name as your property's name, in this case you can use the HashMap that allows you to say "Hei, the TagName 'A' is the property 'foo'!". There's also a protected virtual method called convertData that tries to covert Xml Node Text Value to your property's type, take a look at this example.


QString xml = "<personInfo>"
"<age>21</age>"
"<personName>Matteo</personName>"
"<surname>Bertozzi</surname>"
"<personWeb>http://th30z.netsons.org/</personWeb>"
"</personInfo>";

THXmlHashMap dataMapping;
dataMapping.insert("personName", "name");
dataMapping.insert("personWeb", "website");

TestObject obj;
THXmlMapper xmlMapper(&obj);
xmlMapper.setMapping(dataMapping);
xmlMapper.map(xml);
qDebug() << obj.name() << obj.surname() << obj.age() << obj.website();



Source Code is Available Here: Qt4 Xml Object Mapper.

Saturday, April 11, 2009

Qt/Cocoa DataStream (Binary Communication)

In a time of REST protocols... I still love the Binary Communication. I don't have much ideas this period, I need to find a different job (C# doesn't fit my code necessity). The Example Source code, contains two Folder. One is the Qt4 TcpServer the second one is the ugly application that you can see below :)

Note: This example doesn't have anything related to the Qt 4.5 Cocoa Support.

Run the Qt4 Server, and the Cocoa Application (Remember to change the SERVER_HOST in AppController.m) and try to send some binary data. The Qt Server will receive this data it will resend you. Protocol is Very easy 1 byte of Data Type (Int8, Int16, ..) and Data. Remember that Intel arch is Little Endian.

Note: This is just a "Draft" a "non complete" example only to give the idea on how it works.

The Source Code is available here: Qt/Cocoa DataStream Source Code.

Qt4 PageFlow

Just another example that I don't have finished last Sunday. This is a simple widget that tries to be similar at the iPhone Mobile Safari Tabs Page. It's a really nice concept used also by Palm Pre to display the running apps. To switch  item swipe left or right (Press Mouse Button, Move mouse in a specified direction and Release it).

Source code is available here: Qt4 PageFlow Source Code.

Sunday, April 5, 2009

Qt4 CoverFlow and QThreadPool

My OpenMoko cannot stay without CoverFlow, so here some code. But I need a lightweight class that allows me to load all files in a directory or a list of files. Scanning directory with QDir entryList can take long time, and loading all the images can take much more, So what I need is a class that solve this problem internally.

I've choose the way of QRunnable and QThreadPool to solve this problem, so I've a class that execute QDir EntryList and another one that load an Image. When file is Ready (FileName, Path) a gray square is displayed and will be replaced by the Image once it is fully loaded and scaled. Using this method you can flow between files even if CPU and Disk are still loading to load images, this means No UI Freeze when CoverFlow starts.

Note 1: You can flow between images using Left and Right Key or Clicking with mouse at the Left or the Right of the Central one.
Note 2: If you want a CoverFlow with a great transition effect take a look at Ariya's PictureFlow.

The Source code Is Available Here: Qt4 CoverFlow Source Code.

Saturday, April 4, 2009

Qt4 Photos Preview

After a great start of the year, working on B*Tree and other Indexing Data Structure, it's about two month that I'm experimenting with User Interface... My Love still remains Networking and File-Systems but it's fun drawing images, shadows and UI Components.

Ok, Networking and Bytes can wait till next week. Today I've watched the PALM Pre Preview, No Back buttons, No Save buttons touch capability outside the glass... Data Abstraction... It's really nice.

But, There are so much things... so I've extracted a tiny nice one. A Nice way to display a "Photo Folders". You can customize the output a bit, Shadow, Photo Size, Second and Third Photo Offsets, but it's an example not a reusable class...

You can find the Source Code Here: Qt4 Photos Preview Source Code.

QtCentre Contest 2008 a Nice Surprise...

Backing home yesterday, I've found a postal package from QtCentre, there's also a QtCentre T-Shirt but this raining day doesn't permit to have great photos.

I would like to thanks again, all the QtCentre, Contest Sponsors (ICS, KDAB, BitRock, Thorsen, ...) and the "Trolltech" Team, for this, for the OpenMoko, and the incredible jobs they do!

Saturday, March 28, 2009

iPhone: Download and Display Gravatar

Back to the real iPhone for a while... Gravatar, or globally recognized avatar, is an interesting free service. It can be integrated with AddressBook app or other apps that can have a picture related to email address. Here an Objective-C Example to retrive the Gravatar. It's really simple!

The Source Code is Available Here: iPhone Gravatar Example.

The Apple Worldwide Developers Conference (WWDC) takes place June 8-12, 2009 held at Moscone Center West in San Francisco. http://developer.apple.com/WWDC/.

Qt4 iPhone Like App Prefs

Here a simple example on How to Customize an ItemView class, in this case a QTreeView, to be similar to the iPhone Application Preferences Panel.

All the look'n' feel magic is provided by the ItemDelegate that paint the right object using the specified type.

There're six different item types: Button, Link, Group, Value, Multi-Value, Info. Values are all string except boolean that are painted as On/Off Button. Double Tap on this item to change is value. For all the others item when you click on it a right event will be dispatched, and you'll have to handle it to load the right "Edit" page.

This is Just an Example, to use in an application you need, at least, to differentiate the Display Role Value and the real KeyName value.

The Source Code is Available Here: Qt4 iPhone Like App Prefs Source Code.

Tuesday, March 24, 2009

Qt4 Drawing Notification Badges

Wow a Couple of Minutes of Free Time, and here two lines of code example to answer at Dave's question "How to Draw iPhone Like Notification Badges".

Badges are used olso in Mac OS X in application like iTunes and in the DockBar, check this post "Cocoa Notification Badge" to see how to use it with cocoa.

Obviously Notification Badges will be a features of My OpenMoko Apps.

The Example is very simple, there's a method that draws the badge with specified text and Brush, you can put the badge where you want not only on top left as showed in the picture :)

The Source Code is Available here: Qt Draw Badges Source Code.

Sunday, March 22, 2009

OpenMoko: My Phone, Video Preview

We're gonna show you some of future plans. Before that, let me remind you of where we're at with the iPhone. (Greg Joswiak, March 2009 Apple Event)

Ok, the iPhone 3.0 is here (ok, still beta). There're some great features like the Push Notification Service, P2P networking capabilities, Hardware Access and so on... but for us? poor Linux developers?

Previously showed in this post OpenMoko "My iPhone", I'm working to make my Neo Freerunner similar to the iPhone. Yesterday I've switched to QtEmbedded 4.5 for Applications that doesn't require media or phone content, unfortunatly QtEmbedded doesn't have Phonon support.

Till now (Just 3 'days' of development), I've implemented some of the Touch Screen gesture, like sweep, scroll, double tap, zoom, rotation... and others nice features with the accelerometer like Shake and Screen orientation, Normal or Landscape automatically enabled without writing a line of code.

Now there's one more thing I want to show you, a video preview of my OpenMoko.


One more thing "Freerunner freely runs Gentoo", Gentoo Team have reached the first milestone for running Gentoo on the Freerunner.  http://gentoo.mindzoo.de


I'm still an Apple iPhone Fan, but developing OpenMoko with Qt is fantastic! Thanks Trolls!

Sunday, March 15, 2009

OpenMoko: My "iPhone"

No Code Post Yesterday, No Code Post Today.

But for those that doesn't follow my Tweets, Yesterday I've updated the Cocoa SQLite Wrapper to support the NULL value.

I had in plan to post an Example of "Qt Animation", Moving Objects along a path, something like CoverFlow or other Effects. But my Moko needs to be more usable, and needs an iPhone like UI.

Sunday, March 8, 2009

Cocoa: Sidebar with Badges, Take 2

Do you remember the Cocoa Sidebar? No, Take a Look at this post Cocoa Sidebar with Badges.

Joel asked me to revise the Sidebar, allowing to add/remove and do other operation at any time.

I've rewritten all the code of the Sidebar, and I've added a couple of new features, like the default action handler and obviously the ability to add, remove items and badges at any time.

All the past features, like Drag & Drop are still present, but there's something else to do to improve it. If You've suggestions, patches or something else post a comment or send me a mail!

The Source Code is Available Here: Cocoa Sidebar 2 Source Code.

Update 10 March 2008 - Source Updated with Fixes.

Saturday, March 7, 2009

OpenMoko: NEO QtExtended Accelerometer

QtExtended doesn't have an accelerometer class, so I've decided to Write my on class with a simple Example. A Spot that moves around X and Y Axis using Accelerometer Information.

The Second NEO Freerunner Sensor, in contrast to the first sensor  is turned 45 degrees around the Z axis. See the attached image to get a clue about its orientation.

The information from both of the accelerometers is exported through two different input event based file mappings. These device nodes can be found at /dev/input/event2 and /dev/input/event3.

The QAccelerometer Class emit an Event called accelerate(qreal x, qreal y, qreal z) that gives you X, Y, Z axis values.

Each acceleration event relays the current acceleration readings along the three axes of the device. Therefore, a value of 1.0 represents a load of about +1g along a given axis while a value of -1.0 represents -1g.

You can find More information about OpenMoko Accelerometer here "Accelerometer Data Retrieval" and "Accelerometer Technical Fundamentals".
Keep in Mind this Simple Table of X, Y,  Z axis and Phone State:
( 0,  0,  1) = Front
( 0,  0, -1) = Back
( 1,  0,  0) = Vertical (Short Side), Right
(-1,  0,  0) = Vertical (Short Side), Left
( 0, -1,  0) = Vertical (Long  Side), Front
( 0,  1,  0) = Vertical (Long  Side), Back

The Source Code is Available Here: NEO QAccelerometer Test Source Code.

Qt4: Flickr and QtConcurrent

A couple of days ago, I've filled up a Qt Questionnaire and I've seen a couple of subjects that I need to revise. So, Here an Example of Flickr Downloader using QtConcurrent, High Level Network Operations (QNetworkManager), QGraphicsView and QDomElement.



The Flickr Service Class implements, only a couple of Methods. Request of Recently added and Interesting Photos, and the Search Photos Methods.

The Source Code is Available Here: QFlickr Test Source Code. (You Must Set your Flickr Key!)

PS: Starting Today, All the Qt4 Examples/Libraries will be released under LGPL license while the Cocoa Examples/Libraries will be released under BSD license.

Sunday, March 1, 2009

Qt4 Black Bar and Buttons

Today I've written a couple of Widgets for my next Qt4 Application. And below you can see an Example of UI using Two widget, the BlackBar and the BlackButton.

The BlackBar looks like the iTunes bar of Podcast page. Is something like a TabBar. The Black Buttons has a SetRadius Methods that allow you to modify the Button Shape.


The Source Code is Available Here: Qt4 THLibrary Preview Source Code.

Saturday, February 28, 2009

Cocoa: Drag & Drop

Today a simple example of Drag & Drop with Cocoa and NSView. The screenshot below shows two groups. In the first one, you can drop the photos on your filesystem, taken from Desktop or Finder. In the second group, you can only drop the first group image.

You can find the source code here: Drag & Drop Test Source Code.