Showing posts with label application. Show all posts
Showing posts with label application. Show all posts

Saturday, February 1, 2014

Handling GamePad events in BB10 Cascades App

I added GamePad support to my CrazyFlight game for BB10. You can see demo here.



In this post I will describe, how we can add GamePad support to BB10 cascades or Qt app.

First we should add use_gamepad permission to bar-descriptor.xml file. This is not necessary to enable gamepad support but its necessary for AppWorld to detect that your game supports GamePad, this helps in app discovery process.
 <permission>use_gamepad</permission>
We should also add libscreen dependency to our .pro file.
LIBS += -lscreen
As far as I know there is no Cascades API for handling GamePad events, we need to rely on native API to get GamePad events. I created a Helper class that handles Native API call back and send events to Cascades QML items.

Here is definition of my helper class's (GamePadObserver.h) header file.
#ifndef GAMEPADOBSERVER_H_
#define GAMEPADOBSERVER_H_

class GamePadObserver: public QObject {
 Q_OBJECT
 Q_ENUMS(GamePadButton)

 // Structure representing a game controller.
 struct GameController {
  // Static device info.
  screen_device_t handle;
  int type;
  int analogCount;
  int buttonCount;
  char id[64];

  // Current state.
  int buttons;
  int analog0[3];
  int analog1[3];

  // Text to display to the user about this controller.
  char deviceString[256];
 };

public:
 //Enum which we will use to send signal when GamePad event is detected
 enum GamePadButton{
   A_BUTTON=0,
   B_BUTTON,
   C_BUTTON,
   X_BUTTON,
   Y_BUTTON,
   Z_BUTTON,
   MENU1_BUTTON,
   MENU2_BUTTON,
   MENU3_BUTTON,
   MENU4_BUTTON,
   L1_BUTTON,
   L2_BUTTON,
   L3_BUTTON,
   R1_BUTTON,
   R2_BUTTON,
   R3_BUTTON,
   DPAD_UP_BUTTON,
   DPAD_DOWN_BUTTON,
   DPAD_LEFT_BUTTON,
   DPAD_RIGHT_BUTTON,
   NO_BUTTON
 };

public:
 GamePadObserver(QObject* parent = 0);
 virtual ~GamePadObserver();

 //Main event loop should send event to this handler if it can not handle event by itself
 //This handler will try to handle event if its related to GamePad
 void handleScreenEvent(bps_event_t *event);

signals:
        //Signals will be emitted when Gamepad events is detected
 void buttonReleased(int button);
 void buttonPressed(int button);

private:
 //Helper methods to discover the GamePad and device connection
 void discoverControllers();
 void initController(GameController* controller, int player);
 void loadController(GameController* controller);
 void handleDeviceConnection(screen_event_t screen_event);
       
 // Methods to handle gamepad events
 void handleGamePadInput(screen_event_t screen_event);
 QString gamePadButtonAsString(GamePadButton button);

private:
 screen_context_t _screen_ctx;
 GameController _controllers[2];
 bool _conneted;
 GamePadButton _lastButton;
};
#endif /* GAMEPADOBSERVER_H_ */
Now let's see source file.
In constructor we are creating screen context and then trying to discover if there is GamePad connected to device already.
#define SCREEN_API(x, y) rc = x; \
    if (rc)  printf("\n%s in %s: %d, %d", y, __FUNCTION__,__LINE__, errno)

GamePadObserver::GamePadObserver( QObject* parent)
: QObject(parent),_screen_ctx(0),_conneted(false)
{
 // Create a screen context that will be used to create an EGL surface to receive libscreen events.
 SCREEN_API(screen_create_context(&_screen_ctx, SCREEN_APPLICATION_CONTEXT), "create_context");
 discoverControllers();
}

void GamePadObserver::discoverControllers()
{
    // Get an array of all available devices.
    int deviceCount = 0;
    SCREEN_API(screen_get_context_property_iv(_screen_ctx, SCREEN_PROPERTY_DEVICE_COUNT, &deviceCount), "SCREEN_PROPERTY_DEVICE_COUNT");
    screen_device_t* devices = (screen_device_t*) calloc(deviceCount, sizeof(screen_device_t));
    SCREEN_API(screen_get_context_property_pv(_screen_ctx, SCREEN_PROPERTY_DEVICES, (void**)devices), "SCREEN_PROPERTY_DEVICES");

    // Scan the list for gamepad and joystick devices.
    int controllerIndex = 0;
    for (int i = 0; i < deviceCount; i++) {
        int type;
        SCREEN_API(screen_get_device_property_iv(devices[i], SCREEN_PROPERTY_TYPE, &type), "SCREEN_PROPERTY_TYPE");

        if ( !rc && (type == SCREEN_EVENT_GAMEPAD || type == SCREEN_EVENT_JOYSTICK)) {
            // Assign this device to control Player 1 or Player 2.
            GameController* controller = &_controllers[controllerIndex];
            controller->handle = devices[i];
            loadController(controller);

            // We'll just use the first compatible devices we find.
            controllerIndex++;
            if (controllerIndex == MAX_CONTROLLERS) {
                break;
            }
        }
    }
    free(devices);
}
On destructor we should release screen context.
GamePadObserver::~GamePadObserver()
{
 screen_destroy_context(_screen_ctx);
}
loadController setup our GameController structure, that we will use to store currently pressed buttons while handling the events.
void GamePadObserver::loadController(GameController* controller)
{
    // Query libscreen for information about this device.
    SCREEN_API(screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_TYPE, &controller->type), "SCREEN_PROPERTY_TYPE");
    SCREEN_API(screen_get_device_property_cv(controller->handle, SCREEN_PROPERTY_ID_STRING, sizeof(controller->id), controller->id), "SCREEN_PROPERTY_ID_STRING");
    SCREEN_API(screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_BUTTON_COUNT, &controller->buttonCount), "SCREEN_PROPERTY_BUTTON_COUNT");

    // Check for the existence of analog sticks.
    if (!screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG0, controller->analog0)) {
     ++controller->analogCount;
    }

    if (!screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG1, controller->analog1)) {
     ++controller->analogCount;
    }

    if (controller->type == SCREEN_EVENT_GAMEPAD) {
        sprintf( controller->deviceString, "Gamepad device ID: %s", controller->id);
        qDebug() << "Gamepad device ID" <<  controller->id;
    } else {
        sprintf( controller->deviceString, "Joystick device: %s", controller->id);
        qDebug() << "Joystick device ID" <<  controller->id;
    }
}
handleScreenEvent function should be called from main event loop when event is related to screen domain. This function check if event type is GamePad device connection or its GamePad button event and handle it accordingly.
void GamePadObserver::handleScreenEvent(bps_event_t *event)
{
    int eventType;

    screen_event_t screen_event = screen_event_get_event(event);
    screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TYPE, &eventType);

    switch (eventType) {
        case SCREEN_EVENT_GAMEPAD:
        case SCREEN_EVENT_JOYSTICK:
        {
         handleGamePadInput(screen_event);
         break;
        }
        case SCREEN_EVENT_DEVICE:
        {
         // A device was attached or removed.
         handleDeviceConnection(screen_event);
         break;
        }
    }
}
handleDeviceConnection handles GamePad device connection. If it detects new connection then it loads new device, in case of device disconnection it remove device.
void GamePadObserver::handleDeviceConnection(screen_event_t screen_event)
{
    // A device was attached or removed.
    screen_device_t device;
    int attached;
    int type;

    SCREEN_API(screen_get_event_property_pv(screen_event, SCREEN_PROPERTY_DEVICE, (void**)&device), "SCREEN_PROPERTY_DEVICE");
    SCREEN_API(screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_ATTACHED, &attached), "SCREEN_PROPERTY_ATTACHED");

    if ( attached ) {
        SCREEN_API(screen_get_device_property_iv(device, SCREEN_PROPERTY_TYPE, &type), "SCREEN_PROPERTY_TYPE");
    }

    int i;
    if (attached && (type == SCREEN_EVENT_GAMEPAD || type == SCREEN_EVENT_JOYSTICK)) {
        for (i = 0; i < MAX_CONTROLLERS; ++i) {
            if (!_controllers[i].handle) {
                _controllers[i].handle = device;
                loadController(&_controllers[i]);
                break;
            }
        }
    } else {
        for (i = 0; i < MAX_CONTROLLERS; ++i) {
            if (device == _controllers[i].handle) {
                initController(&_controllers[i], i);
                break;
            }
        }
    }
}

void GamePadObserver::initController(GameController* controller, int player)
{
    // Initialize controller values.
    controller->handle = 0;
    controller->type = 0;
    controller->analogCount = 0;
    controller->buttonCount = 0;
    controller->buttons = 0;
    controller->analog0[0] = controller->analog0[1] = controller->analog0[2] = 0;
    controller->analog1[0] = controller->analog1[1] = controller->analog1[2] = 0;
    sprintf(controller->deviceString, "Player %d: No device detected.", player + 1);
}
handleGamePadInput function that handles GamePad events.
void GamePadObserver::handleGamePadInput(screen_event_t /*screen_event*/)
{
    int i;
    for (i = 0; i < MAX_CONTROLLERS; i++) {
        GameController* controller = &_controllers[i];

        if ( controller->handle ) {
            GamePadButton gamePadButton = NO_BUTTON;

            // Get the current state of a gamepad device.
            SCREEN_API(screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_BUTTONS, &controller->buttons), "SCREEN_PROPERTY_BUTTONS");

            if (controller->analogCount > 0) {
             SCREEN_API(screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG0, controller->analog0), "SCREEN_PROPERTY_ANALOG0");
            }

            if (controller->analogCount == 2) {
             SCREEN_API(screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG1, controller->analog1), "SCREEN_PROPERTY_ANALOG1");
            }

            for(int i = A_BUTTON ; i < NO_BUTTON ; ++i) {
             if( controller->buttons & (1 << i) ) {
              gamePadButton = (GamePadButton)(i);
              break;
             }
            }

            if( gamePadButton == NO_BUTTON ) {
             emit buttonReleased( _lastButton );
             _lastButton = NO_BUTTON;
            }
            else if( _lastButton != gamePadButton ) {
             emit buttonReleased(_lastButton);
             emit buttonPressed(gamePadButton);
             _lastButton = gamePadButton;
            }
        }
    }
}
Now we have all necessary implementation to handle the GamePad connection and GamePad button events. But we should pass events related to GamePad to our helper class when we receive it in our main event handler. To do that, In our main function we should register main bps event loop or filter as below and can use GamePadObserver as described.
#include "GamePadObserver.h"

static QAbstractEventDispatcher::EventFilter previousEventFilter = 0;
static GamePadObserver _gamePadObserver;

static bool bpsEventFilter(void *message)
{
    bps_event_t * const event = static_cast(message);

    if( event && bps_event_get_domain(event) == screen_get_domain()) {
     _gamePadObserver.handleScreenEvent(event);
    }

    if (previousEventFilter)
        return previousEventFilter(message);
    else
        return false;
}

int main(int argc, char **argv)
{
    // Register GamePadObserver so we can use it in QML code
    qmlRegisterUncreatableType("GamePadObserver", 1, 0,"GamePadObserver", "");

    QApplication app(argc, argv);

    previousEventFilter = QAbstractEventDispatcher::instance()->setEventFilter(bpsEventFilter);

    QScopedPointer view(new QDeclarativeView());
    view->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    view->setResizeMode( QDeclarativeView::SizeRootObjectToView );

    QDeclarativeContext *ctxt = view->rootContext();
    view->setSource(QUrl("app/native/assets/main.qml"));

    ctxt->setContextProperty("GamePad",&_gamePadObserver);
    view->showFullScreen();

    return app.exec();
}
And finally, out GamePadObserver class is ready to deliver GamePad events. To handle GamePad events in QML you can use GamePadObaserver class as below.
        
        Connections{
            target: GamePad
            onButtonPressed: {
                                
                if(button == GamePadObserver.DPAD_UP_BUTTON
                || button == GamePadObserver.DPAD_DOWN_BUTTON ){
                    handleUpButton();
                }else if(button ==  GamePadObserver.DPAD_LEFT_BUTTON 
                || button ==  GamePadObserver.DPAD_RIGHT_BUTTON) {
                    handleLeftButton();
                }          
                else if(button == GamePadObserver.MENU1_BUTTON                 
                || button == GamePadObserver.MENU2_BUTTON
                || button == GamePadObserver.X_BUTTON
                || button == GamePadObserver.Y_BUTTON 
                || button == GamePadObserver.A_BUTTON 
                || button == GamePadObserver.B_BUTTON ) {
                    handleButtonSelection();
                } 
            }        
        }
So, I hope this will help to utilize GamePad events in your games.

Friday, August 30, 2013

Ubuntu Touch Calendar prototype for new design


Lately I am working on Ubuntu Touch's Calendar core app. Recently I tried to create a prototype for calendar to show how new design looks for the app.

Here if demo on youtube.



And following are few snaps from prototype.






Friday, June 21, 2013

Inviting Application Review from Application in BB10 using Cascades API

Most time people leave a review for application when they are unhappy but if they are happy with your app, Chances are high that they will ignore the review. And this might leave impression on App World that your application if not working fine and is of low quality.

To overcome this we might offer user a option to review application from within application and some user might be happy enough to provide review.

BB10 has nice QML Cascades API, which makes the task very easy. Only few lines of code and you can have option to offer review from application.

Following is the code which I am using. You can use InvokeActionItem, with actions property of Page. "sys.appworld" this is invocation target id for App World. And in URI you need to mention your application's ID, which you can find from App World.
Page {
    ...
    actions: [
        ...
        InvokeActionItem {
            title: "Rate Application"
            ActionBar.placement: ActionBarPlacement.InOverflow
            imageSource: "rate.png"
            query {
                invokeTargetId: "sys.appworld"
                invokeActionId: "bb.action.OPEN"
                uri: "appworld://content/20200034"
            }
        }
        ...
    ]
    ...
}


Sunday, April 14, 2013

Audiobook Reader for Ubuntu-Touch

I have been exploring and working on Ubuntu-Touch for some time now. I have wrote some QML code for official Ubuntu-Touch calendar app and mean time I was also working on porting my Audiobook Reader application. This porting exercise helped me to understand how mature SDK is and also helped me to learn the SDK.

There were some minor issue with Ubuntu-Touch SDK, but nothing serious that can affect the work. As per Ubuntu-Touch development guideline, they prefer QML/Javascript and suggest to avoid C++ code as much as possible. This will help to make sure most of application is compatible for most Ubuntu platform. I tried to follow guideline and tried to not use C++ till now for app. I found myself missing C++ now and then, sometimes there are plugins that we can use instead and sometime there is no alternative. Mostly I missed the File IO, surely SDK team will come up with something, but till now there is no solution.

Anyway, I did not faced any major issue and was able to create initial version of Audiobook Reader quite easily without much problem. Following is demo.


Thursday, April 4, 2013

Accessing Amazon AWS service from QML/Javascript

Sometime back I published a post that shows how to access Amazon Web Service using Qt. You can find original post here. Now that trend is to code everything from QML and Javascript ( at-least Ubuntu Touch is following that path to make it as device independent as possible), I tired to access AWS service from using pure QML and Javascript.

I required to use external Crypto library for HMACSHA1 algorithm but everything else can easily be done with pure QML/Javascript.

Following is code i used for downloading Book cover image from Amazon AWS.

First all to communicate with AWS you required to have AWS access key id and Secret Access key. You can get it from here. I am also importing the Crypto library, for using HmacSHA1 implementation. I am using crypto-js Library. You can download required the same from here.

.import "JSLib/rollups/hmac-sha1.js" as Crypto

//key and password, required to sign the request using HMACSHA1
var AWS_KEY = "KEY";
var AWS_PASS = "PASSWORD";
var END_POINT = "http://ecs.amazonaws.com/onca/xml";
var AWS_TAG = "TAG"

Now we have required information, we can are ready to create request. In following code, I am putting all required parameter in a map and then using it to create signature and URL. We also need to encode parameter, I am using encodeURIComponent for encoding required parameter.
function downloadCover( author,bookName,callback) {

    var queryItems = {};
    queryItems["AWSAccessKeyId"] = AWS_KEY;
    queryItems["AssociateTag"] = AWS_TAG;
    queryItems["Author"] = encodeURIComponent(author);
    queryItems["Keywords"] = encodeURIComponent(bookName);
    queryItems["Operation"] = "ItemSearch";
    queryItems["ResponseGroup"] = "Images";       
    queryItems["SearchIndex"] = "Books";
    queryItems["Service"] = "AWSECommerceService";
    queryItems["SignatureMethod"] = "HmacSHA1";
    queryItems["Timestamp"] = encodeURIComponent( new Date().toISOString());
    queryItems["Signature"] = createSignature(queryItems);


    var downloadUrl = createUrl(queryItems);
    sendNetworkRequest(downloadUrl,callback);
}
Following is code for creating signature. Creating signature is the only tricky part to make code works as expected. I am using HmacSHA1 from Crypto-JS lib. This function return WordArray object, which can be converted to HEX string, binary string or base64. Once we have HmacSHA1 hash of request, we need to convert it to Base64. I was not able to use base64 function from Crypto-JS library due to some error. I decided to copy base64 function from library directly to my js file and use it. Then finally we need to encode this base64 output, which we can be used as signature while sending request.
function createSignature(queryItems) {
    var strToSign = "GET\n";
    strToSign += "ecs.amazonaws.com\n";
    strToSign += "/onca/xml\n"

    for( var prop in queryItems ) {
        if( prop === "Signature") {
            continue;
        }

        strToSign += ( prop+"="+ queryItems[prop]);
        strToSign += "&"
    }
    //removing last &
    strToSign = strToSign.slice(0,strToSign.length-1)


    var signature = Crypto.CryptoJS.HmacSHA1(strToSign, AWS_PASS);
    signature = base64(signature);

    return encodeURIComponent(signature);
}

Now we are almost done, all we need to do is to use created signature and make HTTP request. Following code shows how. There is nothing new here. I am creating complete URL from all required parameter and making request using this URL by XMLHttpRequest object.

function createUrl(queryItems )
{
    var url = END_POINT+"?";

    for( var prop in queryItems ) {
        url += ( prop+"="+ queryItems[prop]);
        url += "&"
    }
    //removing last &
    url = url.slice(0,url.length-1);
    return url;
}

function sendNetworkRequest(url,callback) {
    var http = new XMLHttpRequest();
    http.onreadystatechange = function() {
        if (http.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
            console.log("Headers -->");
            console.log(http.getAllResponseHeaders ());
            console.log("Last modified -->");
            console.log(http.getResponseHeader ("Last-Modified"));

        } else if (http.readyState === XMLHttpRequest.DONE) {
            console.log(http.responseText);
            callback(http.responseText);
        }
    }

    http.open("GET", url);
    http.send();
}

Friday, March 1, 2013

Using LocalStorage API from javascipt in QML application

Recently I needed to create database from QML application on which I am working. I wanted to separate database related code from QML and created javascript file to handle database related work. I had to struggle a little to make storage API work from javascript, below are my findings.

As you might already know to use sqllite database in QML you will need to import LocalStorage API.
import QtQuick.LocalStorage 2.0 as Sql
This will work for QML but if you want to use it from javascript then you will need to use following syntax.
.import QtQuick.LocalStorage 2.0 as Sql
Now you should be able to use LocalStorage API in javascript. LocalStorage related API can be accessed by using LocalStorage object and we imported LocalStorage module as Sql, we will need to use access LocalStorage object from Sql scope. Like below.
var db = 
   Sql.LocalStorage.openDatabaseSync("TestDB", "1.0", "Description", 100000);
Now you can use this db object to create table and select values from it just like you do in QML. Following is sample example.
function getDatabase() {
     var db = 
     Sql.LocalStorage.openDatabaseSync("TestDB", "1.0", "Description", 100000);

     //create table
     db.transaction(
        function(tx) {    
var query="CREATE TABLE IF NOT EXISTS TEST(Id INTEGER PRIMARY KEY, Title TEXT)";                   
            tx.executeSql(query);
      });

     return db;
}

function printValues() {

    var db = getDatabase();
    db.transaction( function(tx) {
        var rs = tx.executeSql("SELECT * FROM TEST");
        for(var i = 0; i < rs.rows.length; i++) {
            var dbItem = rs.rows.item(i);
            console.log("ID:"+ dbItem.Id + ", TITLE:"+dbItem.Title);
        }
    });
}

Thursday, November 15, 2012

Creating a simple "Color Match" game for Windows Phone

I created a article for Forum Nokia. Article is How to guide for creating a vary simple game using Visual C# and XAML for Windows Phone.

I am still learning WP development so content is vary basic. I am also planning to publish this game vary soon on Windows phone store.

Please find the article here. Article shows How to create basic menu screen, How to achieve navigation between different screen, how to use XAML to create geometry, How to achieve opacity animation, How to change image dynamically and How to use isolated storage for persistence.

Followings are few snapshots from application.




Friday, November 9, 2012

Porting Qt app to BlackBerry 10 SDK

Recently BB10 device is getting in to news for its Qt framework support. I got curious about it and decided to port my Harmattan Qt app to BB10 device. First of all I am glad that finally there will be a real main stream device that will support Qt as development framework.

After installing BB10 NDK and going through few sample application I realized that I need to create BlackBerry Cascades C++ project using its QNX Momentics IDE event though I just wanted to create plain Qt application. So I created the Cascades C++ project and merged my existing Qt App's code to BB10 project.

I was aware that in order to run the application I need to change Harmattan component used in QML to standard QML component but I wanted to check debugging support provided by Momentics IDE to debug Qt cpp code and QML code. So I started application and I was staring at while screen with no error message in console of IDE and seems like there is no support to debug QML code or Java script code. I added few debug message to identify problem but still did not see any message in console. I still don't know how to see those debug log from Qt app in BB10. I think there must be some installation problem.

In addition to this debug log problem, Its emulator is not working in normal mode on my HP Elitebook 6930p laptop with Ubuntu as OS. I always have to run it in safe mode.  While running it in Safe mode, I faced another major problem. The emulator spill out of my laptop's 15 inch screen. Default emulator resolution is so big, I have to scroll a lot to see the whole screen of device. It seems that controller utility provided with emulator is not supposed to work when emulator is running in safe mode. This is so discouraging. However I decided continue my porting effort.

So no debug log and huge emulator that my 15 inch laptop can not contain, I decided to first try to run my application using Qt Desktop version and once application is working fine on desktop Qt SDK. I merged my code back to BB10 project.

I needed to make some minor change relate to path before I can see anything running. In BB10, Qt application locate images and QML file in assets folder not from Qt's Resource file. So I made necessary changes to use Image and QML file from Assets folder. Actually you can specify where your image files and QML files are present in bar-descriptor.xml but I am using default assets folder only.

Following is how you can show QML file located in assets folder using QDeclarativeView.

    QScopedPointer view(new QDeclarativeView());
    view->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    view->setResizeMode( QDeclarativeView::SizeRootObjectToView );
    view->setSource(QUrl("app/native/assets/main.qml"));
    view->showFullScreen();

So after this I was able to see my application in emulator. But my application was supported in landscape mode only so I need to make change to make it launch in landscape mode only. To make application support either Portrait or Landscape mode, you need to set aspectRatio tag in bar-descriptor.xml, and to disable auto orientation change you can set autoorients tag to false

Following is my entry into bar-descriptor.xml
    
<initialwindow>
    <aspectratio>landscape</aspectratio>
    <autoorients>false</autoorients>
    <systemchrome>none</systemchrome>
    <transparent>false</transparent>
</initialwindow>

So now my plain Qt Application is running fine in emulator, but my application keeps running even after its minimized. I realized that I need to capture BPS Event in order to detect application minimize and maximize event. I found good information here for this purpose.

Following is my code to detect application minimize event so I can pause my application.

static QAbstractEventDispatcher::EventFilter previousEventFilter = 0;

static bool bpsEventFilter(void *message)
{
    bps_event_t * const event = static_cast<bps_event_t>(message);

    if (event && bps_event_get_domain(event) == navigator_get_domain()) {
        const int id = bps_event_get_code(event);

		//unsigned int code = bps_event_get_code(event);
		switch ( id ) {

		case NAVIGATOR_WINDOW_INACTIVE:
		   qDebug() << "INFO: Window inactive";
		   break;

		case NAVIGATOR_WINDOW_ACTIVE:
		   qDebug() << "INFO: Window active";
		   break;

		case NAVIGATOR_WINDOW_STATE:
		   navigator_window_state_t state = navigator_event_get_window_state(event);
		   if (state == NAVIGATOR_WINDOW_FULLSCREEN) {
			   qDebug() << "INFO: Resume game";
		   } else {
			   qDebug() << "INFO: Pause game";
			   Utils::instance()->PauseGame();
		   }
		   break;
		}
    }

    if (previousEventFilter)
        return previousEventFilter(message);
    else
        return false;
}

This is how you add event handler in main function.
 previousEventFilter = QAbstractEventDispatcher::instance()->setEventFilter(bpsEventFilter);
So After all this my porting activity is almost complete. Now I need to learn how to submit application to BB10 store. Let's see how that goes.  So overall I feel BB10 provides nice Qt support for app development, emulator support needs to be improved though to be considered as useful ( at lest in my case).

Saturday, July 7, 2012

Crazy Chickens game with Motion detection

Past some time I was working on update of my application Crazy Chickens for N9.

In new version, Game character recognizes gesture based on user motion and move his bucket accordingly to catch egg. Game uses the phone back camera to capture image and recognizes gesture by tracking motion of some predefined colored object, which user is holding and moving to move the character. Hope you will enjoy the new update.

There also some minor update in UI and game logic to make game more enjoyable.

You can download app from following link,
- Fixed web browser: http://store.nokia.com/content/200523
- Nokia mobile browser: http://store.ovi.mobi/content/200523


Game need some setup before you play the game, You will need to connect phone to TV using TV out cable and place phone such that it back camera faces you. Game can recognized four color, Red, Blue, Yellow and Green. You need to choose one color and hold that colored object in hand. To move character to put bucket under hen, you need to move colored object in direction of hand. 


Please also make sure that you are fully visible and color object's movement does not go out of camera frame. Also make sure that there is enough light in room else game might has problem recognizing color clearly.

If you don't have TV out cable then you can install VNC server on Phone and connect it from PC to project phone's screen on PC.

Hope you will like the update. Please let me know if you have any feedback. I will try to update game with your feedback.

Friday, December 23, 2011

Crazy Flight a classic helicopter game now available on N9 Harmattan

I created this game - Crazy Flight, when I was on vacation in india, to please my nephew, so he can play on my phone and I can work on my computer.

Game is created using QML and C++ and backend and works on N9/N950 Harmattan plaform. Well programing did not take much time but creating graphics and polishing it took a while and around a week time I was able to publish this game on Ovi store for N9.

Game is vary simple to play,  you have to touch on screen to make plane go up and release touch to go down and avoid obstacle which may come.

You can download this game from Ovi store here. It free game with Ads.
Mobile link is here.


Here are few snapshot from game. If you have any comments I am glad to have those.





Friday, December 9, 2011

Using QDeclarativeImageProvider to load QPixmap to QML Image element

Recently for my mobile application, I required cache image from network and use that in QML application. Prior to caching, I was using WebView element to show image from network, but I needed to show that image multiple places, to avoid multiple network request I decided to prefetch network image and show that using Image element.

To make it work, I downloaded network image to QPixmap using QNetworkAccessManager and then used QDeclarativeImageProvider to provide cached QPixmap to Image element.

As per documentation "The QDeclarativeImageProvider class provides an interface for supporting pixmaps and threaded image requests in QML."  I also used it as proxy image provider. When actual Image data is not available my image provider class will provide some dummy image and when actual data is available it will provide actual image data.

Following is my code for my custom image provider derived from QDeclarativeImageProvider.

In following code, by providing QDeclarativeImageProvider::Pixmap as ImageType, I am saying I will povide QPixmap as Image type and in this case requestPixmap API will be called by declarative engine to fetch image. You can also use QDeclarativeImageProvider::Image, to provide QImage to Image and in that case requestImage API will be called.

#include <QDeclarativeImageProvider>

class ImageProvider: public QDeclarativeImageProvider
{
public:
    ImageProvider(ImageManager* manager)
        : QDeclarativeImageProvider(QDeclarativeImageProvider::Pixmap),
          mManager(manager)
    {}

    QPixmap requestPixmap(const QString &id, QSize *size, 
        const QSize &requestedSize)
    {
        int width = 320;
        int height = 53;

        QPixmap result;

        if( mManager->imageData() == 0 ) {
     QPixmap pixmap(requestedSize.width() > 0?requestedSize.width():width,
             requestedSize.height() > 0 ?requestedSize.height():height);

            pixmap.fill(QColor(id).rgba());

            if ( size ) *size = QSize(width, height);
            result = pixmap;
        } else {

            result = *mManager->imageData();
            if ( size ) *size =result.size();

            if (requestedSize.isValid()) {              
                result = result.scaled(requestedSize,Qt::IgnoreAspectRatio);
            } 
        }
        return result;
    }

private:
    ImageManager* mManager;
};
Now custom image provider is ready, but we need to register our image provide to declarative engine, so that it will now forward image loading request to our image provider. To do that, we need to use QDeclarativeEngine::addImageProvider API, as described in following code. Here in addImageProvider API, "MyImage" is provider name, that will be used in QML to indicate that our custom image provider should be used.
QScopedPointer view(new QDeclarativeView());
view->engine()->addImageProvider(QLatin1String("MyImage"), 
    new ImageProvider(ImageManager::instance()));
Now we are ready to use our custom image provider with Image element, like shown below. Here in Image.source we providing path as image://MyImage, which will tell system to use MyImage image provider and remaining part of url will be used as id in requestPixmap or requestImage parameter. Which can be used to decide what kind of image data to provide.
import QtQuick 1.0

Rectangle {
    id:container
    width: 320;height: 53
    anchors.horizontalCenter: parent.horizontalCenter    

    Connections{
        target: ImageManager
        onImageAvailable:{
            myImage.source = "image://MyImage/test"
        }
    }

    Image {
        id: myImage
        anchors.centerIn: parent
        source: "image://MyImage/"+container.color
    }
}
This is all that is needs to be done to implement custom image provide. Hope it will be usefull.

Saturday, October 15, 2011

Audiobook Reader now available for N9 / N950 ( Harmattan ) on Nokia Store

I recently updated my Audiobook reader application for N9 Harmattan platform. It is also supported on N950. You can download it from Nokia Store from here.





For those who dont know about this application, Audiobook reader is simple Audiobook player which lets you add audiobook with single large audio file or folder with audio files for each chapter. It automatically bookmark the last position of audiobook and resume playback from that position. It also allow to add custom bookmark and playback from certain chapter from Audiobook.

For N9, I completely reimplemented UI layer to give native look and feel. For this version I am also showing book cover image, downloaded from AWS to give more feel of book.




Same as N900 version, this version also support custom bookmark support and chapter selection support. Volume can be changed by using Hardware key.


Thursday, October 6, 2011

Enabling Booster support for QML applicaion in Harmattan

Recently I added support for Booster for My QML application. Its quite easy to add booster support for existing QML or new QML application.

I am wiring down my experience here in hope it will help someone.

The QML booster reduce application startup latency by creating instances of QApplication and QDeclarativeView the classes in MDeclarativeCache.

To use this class you will need to add following header.

#include <MDeclarativeCache>
And then you will need to use QApplication and QDeclarativeView class instance provided by MDeclarativeCache. Following code shows how that can be done.

QApplication* app = MDeclarativeCache::qApplication(argc, argv);
QDeclarativeView* view = MDeclarativeCache::qDeclarativeView();
To enable booster and link with it properly you need to add following line in to your Qt project (.pro) file.

# enable booster
CONFIG += qt-boostable qdeclarative-boostable
LIBS += -lmdeclarativecache

If you are planning to use applauncerd to launch application then you will need to use Q_DECL_EXPORT macro in front of main function from "QtCore/QtGlobal" header file as shown in following code.

#include ≶QtCore/QtGlobal>

Q_DECL_EXPORT int main( int argc, char* argv[] ) {
}
You will also need modify include path in your pro file in order to locate header file properly.

INCLUDEPATH += /usr/include/applauncherd
And finally in your desktop file, you need to use --type=d to launch application using booster.

Exec=/usr/bin/invoker --single-instance --type=d /usr/bin/appname

The Math Game now available for N9/N950 (Harmatta) on Ovi Store

Today The Math Game's Harmattan version passed the Ovi QA process and its now available on Ovi Store.

The Math Game is fun and simple math game for little once. I created  game in hope that it will help to increase kid's interest in Math.

Harmattan version is now available here.

You can find maemo version here.

Please find more information regarding this application here.

Saturday, September 24, 2011

Crazy Chickens game available on N9/N950 Harmattan

Recently I ported my Crazy Chickens game for Harmattan / Maemo6. Its now available on Ovi Store.

Find out more information about this game here. Following are few snaps of game from Harmattan version.






Saturday, September 10, 2011

Accessing Amazon Web service from Qt

Currently I am trying to port my Audiobook reader application to Harmattan. I decided to improve its UI and as a change I decided to show book cover page in background.

Initially I thought to use taglib to fetch album art from audio file, but then I decided to download cover art from internet as some audio file might not contain album art information.

To download cover art from internet, I decided to use Amazon web service. Initially I struggled to successfully communicate with AWS.

AWS required to send signature with every request you send and there is certain procedure to create that signature. Creating signature with Qt is quite easy, but still I was facing problem with retrieving data from AWS because I did not read QUrl documentation carefully.

While generating QUrl, it expect human redable URL string with no percentage encoding. But I was trying to generate QUrl from already encoded parameters.

And as a result I was getting such error message.
"Value 2011-09-11T05%3A18%3A42 for parameter Timestamp is invalid. Reason: Must be in ISO8601 format".

Double encoding was causing above problem.

I am posting my code here, in hope that will be helpful to someone.

First all to communicate with AWS you required to have AWS access key id and Secret Access key. You can get it from here.

Here is AWS doc that explain how to generate signature. And here utility which you can use to verify if you generated correct signature.

Now we are ready for implementation. Following is my code.

Here in below code, I am trying to create AWS request to get all image for mentioned book. In request I am also specifying SignatureMetod to HmacSHA1, by default AWS use HmacSHA256 signature method for comparison.

const char AWS_KEY[] = "YOU ACCESS KEY";
const char AWS_PASS[] = "YOUR SECRET KEY";
const char END_POINT[] = "http://ecs.amazonaws.com/onca/xml";

AwsAlbumArtHelper::AwsAlbumArtHelper(QObject *parent) :
    QObject(parent)
{
    _netManager = new QNetworkAccessManager(this);    
}

QByteArray AwsAlbumArtHelper::getTimeStamp()
{
    QDateTime dateTime = QDateTime::currentDateTimeUtc();
    return dateTime.toString(Qt::ISODate).toUtf8();
}

void AwsAlbumArtHelper::downloadAlbumArt(const QString& bookname)
{
    _bookName = bookname;
    QMap< QString,QString > queryItems;
    queryItems["AWSAccessKeyId"] = AWS_KEY;
    queryItems["ResponseGroup"] = "Images";
    queryItems["Keywords"] = QUrl::toPercentEncoding(bookname);
    queryItems["Operation"] = "ItemSearch";
    queryItems["SearchIndex"] = "Books";
    queryItems["Service"] = "AWSECommerceService";
    queryItems["SignatureMethod"] = "HmacSHA1";
    queryItems["Timestamp"] = QUrl::toPercentEncoding(getTimeStamp());
    queryItems["Signature"] = createSignature(queryItems);

    QUrl downloadUrl = createUrl(queryItems);
    QNetworkRequest request(downloadUrl);

    disconnect(_netManager,SIGNAL(finished(QNetworkReply*)),this,SLOT(imageDownloaded(QNetworkReply*)));
    connect(_netManager,SIGNAL(finished(QNetworkReply*)),this,SLOT(xmlDownloaded(QNetworkReply*)));
    _netManager->get(request);
}
Following code create signature from query parameters. I used code pasted here for signing string with hmacSha1.
QByteArray AwsAlbumArtHelper::createSignature(const QMap< QString,QString >& queryItems)
{
    QUrl url(END_POINT);
    QString stringToSign = "GET\n";
    stringToSign.append(url.host() + "\n");
    stringToSign.append(url.path() + "\n");

    QList<qstring> keys = queryItems.keys();
    for( int i=0; i < keys.count() ; ++i ) {
        stringToSign.append(keys[i]+"="+queryItems[keys[i]]);
        if( i != keys.count() -1  ) {
            stringToSign.append("&");
        }
    }
    QString signature = hmacSha1(AWS_PASS,stringToSign.toUtf8());
    return QUrl::toPercentEncoding(signature);
}

QUrl AwsAlbumArtHelper::createUrl( const QMap< QString,QString >& queryItems )
{
    QUrl url(END_POINT);
    QMapIterator<QString, QString> it(queryItems);
    while (it.hasNext()) {            
        it.next();
        //everything is already URL encoded
        url.addEncodedQueryItem(it.key().toUtf8(), it.value().toUtf8());
    }
    return url;
}
Now we are ready to submit request using downloadAlbumArt method with required book name and AWS should return xml data with various image link. We need to parse xml and use mentioned link to download image.

Sunday, September 4, 2011

Porting Qt app to Harmattan

As I received Nokia N9 Dev kit from Qt Ambassador program, I started working on porting my existing Maemo 5 application to Maemo 6 (Harmattan/Meego) platform.

It seems from documentation that preferred way to create Meego application is by using QML and com.meego components. In order to make my Qt and QML application to work correctly on meego I needed to make quite a few changes.

First thing I noticed is that, Qt Widget are available on harmattan but that just for backword compatiblity and dose not provide native look and feel for Harmattan platform. That mean Qt Widget library are kind of useless on harmattan. We need to use meego touch library or meego QML component.

Some of my application were QWidget based or some were Graphics View based. I ported most of application to use QML and If i can not port to use QML then I  used QDeclarativeItem to load that component to QML.

For some of my application I was locking orientation, using "WA_Maemo5PortraitOrientation" flag in view.setAttribute(Qt::WA_Maemo5PortraitOrientation, true); API call, But on Harmattan I need to use following code in QML page.
 Page{
        orientationLock: PageOrientation.LockPortrait
    }
To make application full screen, I need to disable statusbar and toolbar from PageStackWindow. I used following code

PageStackWindow {
    showStatusBar: false
    showToolBar: false
}
In one of my application I was using GraphicsView framework, I loaded graphics view to QML using QDeclarativeItem and QGraphicsProxyWidget. Visit following link for more info. 

But after GraphicsView loaded to QML, view was displaying some white area that initially I was not able to remove. After a white I realized it was frame for graphics view. I removed it by using setFrameStyle API.
setFrameStyle(QFrame::NoFrame);
Desktop file also needs to be changed to locate icon correctly and to launch only single instance of application.
[Desktop Entry]
Encoding=UTF-8
Version=0.1
Name=appname
GenericName=app name
Comment=some comment
Exec=/usr/bin/single-instance /usr/bin/appname
Terminal=false
Type=Application
Icon=/usr/share/icons/hicolor/64x64/apps/icon.png
Also in control file, to make your application user application and not system component, we need to add following flag.
Maemo-Flags: visible
I used following in my project file to transfer icon file to proper location.
unix  {
    #VARIABLES
    isEmpty(PREFIX) {
        PREFIX = /usr
    }
    BINDIR = $$PREFIX/bin
    DATADIR =$$PREFIX/share

    DEFINES += DATADIR=\\\"$$DATADIR\\\" PKGDATADIR=\\\"$$PKGDATADIR\\\"

    INSTALLS += target desktop icon64

    target.path =$$BINDIR

    desktop.path = $$DATADIR/applications
    desktop.files += ./image/$${TARGET}.desktop

    icon64.path = /usr/share/icons/hicolor/64x64/apps/
    icon64.files += ./image/$${TARGET}.png
}
I also faced segmentation fault while testing Webview with emulator, but on device it works fine.

That's all, most of my experience was smooth while porting and did not struggled much.

Saturday, August 27, 2011

Snake game for N9/N950 Meego Harmattan now available on ovi store

I am happy to announce that Snake game is now available on N9/N950 Meego harmattan device also.


You can download game from Ovi Store from here. This game is port of N900 version, please find more information about game here.

 Now I am planning to port my Crazy Chickens game for meego. I hope I will be able to finish working on it soon.

Using Phonon Video player from QML

Recently one of my friend asked me to give some sample code for integrating Phonon Video Player to QML. Long back I had created a application which download video from dailymotion and play the video using Phonon.

QtMultimediaKit provides QML Video element which we cause use for playing video. But form reason if you need to use your exiting code then you can follow what I did.

I tried to my video widget from that application with sample QML application. I was able to integrate that widget quite easily without any problem.

Following is sample code for video player that uses the Phonon VideoPlayer to play video.

#include <phonon/videoplayer.h>
#include <QUrl>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{    
    player = new Phonon::VideoPlayer(Phonon::VideoCategory, this);

    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setMargin(0);
    mainLayout->addWidget( player);
}

void Widget::play()
{
    if( player->isPlaying() == false )
        player->play(QUrl("URL FOR VIDEO"));
}
Then I created an custom QDeclarativeItem, which uses my video widget class through QGraphicsProxyWidget. Visit my post for more information how we can use this class into QML.
#include "qmlvideo.h"
#include <QGraphicsProxyWidget>

#include "widget.h"

QmlVideo::QmlVideo(QDeclarativeItem *parent) :
    QDeclarativeItem(parent)
{
    myVideoWidget = new Widget;
    QGraphicsProxyWidget* proxy = new QGraphicsProxyWidget(this);
    proxy->setWidget(myVideoWidget);
}


void QmlVideo::play()
{
    myVideoWidget->play();
}
Now finally I created QML file which uses above created declarative item. I also tried how we can put player control with video player. Following is final code with some unnecessary code removed.
import QtQuick 1.0
import qmlVideo 1.0

Rectangle {
    width: 624 ; height: 480
    QmlVideo{
        id:videoPlayer
    }

    Item{
        anchors.bottom: parent.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        width: playerControl.width
        height: playerControl.height
        MouseArea{
            id:mouseArea
            anchors.fill: parent
            hoverEnabled:true

            onEntered: {
                playerControl.opacity = 1
            }

            onExited: {
                playerControl.opacity = 0
            }
        }
    }

    Rectangle{
        width: 200
        height: 50
        anchors.bottom: parent.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        id:playerControl
        color: "gray"
        opacity: 0
        radius:10

        Row{
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter
            spacing: 20

            Button{
                icon: "backward.png"
                iconOn:"backward_on.png"
                onClicked: {
                    videoPlayer.backward();
                }
            }
        }

        Behavior on opacity {
            NumberAnimation { duration: 500 }
        }
    }
}
Following is output and here is link to source code.Hope it will be useful to someone.

Friday, August 12, 2011

The Math Game for maemo now available on Ovi Store


I had created  and submitted The Math Game for Meego Coding competition. Find more information about this game here.

Meantime I had also uploaded the game on Ovi store. There were quite a lot problem to got it through Ovi Store QA, But finally maemo version of game got published today.

I am still now able to pass my Symbian version though. There is some problem for creating sis file using remote compiler.

This game is fun game for little ones, you can download it for free from here and from mobile visit this link.