Introducing Android SDK

Smart mobiles are gaining wider acceptance with each passing day. The market acceptance is resulting in increased demand for easier as well as flexible programming platforms, which in turn has resulted in new players entering the mobile SDK arena. The latest entrant is Google with its Android platform and corresponding SDK, which will be the focus of this discussion. The first section will be about whys and wherefores of Android. In the second section, the focus will be on the steps required in developing a basic Android application. The last section will focus on developing an application based on the steps described in the second section. That sets the agenda for this discussion.

Android – the Whys and Wherefores:

By definition “Android is a software stack for mobile devices that includes an operating system, middleware and key applications”. In other words, Android not only provides a runtime environment but also an SDK to develop applications aimed at the runtime environment. The Android stack consists of the following layers:

1. Kernel

2. Android Runtime

3. Libraries

4. Application Framework

5. Applications

The layers enumerated above are in bottom-up fashion i.e. Kernel forming the bottom most layer and Applications forming the topmost layer. Even though, Android is termed as a software stack, it, more or less exhibits characteristics of an Operating System that will be evident from details of the layers.

1. Kernel

It forms the foundation of Android. Kernel does all the low-level interactions at the hardware level. Kernel achieves this via the device drivers that are present at this layer. Android makes use of Linux kernel 2.6. The core services provided by the kernel include security, memory management, process management and network stack and driver model. In short, the kernel acts as a layer that encapsulates the interaction between other layers and hardware.

2. Android Runtime:

Runtime contains basic libraries that are required to run an application. These libraries provide most of the functionalities provided by Java libraries. Android applications target Dalvik virtual machine (VM), which essentially is the runtime.  Each application runs in its own process, each with its own instance of Dalvik VM. The runtime depends on the kernel for functionalities such as system-level threading and low-level memory management.

3. Libraries:

The various components and sub-systems of Android are included in the stack as a set of C/C++ libraries. The library includes System library, Media libraries, Surface Manager Library, OpenGL library etc. The functionalities of these libraries are provided to the developer through the Application Framework Layer.

4. Application Framework:

This layer exposes the functionalities provided by the Libraries layer to the developer. The Libraries layer contains C/C++ API. The Application Framework layer wraps those API and exposes it to the developer as Java API. The Application Framework consists of components such as Activity Manager, Window Manager, Content Providers, View Systems etc. Applications are built upon the services provided by these components.

5. Applications:

This is topmost layer of the Android stack. This layer contains pre-built applications such as email client, SMS program, maps, browser etc. The custom applications deployed by the user sit in this layer.

That completes the bird-eye view of the Android. In the next section, the steps to develop an Android application will be enumerated. From here on, Android would mean the complete stack and Android SDK would mean the tools and libraries required for developing applications for Android.

Developing an Android Application – Step-by-Step:

An Android application can be developed either by using Eclipse plug-in or by using tools provided alongwith the SDK. In this discussion, the second way will be used. The advantage of using the second step is that one will not be tied up with a particular IDE. Following are the steps for developing application without using Eclipse:

1. Generate Project Directories and Stubs

2. Develop UI logic

3. Compile and Deploy the Project

For all the steps except second, SDK provide tools. Here are the details.

1. Generate Project Directories and Stubs:

First step is to generate the directory structure and the source code stubs. To achieve this end, Android SDK provides a tool named activityCreator.py. It is a Python script. The script also creates an ant build file that can later be used to compile the application. The option that one needs to keep in mind is the out option. Using the out option, the name of the project directory can be specified. For example, to create a HelloWorld project with ‘HelloWorld’ as the directory and org.me.android.hello.HelloWorld as the class, the command will be

activityCreator.py –out HelloWorld com.android.hello.HelloWorld

2. Develop UI logic:

Next step is to develop the UI of the application. The activityCreator.py script created the stubs. To develop the UI, the generated source-code stub needs to be edited. It can be found in the src folder of the generated application folder. For example, the stub generated for the HelloWorld can be found inside HelloWorld\src folder. The auto-generated class will be as follows

public class HelloWorld extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.main);

}

}

The UI in Android is composed of hierarchies of Views. Each component is a view. Some of the views act as containers. One of the most commonly used views is TextView. It provides the functionality of a label. To instantiate an object of the TextView class, an instance of the Android Context is required.

Context is a handle to the system. It provides access to the services such as accessing database, resolving resource bundles to their locales etc. Activity class is a sub-class of Context class. Any class that is generated by the script inherits Activity. Hence, instance of Context can be passed by passing the instance of the generated class using this keyword. For example, to instantiate an object of TextView class named textView, the statement will be

TextView textView = new TextView(this);

Next step is to display a text value using the TextView. To do so, setText method of TextView class can be used. For example, the following statement will display “Hello World”

textView.setText(“Hello World”);

Last step in displaying the text label is to add instance of TextView to the onscreen display. setContentView() method of Activity class can be used to connect or add instance of TextView class. For example, to add textView to the onscreen display, the statement will be

setContentView(textView);

Next, let us see how to compile the project and deploy it.

3. Compile and Deploy the Project:

To compile the project, the only tool needed is ant. In the folder containing the
build.xml file, one has to just give the following command

ant

The ant tool will take the build.xml file and generate the class files. Then it will
package them into an .apk file. It is Android asset package file. The next step is to
deploy the .apk file. To do so, adb tool can be used. The install option of the adb
tool tells the tool to install the package into the simulator. The parameter that
needs to be passed to the tool is the path to the package.

That completes this section. Next, a small application will be developed based on the steps detailed in this section.

Android SDK – In Real World:

The application to be developed will have following features:

1. A widget, which will be a button

2. An event-handler for the button

3. A dialog box that will be shown when the button is clicked

The application, though simple, will be the base for future discussions. So lets get started. First step is to create the application structure. The name of the application will be AndroidNotepad. Using the createActivity.py the structure can be created. Once the structure is created, the AndroidNotepad.java will contain the following code

package org.me;

import android.app.Activity;

import android.os.Bundle;

public class AndroidNotepad extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(button);

}

}

Next, a button needs to be added. That can be done as shown in the code

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

public class AndroidNotepad extends AndroidNotepad {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

setContentView(button);

}

}

The next step is to capture the click event of the button. To do so, the OnClickListener interface needs to be implemented. The interface can be found in View package. To implement the OnClickListener interface, one needs to override the onClick() method. The following code implements the OnClickListener for the button

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.view.*;

public class AndroidNotepad extends Activity implements View.OnClickListener {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

setContentView(button);

}

public void onClick(View arg0) {

}

}

To attach the event handler to the button, the setOnClickListener() method of Button can be used.

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.view.*;

public class AndroidNotepad extends Activity implements View.OnClickListener {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

button.setOnClickListener(this);

setContentView(button);

}

public void onClick(View arg0) {

}

}

Lastly, the code to display the dialog box when the button is clicked is as under

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.view.*;

public class AndroidNotepad extends Activity implements View.OnClickListener {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

button.append(“Click”);

button.setOnClickListener(this);

setContentView(button);

}

public void onClick(View arg0) {

showAlert(“Button”, 0, “Button Clicked”, “OK”, true);

}

}

To show the dialog box showAlert method is used. More about the showAlert() method in the future discussions. That brings us to the end of this discussion. This discussion has just touched the tip of the iceberg that is Android. The next part of this discussion will be about using XML based definitions for the UI. Till then…

Smart mobiles are gaining wider acceptance with each passing day. The market acceptance is resulting in increased demand for easier as well as flexible programming platforms, which in turn has resulted in new players entering the mobile SDK arena. The latest entrant is Google with its Android platform and corresponding SDK, which will be the focus of this discussion. The first section will be about whys and wherefores of Android. In the second section, the focus will be on the steps required in developing a basic Android application. The last section will focus on developing an application based on the steps described in the second section. That sets the agenda for this discussion.

Android – the Whys and Wherefores:

By definition “Android is a software stack for mobile devices that includes an operating system, middleware and key applications”. In other words, Android not only provides a runtime environment but also an SDK to develop applications aimed at the runtime environment. The Android stack consists of the following layers:

1. Kernel

2. Android Runtime

3. Libraries

4. Application Framework

5. Applications

The layers enumerated above are in bottom-up fashion i.e. Kernel forming the bottom most layer and Applications forming the topmost layer. Even though, Android is termed as a software stack, it, more or less exhibits characteristics of an Operating System that will be evident from details of the layers.

1. Kernel

It forms the foundation of Android. Kernel does all the low-level interactions at the hardware level. Kernel achieves this via the device drivers that are present at this layer. Android makes use of Linux kernel 2.6. The core services provided by the kernel include security, memory management, process management and network stack and driver model. In short, the kernel acts as a layer that encapsulates the interaction between other layers and hardware.

2. Android Runtime:

Runtime contains basic libraries that are required to run an application. These libraries provide most of the functionalities provided by Java libraries. Android applications target Dalvik virtual machine (VM), which essentially is the runtime.  Each application runs in its own process, each with its own instance of Dalvik VM. The runtime depends on the kernel for functionalities such as system-level threading and low-level memory management.

3. Libraries:

The various components and sub-systems of Android are included in the stack as a set of C/C++ libraries. The library includes System library, Media libraries, Surface Manager Library, OpenGL library etc. The functionalities of these libraries are provided to the developer through the Application Framework Layer.

4. Application Framework:

This layer exposes the functionalities provided by the Libraries layer to the developer. The Libraries layer contains C/C++ API. The Application Framework layer wraps those API and exposes it to the developer as Java API. The Application Framework consists of components such as Activity Manager, Window Manager, Content Providers, View Systems etc. Applications are built upon the services provided by these components.

5. Applications:

This is topmost layer of the Android stack. This layer contains pre-built applications such as email client, SMS program, maps, browser etc. The custom applications deployed by the user sit in this layer.

That completes the bird-eye view of the Android. In the next section, the steps to develop an Android application will be enumerated. From here on, Android would mean the complete stack and Android SDK would mean the tools and libraries required for developing applications for Android.

Developing an Android Application – Step-by-Step:

An Android application can be developed either by using Eclipse plug-in or by using tools provided alongwith the SDK. In this discussion, the second way will be used. The advantage of using the second step is that one will not be tied up with a particular IDE. Following are the steps for developing application without using Eclipse:

1. Generate Project Directories and Stubs

2. Develop UI logic

3. Compile and Deploy the Project

For all the steps except second, SDK provide tools. Here are the details.

1. Generate Project Directories and Stubs:

First step is to generate the directory structure and the source code stubs. To achieve this end, Android SDK provides a tool named activityCreator.py. It is a Python script. The script also creates an ant build file that can later be used to compile the application. The option that one needs to keep in mind is the out option. Using the out option, the name of the project directory can be specified. For example, to create a HelloWorld project with ‘HelloWorld’ as the directory and org.me.android.hello.HelloWorld as the class, the command will be

activityCreator.py –out HelloWorld com.android.hello.HelloWorld

2. Develop UI logic:

Next step is to develop the UI of the application. The activityCreator.py script created the stubs. To develop the UI, the generated source-code stub needs to be edited. It can be found in the src folder of the generated application folder. For example, the stub generated for the HelloWorld can be found inside HelloWorld\src folder. The auto-generated class will be as follows

public class HelloWorld extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.main);

}

}

The UI in Android is composed of hierarchies of Views. Each component is a view. Some of the views act as containers. One of the most commonly used views is TextView. It provides the functionality of a label. To instantiate an object of the TextView class, an instance of the Android Context is required.

Context is a handle to the system. It provides access to the services such as accessing database, resolving resource bundles to their locales etc. Activity class is a sub-class of Context class. Any class that is generated by the script inherits Activity. Hence, instance of Context can be passed by passing the instance of the generated class using this keyword. For example, to instantiate an object of TextView class named textView, the statement will be

TextView textView = new TextView(this);

Next step is to display a text value using the TextView. To do so, setText method of TextView class can be used. For example, the following statement will display “Hello World”

textView.setText(“Hello World”);

Last step in displaying the text label is to add instance of TextView to the onscreen display. setContentView() method of Activity class can be used to connect or add instance of TextView class. For example, to add textView to the onscreen display, the statement will be

setContentView(textView);

Next, let us see how to compile the project and deploy it.

3. Compile and Deploy the Project:

To compile the project, the only tool needed is ant. In the folder containing the
build.xml file, one has to just give the following command

ant

The ant tool will take the build.xml file and generate the class files. Then it will
package them into an .apk file. It is Android asset package file. The next step is to
deploy the .apk file. To do so, adb tool can be used. The install option of the adb
tool tells the tool to install the package into the simulator. The parameter that
needs to be passed to the tool is the path to the package.

That completes this section. Next, a small application will be developed based on the steps detailed in this section.

Android SDK – In Real World:

The application to be developed will have following features:

1. A widget, which will be a button

2. An event-handler for the button

3. A dialog box that will be shown when the button is clicked

The application, though simple, will be the base for future discussions. So lets get started. First step is to create the application structure. The name of the application will be AndroidNotepad. Using the createActivity.py the structure can be created. Once the structure is created, the AndroidNotepad.java will contain the following code

package org.me;

import android.app.Activity;

import android.os.Bundle;

public class AndroidNotepad extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(button);

}

}

Next, a button needs to be added. That can be done as shown in the code

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

public class AndroidNotepad extends AndroidNotepad {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

setContentView(button);

}

}

The next step is to capture the click event of the button. To do so, the OnClickListener interface needs to be implemented. The interface can be found in View package. To implement the OnClickListener interface, one needs to override the onClick() method. The following code implements the OnClickListener for the button

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.view.*;

public class AndroidNotepad extends Activity implements View.OnClickListener {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

setContentView(button);

}

public void onClick(View arg0) {

}

}

To attach the event handler to the button, the setOnClickListener() method of Button can be used.

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.view.*;

public class AndroidNotepad extends Activity implements View.OnClickListener {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

button.setOnClickListener(this);

setContentView(button);

}

public void onClick(View arg0) {

}

}

Lastly, the code to display the dialog box when the button is clicked is as under

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.view.*;

public class AndroidNotepad extends Activity implements View.OnClickListener {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

button.append(“Click”);

button.setOnClickListener(this);

setContentView(button);

}

public void onClick(View arg0) {

showAlert(“Button”, 0, “Button Clicked”, “OK”, true);

}

}

To show the dialog box showAlert method is used. More about the showAlert() method in the future discussions. That brings us to the end of this discussion. This discussion has just touched the tip of the iceberg that is Android. The next part of this discussion will be about using XML based definitions for the UI. Till then…

VTK – Understanding the Terminology

Visualization

Visualization is the process of transforming a set of data into graphics primitives. These graphics primitive, in turn, can be rendered. In other words “Visualization is any technique for creating images, diagrams, or animations to communicate a message”.

Types of Visualization

Type is defined by the type of data that is being visualized. Typically, based on type of data Visualization can be categorized into:

1. Scientific Visualization

2. Educational Visualization

3. Information Visualization

4. Knowledge Visualization

5. Product Visualization

Visualization techniques

The following are examples of some common visualization techniques:

* Constructing isosurfaces

* direct volume rendering

* Streamlines, streaklines, and pathlines

* table, matrix

* charts (pie chart, bar chart, histogram, function graph, scatter plot, etc.)

* graphs (tree diagram, network diagram, flowchart, existential graph, etc.)

* Maps

* parallel coordinates – a visualization technique aimed at multidimensional data

* treemap – a visualization technique aimed at hierarchical data

* Venn diagram

* Timeline

* Euler diagram

* Chernoff face

* Hyperbolic trees

* brushing and linking

* Cluster diagram or dendrogram

* Ordinogram

AN : I will keep on updating as and when I come across a terminology related to VTK.

Introducing Google Maps API

Maps are becoming ubiquitous in web applications. They are being used as an effective and non-intrusive way of gathering geo-specific data from the user or to present geo-specific information to the user including tracking report of shipments et al. However even two years ago, embedding a map within an application was considered a specialized area requiring good understanding of Geographical Information System or GIS. But the arrival of Google Maps and its corresponding set of APIs, incidentally known as Google Map API, have changed the scenario. Now a developer having a good grasp on JavaScript, can without much ado embed an interactive map in a web-application using Google Map API. The questions that arise next is what exactly is Google Map API and what are the steps to be followed in using Google Map API. The answer to these questions is the focus of this discussion. The first section would deal with the whys and wherefores of Google Map API. In the second section I would detail the steps to use Google Map API. The last section would focus on a real world example based on the steps discussed in second section. That is the outline of the discussion.

Google Map API – What is it:

Google Map provides not only the map, satellite image or a hybrid of both but also an extensive range of operations on the map such as zooming, panning, information pop-ups, overlays etc. Google Map API provides interface into these operation through JavaScript objects. The beauty of the setup is that the functionalities work in the same non-intrusive way as the original Google Maps without developer needing to know the details of AJAX or how it is implemented in Google Maps. The developer has to just know the classes and their methods to access the services of Google Maps. The functionalities exposed by the Google Map API can be categorized as follows:

1. Configuration

2. Controls

3. Map Types

4. Map State

5. Overlays

6. Information Window

7. Map Navigation

8. Events

The accesses to most of the group of functionalities mentioned above are through the methods of GMap2 class. GMap2 class forms the basis of map creation, display and manipulation.

1. Configuration:

All the aspects of any map provided by Google Maps are configurable -be it the enabling of dragging and information windows or continuous zooming. The methods of GMap2 class sectioned under configuration enables configuration of the map. Following are the most oft used methods for configuring maps:

i. enableDragging() – enables the dragging of map. Dragging is enabled by

default.

ii. disableDragging() – disables the dragging of map.

iii. enableInfoWindow() – enables the information window

iv. disableInfoWindow() – disables the displaying of information window.

2. Controls:

The UI elements using which user controls the map and its functionalities come under controls category. There are two main methods related to controls which are:

i. addControl(control, [position]) – adds the specified control to the map at the

place specified by position parent. The position

parameter is optional.

ii. removeControl(control) – removes the specified control from the map.

Both the above functions takes instance of GControl class. There are four existing instances of GControl class – GSmallMapControl, GLargeMapControl, GSmallZoomControl, GScaleControl and GMapTypeControl. These can be passed to the addControl() method to add controls to the map.

3. Map Types:

Google Maps provide three types of map – simple map that provides outline based map, satellite map that streams the satellite imaged maps and hybrid map which is a combination of both aforementioned maps. The map types provided by Google Maps is controlled by the following methods:

i. setMapType(type) – sets the type of map to be displayed.

ii. removeMapType(type)- removes a already set map type.

The type parameter is specified using the constants provided by GMapType class. It can be G_NORMAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP corresponding to maps of type simple, satellite image based or combination of both.

4. Map State:

The methods that provide information about the state of the map comes under it. The information provided by map state methods include whether the map is loaded or not, the current focus point or center of the map etc. The commonly used methods are:

i. isLoaded() – it tells whether the map is loaded on to client browser or not

ii. getCenter() – this method provides the latitude and longitude of the center of

current viewport of the map.

5. Overlays:

By definition “A map overlay refers to a point or polyline that is added on top of the Google Map”. In essence an overlay means a point or line that is placed on the map to distinguish it from rest of the map. Mostly used methods in this category are:

i. addOverlay(overlay) – it adds an overlay presented by the overlay object

passed as parameter.

ii. removeOverlay(overlay) – it removes an overlay already added and

represented by the overlay object passed as

parameter.

The overlay object can be of type GPoint or GPolyline.

6. Information Window:

When an overlay is clicked, a window containing detailed information can be displayed. It is called the Information window or info window in short. Following are the main methods to control an info window:

i. openInfoWindow(latlng,dom,[opts]) – opens an information window at the

point specified by latlang and with the

data specified as dom which is a DOM

node.

ii. showMapBlowup(latlng,[opts]) – opens a info window at the specified as

specified latlng containing the close-up view of

the latlng specified as parameter.

The parameter latlng is of the type GLatLng.

7. Map Navigation:

The navigation of map can be controlled using the methods provided under this category. The commonly used methods are:

i. setCenter(center,[zoom],[type]) – loads the map with focus on the point

specified by center with an optional level of

zoom and type of the map.

ii. panTo(center) – it navigates to the point on the map specified by center.

iii. setZoom(level) – it zooms into or magnifies the current center to the level

specified with the parameter level.

8. Events:

Google Map API provide methods to intercept any event taking placing on the map. The common events supported by Google Map API are:

i. click – it is generated when user clicks on any point within the boundaries of the

map.

ii. move – it is fired when the map is moving or panning. During the panning it

may be fired many times.

iii. moveend – it is fired when the panning is completed.

That brings us to the end of first section. In the next section I would detail the steps required to work with Google Map API.

Using Google Map API – Step By Step:

Now that the services provided by Google Map API have been discussed, lets see the steps to use the API. To use Google Map API, two main steps have to be followed:

1. Acquiring the Registration Key

2. Setting-up the map

The second step again consists of sub-steps that actually deals with the setting up of HTML and Google Map API library.

1. Acquiring the Registration Key:

It is through the registration key that one can access the API. A key can be used within a web directory i.e. files within that directory and its subdirectories can make use of the key. To get the key, go to the site and provide the URL of the site for which the key has to be generated. The key alongwith an example would be provided which can be used as base for further developments.

2. Setting-up the map:

The Google Map API library is a JavaScript library. So its focus would be HTML and JavaScript based applications. In other words, Google Map API targets the UI for the web-applications. To set-up the page to display map the required steps can be enumerated as follows:

i. Set-up the HTML page:

The first step in displaying the map is by providing the required placeholder within the page where the map has to be shown. To do this <div> tag has to be used. It creates a logical block for the map to be displayed. For example following statement creates a placeholder named ‘map’:

<div id=”map” style=”width: 500px; height: 500px”></div>

ii. Importing/Including the Google Map API:

To use the API, its library has to be referenced. In case of JavaScript importing or including of the library (other terms for referencing a library) is done using the src attribute of <script> tag. So to include Google Map API library, the src of the <script> tag would be as follows:


<script src=”http://maps.google.com/maps?file=api&v=2&key=[yourkey]“

type=”text/javascript”></script>

The value of src attribute tells us two important points about Google Map API. First is the location of the API which is the Google’s site itself. So even for testing purpose, availability of internet is required. Second the is usage of the key provided after registration. The key is passed along with the URL in the src to tell Google that the site trying to access the API library is authorized site. Next step is to implement a function that would be called when the document is loaded. That is done by calling a function in the <body> tag’s onload handler. the statements would be :

<script type=”text/javascript”>

//<![CDATA[

function load() {

}

//]]>

</script>

For defining the function and it would be called from the body thus:

<body onload=”load()” >

:

:

</body>

The first step in implementation of logic within the function is to check whether the client browser is capable of displaying map or not. That can be done using GBrowserIsCompatible(). It return a Boolean value specifying whether the browser is capable of displaying map or not. The code block using it would be thus:

if (GBrowserIsCompatible()) {

//…

}

To display the map what we need is an object of GMap2 class. To get it, GMap2 constructor with the id of the <div> serving as placeholder, is required. For example the following code creates an instance of GMap2 class and assigns it to the variable named map:

var map = new GMap2(document.getElementById(“map”));

The last step in displaying the map is to set its focus on a particular point. That can be accomplished by calling the setCenter() method on map variable. The argument passed is of type GLatLng which, in turn accepts latitude and longitude as its parameter. The following sets the focus on the point defined by latitude 31.122027 and longitude 77.111664:

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

The map object can be used to manipulate map by using the methods enumerated in first section. The last but not least point is to call GUnload() through onunload handler of body tag to prevent memory leak:

<body onload=”load()” onunload=”GUnload()”>

:

</body>

That brings us to the end of the second section. In the next section I would develop a small application that would show the different functionalities discussed in first section using the steps detailed in this section.

Google Map API – In Real World:

Now I will be building a small application that displays map using Google Map API. It does the following:

1. Display the map with Shimla (India) as its center.

2. Provide zoom and pan controls for navigation.

3. Provide map type control to change between the three map types

4. Handle the click event and display information window showing the current focus

point on click upon the map.

So lets get going. First the HTML setup:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>

</head>

<body onload=”load()” onunload=”GUnload()”>

<div id=”map” style=”width: 500px; height: 500px”></div>

</body>

</html>

The onload handler calls the load function which is as follows:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>

<script src=”http://maps.google.com/maps?file=api&amp;v=2&amp;key=[yourkey]“

type=”text/javascript”></script>

<script type=”text/javascript”>

//<![CDATA[

function load() {

}

</head>

<body onload="load()" onunload="GUnload()">

<div id="map" style="width: 500px; height: 500px"></div>

</body>

</html>

Place the key you received in place of [yourkey]. This sets up the link to Google Map API and declares the load function. Next comes the creating the map instance and setting the center.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>

<script src=”http://maps.google.com/maps?file=api&amp;v=2&amp;key=[yourkey]“

type=”text/javascript”></script>

<script type=”text/javascript”>

//<![CDATA[

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById("map"));

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

}

}

</head>

<body onload="load()" onunload="GUnload()">

<div id="map" style="width: 500px; height: 500px"></div>

</body>

</html>

Next lets add the controls:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=[yourkey]“

type=”text/javascript”></script>

<script type=”text/javascript”>

//<![CDATA[

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById("map"));

map.addControl(new GSmallMapControl());

map.addControl(new GMapTypeControl());

map.addControl(new GScaleControl());

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

}

}

</head>

<body onload="load()" onunload="GUnload()">

<div id="map" style="width: 500px; height: 500px"></div>

</body>

</html>

The controls have to be added before setting the center. The last part is to handle the click event and show the current focus point on a information window:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=[yourkey]“

type=”text/javascript”></script>

<script type=”text/javascript”>

//<![CDATA[

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById(“map”));

map.addControl(new GSmallMapControl());

map.addControl(new GMapTypeControl());

map.addControl(new GScaleControl());

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

GEvent.addListener(map,”click”, function(){

map.openInfoWindow(map.getCenter(), document.createTextNode(map.getCenter()));

}

);

}

}

</head>

<body onload=”load()” onunload=”GUnload()”>

<div id=”map” style=”width: 500px; height: 500px”></div>

</body>

</html>

That completes the application. In just few lines it does a lot. This was just a teaser of what Google Map API can do. In the next articles I would discuss about advanced features such as communicating with servers and geo-encoding. Till then….

Mobile Programming using PyS60: Advanced UI Controls

In the last post, the topic of discussion was about basic UI controls that PyS60 provides. These controls are useful when the solution to be developed is simple in terms of interaction. However, if a scenario presents itself where interaction becomes complex, then the basic controls would not suffice. For such situations, advanced controls need to be used that can abstract out the complexities of the interaction to the user as well as provide simple and consistent interface for the developer to work with. PyS60 has many such controls that a developer can use. In this discussion, the focus will be on three of the most commonly used controls – selection list, multi-selection list and text. The first section would focus on the whys and wherefores of these controls. In the last section, the application developed in the previous part will be enhanced using the controls being discussed in this section. That is the agenda for this discussion.

Lists and Text Controls – Whys and Wherefores

There are times when providing a list of choices is a better option than asking the user to enter data in an entry box. In such circumstances, providing a list of choices is a better option. To provide lists, PyS60 has two UI controls

1. Selection List

2. Multi-selection List

The former is a good choice when only one item needs to be chosen whereas when several items need to be chosen then the later is the control of choice. Here are the details.

1. Selection List:

As the name suggests, it displays a list to the user from which he or she can choose. The selection list provided by PyS60 also contains a search field that helps the user to narrow down the choices. It is displayed to the user using a function called selection_list(). It comes under the category of dialogs wrapped in functions. It takes two arguments:

a. choices

b. search_field

The latter is an optional argument.

a. choices:

It is a list of Unicode strings containing the options to be displayed to the user.

b. search_field:

It accepts a ‘0’ or ‘1’ as the value. The value decides whether the search field will be  shown or not. If the value is ‘1’, the search field is shown. The default value is ‘0’ i.e. the search field is off by default. If enabled, the search field is shown after the first key press occurs.

The value returned by the selection_list() function is the index of the selected item. For example, to show a list with ‘egg’, ‘spam’ and ‘butter’ to choose from without any search field, the statements will be

list = [u”egg”, u”spam”, u”butter”]

selection_list(list)

2. Multi-selection List:

There are cases where a single selection is not a solution. This is where multi-selection list comes handy. Like selection list, multi-selection list is also a function that wraps up a dialog and displays the dialog when it is executed. The function that brings up a Multi-selection List is multi_selection_list(). It accepts the following arguments

a. choices

b. style

c. search_field

The first and third are similar to the selection_list() arguments. The second argument is unique to multi_selection_list(). Here are the details

a. choices:

Just as in the case of selection_list, the value accepted by this argument is a list of Unicode strings.

b. style:

This is optional. The value of this parameter decides how the list will be displayed. There are two valid values for the style parameter:

i. checkbox – It is the default value. If ‘checkbox’ is given as the value of the
style, the list presented to the user will be a list containing a
checkbox against each list item. Empty checkboxes indicate
selectable item.

ii. checkmark – It is the other acceptable value for the style argument. If
‘checkmark’ is used as the value, then the list presented to
the user doesn’t have a visual clue as to which item to be
selected. However, once selected, a checkmark will appear
against that item.

c. search_field:

This argument does the same thing that search_field does for selection_list()
function. If value of 1 is passed, the search field is displayed and if value of 0 is
given, the search field is not displayed.

The value returned by the function is tuple containing selected values. If no values are selected, then an empty tuple is returned. For example, the following statements display a list from which multiple items can be selected having the checkmark style, having a search field and the returned values are displayed.

list = [u”egg”, u”spam”, u”butter”]

result = multi_selection_list(list, ‘checkmark’, 1)

print result

Next, let us move onto the control that provides the text editor functionalities.

Text:

It provides text editor with almost all the text formatting functionalities. The control is provided by Text type. Unlike selection or multi-selection list, text is a type. The functionalities provided by text type are categorized under the following:

a. Attributes

b. Methods

Since the text is a type the functionalities are exposed either as a attribute or a method. Here are the details

a. Attributes

Following are the most commonly used attributes of Text:

i. color:

It defines the color of the text. The valid values are all the colors supported by
graphic models in graphics module.

ii. font:

This attribute determines the font family of the text. It can be set using the
supported Unicode name.

iii. style:

It affects the style of the text. The valid values for this attribute are defined as
flags. The valid flags are provided by appuifw module. Some of the commonly
used flags are

  • STYLE_BOLD – Makes the text bold
  • STYLE_UNDERLINE – Underlines a displayed text
  • STYLE_ITALIC – Makes the text italic

For example, to use a Text type with LatinPlain12  as font’ value with bold text, the statements will be

t = appuifw.Text()

t.font = u”LatinPlain12″ # sets font to Latin Plain 12

t.style = appuifw.STYLE_BOLD

b. Methods

Text type provides various methods to perform common operations on the text
held by the editor. The most common methods are:

i. add() : It accepts Unicode string as argument. This method appends a text to
the existing text. It can also be used to insert the
passed argument at current cursor position.

ii. set() : Just like add() method, tt accepts Unicode string as argument. It sets
the passed Unicode string as argument. It replaces any text that
may be present in the editor.

iii. delete() : It accepts two arguments – position and length and deletes length of
characters in the editor starting from the position passed as
argument.

For example, to set a string having value as “This is a text” as the text in the editor, the statement is

t.set(u”This is a text”)

This brings us to the end of this section. In the next section, the guessing game application that was developed in last part will be enhanced using single selection list.

PyS60 in Real World:

In the last discussion, a guessing game was developed. The code was as follows

from appuifw import *

continue_guess=true

while continue_guess:

guess_no=random()

user_guess=query(u”Enter your guess”, ‘number’)

if user_guess is Null:

note(u”You have opted out”)

continue_guess=false

elif user_guess<guess_no:

note(u”Your guess is lesser than the goal”)

elif user_guess>guess_no:

note(u”Your guess is higher than the goal”)

else:

note(u”Congrats for excellent guess”)

user_choice=query(u”Enter Y to continue or N to quit”)

if user_choice is Null or user_choice==’N’:

continue_guess=false

else:

continue_guess=true

Now, let us change the display part for displaying the choices. Instead of taking user’s input using a query dialog, let us show a selection list from which the user can select a value. The following code

user_guess=query(u”Enter your guess”, ‘number’)

needs to be changed to

list = [guess-100, guess, guess*200, u”Quit”]

user_guess = selection_list(list)

first, a list is created using the guess no. and its combination. Then the list is given as an argument to selection_list() method. The returned index, which is the value selected by the user, is then stored in the user_guess variable.

Next, let us change how the result is processed. To do so, the following code

if user_guess is Null:

note(u”You have opted out”)

continue_guess=false

elif user_guess<guess_no:

note(u”Your guess is lesser than the goal”)

elif user_guess>guess_no:

note(u”Your guess is higher than the goal”)

else:

note(u”Congrats for excellent guess”)

to the following

if  guess_no < list [user_guess]:

note(u”Your guess is lesser than the goal”)

elif guess_no < list [user_guess]:

note(u”Your guess is higher than the goal”)

elif guess_no == list [user_guess]:

note(u”Congrats for excellent guess”)

else:

note(“Bye”)

continue_guess = false

The index returned by the selection_list() is used by the if condition to get the value selected by the user, from the list. If the index corresponds to the value lesser or greater than the goal value, then a note is displayed telling the user that he/she is either short of the goal or overshot the goal. Otherwise, user is congratulated. If user selected the option to quit, the continue_guess is set to false, thus ending ‘the game’. The complete code is as follows

from appuifw import *

continue_guess=true

while continue_guess:

guess_no=random()

list = [guess-100, guess, guess*200, u”Quit”]

user_guess = selection_list(list)

if  guess_no < list [user_guess]:

note(u”Your guess is lesser than the goal”)

elif guess_no < list [user_guess]:

note(u”Your guess is higher than the goal”)

elif guess_no == list [user_guess]:

note(u”Congrats for excellent guess”)

else:

note(“Bye”)

continue_guess = false

That completes our application. This discussion focused on the UI controls. From the next discussion, the focus will be moving towards the third party libraries in PyS60. However, the next discussion will focus primarily on graphics module. Till then…

Mobile Programming in Python using PyS60: UI Controls

GUI changed the way a program communicates with the user. It made applications interactive. Interactivity is the norm of the day. Mobiles are no exceptions. PyS60 makes creating GUI based applications easy. It can be termed as on of the RAD environment for Symbian OS. In this discussion I will focus on the basics of using UI library provided by PyS60. The first section will focus on the types of the controls. The second section will be about three basic controls – note and query. In the third section, a simple application will be developed that uses the controls discussed in second section. That’s the agenda for this discussion.

Types of Controls:

PyS60 provides controls or widgets (including dialogs) in two forms. They are:

1. Functions

2. Python types

Controls or widgets under the former mostly are methods where as those in latter category are Python objects implemented in C. Here are the details.

1. Functions:

Many of the dialogs are implemented as functions. In PyS60, dialogs take precedence over the other controls such as textboxes, list-boxes etc. This means if a control and a dialog needs to be shown, then dialog will be shown on top of the control, thus hiding the control. The examples of dialogs implemented as functions are note, query, multi_query etc.

2. Python types

The controls such as textboxes are implemented in C and directly accessed in PyS60. Their precedence is lower than UI implemented as Functions. Text, Listbox and Canvas are examples of Python types. These controls are displayed the instant they are set as the part of the application’s body. In other words, these controls are not displayed until they have been registered as the part of the application.

One of the controls is a dialog that has been implemented as a Python type. It is the Form control. That completes the discussion about the types of UI controls lets move onto next section.

UI Controls – Entry and Notes:

Query and Notes controls are the most commonly used of all the controls. They are used to take input and display messages. Here are the details:

1. Query:

Query is a dialog type. It is used to gather input from the user. It presents a single line text box with a label to the user. Since query is a dialog, so it is implemented as a function. There are three parameters to the function. They are:

i. label

ii. type

iii. initial value

The first two are mandatory parameters whereas the third is optional. Here are the details

i. label

It is the question or prompt that is shown to the user when the dialog box is displayed. The value for this argument is an Unicode string. For example, to show the “Enter name” as the prompt, one will use the following as the value of the argument:

U”Enter name”

ii. type

One can compare it with standard input dialog box that is common on PC. Since it is a dialog, it can be of different dialog types. The type is decided by the type parameter of the query function. The different types are:

a. text – it is a simple text. The text is of Unicode type.

b. code -

c. number – in this case, the input box will accept only numbers and not

decimals

d. date – the input is just date

e. time – to take time as input type needs to be set to time.

f. float – to accept only decimals, this type can be used

All these values are string type. For example to set the type to number, the value passed will be

‘number’

iii. initial value

This is an optional parameter. It sets the initial value shown to the user. However, for the type float, setting this value does not have any effect. For text fields i.e. type having value either ‘text’ or ‘code’, the value for this argument is Unicode. If the type is ‘number’, the value that can be passes is numeric values only. If the type is date, then initial value will be seconds since epoch rounded to the nearest local midnight. For example, to set the initial value to 3, the value passed will be

3

The return value of query is the value provided by the user and the type of the input box. Therefore, to display a query with “Enter any number between 1 and 9” as message, with number as the only acceptable data and 0 as initial value, the statement will be

guess=query(u“Enter any number between 1 and 9”, ‘number’,0)

2. note

note is another control implemented as a dialog. It is used to display messages to the user. This is, again, one of the most common controls in the toolkit of PyS60 as it can be used to display different messages. These messages can be anything from simple message such as information about the size of current file or critical messages such as low battery. The note function takes three arguments. They are

a. text

b. type

c. global

Of these, only text is mandatory argument. The other two are optional. Here are the details.

a. text

It is the message to be shown. It is a Unicode string. For example, to show a message stating that the memory is full, the text argument will be of following format

u”Memory is full”

The u at the starting indicates that it is a Unicode text.

b. type

As stated earlier, the note function can be used to display different kinds of messages. The kind of the message is determined by the value passed for ‘type’ parameter. This parameter can accept the following string values:

i. info – it is the default value, if no value is passed. When type is set to info,

the message shown will be of simple kind. Hence, the icon will have

‘i’ as symbol.

ii. error – to show error messages, one can use this string as the value. If the

type is set to ‘error’, the icon will have ‘e’ as the symbol.

iii. conf – set the type to ‘conf’ when the message to be shown is related to

configuration. An example of configuration is selecting and setting

the fonts. Once a font has been set, a message whose type conf can

be shown to the user informing him/her the name of the new font.

c. global

The value of global argument decides whether, the note displayed is global or not. Global note is a note that will be displayed even if the application calling the note function is not in foreground. The global argument takes an integer value. Any value other than zero is used to make a note or the displayed message global. The default value for this argument is zero. For example, to show a non-global message to the user, the value passed to the global argument will be

0

For example to display a global error message stating that memory is full, the statement will be

note(u”Memory is full”, error, 1)

That brings us to the end of second section. Next section will be about an application using whatever has been discussed until now.

PyS60 in Real World

Lets now see how these controls can be used within an application. The application going to be developed is a simple guessing game. It will perform following tasks

1. Choose a random number

2. Ask the user to enter his or her guess

3. Compare and show the result

4. Ask if he or she will like to continue

So lets start. First the imports

from appuifw import *

As you already know the above statement imports all the classess within appuifw module. Next the application has to choose a random number. However, since this will be a repeating process until the user chooses to stop, choosing the random number will be within a loop. The loop will terminate only when user says he or she will like to stop. The code is as follows

from appuifw import *

continue_guess=true

while continue_guess:

guess_no=random()

The loop will continue till continue_guess becomes false. Next, the application needs to accept user’s guess. To accept the value, query function will be used. The message will be “Enter your guess”, the type will be number (since decimals will not be allowed) and no initial value will be displayed. The value will be saved in user_guess variable. Here is the code

from appuifw import *

continue_guess=true

while continue_guess:

guess_no=random()

user_guess=query(u”Enter your guess”, ‘number’)

Next comes the comparison and displaying the result functionality. First, the user_guess will be checked for validity i.e. if user clicked cancel, it will be null. If it is not null, then it will be compare with the guess_no and appropriate no. will be displayed. If user pressed cancel, a “You opted out” will be shown and the continue_guess will be set to false. Here is the code

from appuifw import *

continue_guess=true

while continue_guess:

guess_no=random()

user_guess=query(u”Enter your guess”, ‘number’)

if user_guess is Null:

note(u”You have opted out”)

continue_guess=false

elif user_guess<guess_no:

note(u”Your guess is lesser than the goal”)

elif user_guess>guess_no:

note(u”Your guess is higher than the goal”)

else:

note(u”Congrats for excellent guess”)

Next comes the code that asks user whether to continue or not. The query box is shown to the user with “Enter Y to continue and N quit”. If Y is entered, the loop is continued else the application is exited.

from appuifw import *

continue_guess=true

while continue_guess:

guess_no=random()

user_guess=query(u”Enter your guess”, ‘number’)

if user_guess is Null:

note(u”You have opted out”)

continue_guess=false

elif user_guess<guess_no:

note(u”Your guess is lesser than the goal”)

elif user_guess>guess_no:

note(u”Your guess is higher than the goal”)

else:

note(u”Congrats for excellent guess”)

user_choice=query(u”Enter Y to continue or N to quit”)

if user_choice is Null or user_choice==’N’:

continue_guess=false

else:

continue_guess=true

That completes the application. In this discussion, the focus was on simple UI controls. From the next part, complex UI controls such as forms. Till then…

Image Manipulation using GDI+ – The C# Way: Thumbnails and Zooming

In the last part I gave you a bird’s eye view of what GDI+ is and how to setup application for using GDI+. However, without knowing about the facilitator i.e. GDI+, going forward would be counter-productive. Hence, in this part, along with different image manipulation techniques, the focus would be on the essentials of GDI+. In the first section, I would discuss about GDI+ in brief including the differences it has with its predecessor that is GDI. Second section would focus on the manipulation techniques such as zooming, creating thumbnails. In the third section, I would extend the application created in last part to include the techniques introduced in this discussion. That is the outline of this discussion.

More About GDI+:

GDI+ essentially refers to the library that helps developers to interact with various devices such as Monitors, Printers etc. having graphical capabilities without going into low-level details of these devices. The essence of GUI is that it can interact with peripherals such as Monitors and presents data in human readable form. However, from the point of view of a developer, if he or she had to directly interact with these devices, then such a task would have been monumental. This is where GDI+ comes into picture. It acts as a conduit and a translator for the data being passed between devices and applications. Even controlling the command line terminals also comes under GDI+. It does everything from printing a ‘Hello World’ program on the console to drawing lines, rectangles etc and printing a form. Pictorially it can be shown thus:

Fig 1- GDI2_1.jpg

The next question that arises is how does GDI+ works? To make it clear as a crystal, lets have a look at an example of drawing a line. A line, in essence, is a sequence of pixels from starting location (X­­0, Y0) to an ending location (Xn, Yn). To draw such a line the devices i.e. monitor in this case, need to know the device coordinate or physical coordinates. However, instead of directly telling the device, the call is made to the drawLine() method of GDI+, and GDI+ draws the line from point A to point B in the memory also known as video memory. GDI+ reads the point A and point B locations, converts them to a sequence of pixels, and tells the monitor to display the sequence of pixels. In short GDI+ converts device independent calls to device understandable form and vice-versa. So that’s an overview of how GDI+ works. Lets now move onto topic of manipulation of image.

Image Manipulation – Thumbnail, zooming and saving:

In the last part, I discussed simple manipulations such as flipping and rotating. Lets tackle something a bit more complex in concept if not in implementation. They are:

1. Creating thumbnails

2. Zooming a loaded image

3. Saving a manipulated image

Of these first two strictly comes under the category of image manipulation whereas the last is a generic image based operation in the lines of file operation.

1. Creating Thumbnails:

Thumbnails are reduced version of images. The dimensions of a thumbnail image are typically of 80 to 200 pixels in length. In GDI+, thumbnail of an image can be created by GetThumbnailImage() of Image class. It takes four parameters- the first parameter corresponds to the width and second parameter is for the height of the thumbnail to be generated, the third parameter is Image.GetThumbnailImageAbort which needs to be passed for compatibility though not being used in current version. The fourth parameter, likewise is not used, yet need to be passed for compatibility. The fourth parameter must be IntPtr.Zero. If the first two parameters that is width and height are 0, then GDI+ returns embedded thumbnail (some images contains thumbnails embedded into them. Otherwise the thumbnail is created using system defined dimensions. For example if img is an instance of Image class and the width, height to be used is system defined, the statement to create a thumbnail would be:

Image thumbNailImage = img.GetThumbnailImage(0, 0, tnCallBack, IntPtr.Zero);

Where thumbNailImage contains the returned thumbnail, the tnCallback is a function corresponding to Image.GetThumbnailImageAbort which is defined as:

// Must be called, but not used

public bool tnCallbackMethod()

{

return false;

}

2. Zooming a loaded image:

Zooming is the process of enlarging an image by multiplying it with a number called zoom-factor. By definition, “The zoom factor is the ratio of the current size of the image to the desired new size of the image”. That means by dividing the current size of the image with desired size of the image we get the zoom factor. For example, to zoom in on an image by 200%, the current size must be multiplied by 200% or by 2 (200%= 200/100=2). To zoom out an image by 25 percent, the size must be multiplied by 25 percent, or 0.25 (25/100 = 0.25 times). It is one of those areas of image manipulation where GDI+ doesn’t provide methods to achieve the result.

3. Saving a manipulated image:

Saving an image is one of the primary operations done on an image. While saving an image, the type into which the image has to be saved or in other words the extension of the image plays a major role. Each type corresponds to a particular format. In essence, while saving an image writing out the data according to the format is necessary. However, since the API that is being used is GDI+, a single call to Save() method of Image class abstracts out all the details about writing out according to the format. It takes two parameters – the name as which the image is to be saved and the format into which the image has to be saved. The format can be specified using the types provided by ImageFormat class. Following table specifies the various formats supported by GDI+:

Property

Description

Bmp Specifies BMP format.
Emf Specifies EMF (Enhanced Metafile Format).
Exif Specifies EXIF format.
Gif Specifies GIF format.
Guid Specifies a GUID structure that represents the ImageFormat object.
Icon Specifies Windows icon format.
Jpeg Specifies JPEG format.
MemoryBmp Specifies memory bitmap format.
Png Specifies PNG format.
Tiff Specifies TIFF format.
Wmf Specifies WMF (Windows Metafile Format

Of these Emf and Wmf are specific to windows. I will be discussing about these, in detail, in future.

For example to save the image with the name “checker.gif” in GIF format, the statement would be:

curImage.Save(“checker.gif”, ImageFormat.Gif);

where curImage is the instance of Image class.

That brings us to the end of this section. In the next section, I would be extending the application developed in the first part by embedding the operations discussed in this section.

Image Manipulation – In the Real World:

It is time to put the theory into practice. I would be doing it by enhancing the application developed in the last part by providing the following functionalities:

1. Save the image in the format specified by user

2. Zoom-in according to the percentage selected from the menu

3. Create thumbnail of a loaded image

The menus corresponding to the operations are:

mnuSave – the submenu of File menu to save the image

mnu200Zoom – zooms the image by 200%.

mnuThumbNail- creates a thumbnail of the image.

Here is the method that handles click event of mnuSave

private void mnuSave_Click(object sender,

System.EventArgs e)

{

// If image is created

if(curImage == null)

return;

// Call SaveFileDialog

SaveFileDialog saveDlg = new SaveFileDialog();

saveDlg.Title = “Save Image As”;

saveDlg.OverwritePrompt = true;

saveDlg.CheckPathExists = true;

saveDlg.Filter =

“Bitmap File(*.bmp)|*.bmp|” +

“Gif File(*.gif)|*.gif|” +

“JPEG File(*.jpg)|*.jpg|” +

“PNG File(*.png)|*.png” ;

saveDlg.ShowHelp = true;

// If selected, save

if(saveDlg.ShowDialog() == DialogResult.OK)

{

// Get the user-selected file name

string fileName = saveDlg.FileName;

// Get the extension

string strFilExtn =

fileName.Remove(0, fileName.Length – 3);

// Save file

switch(strFilExtn)

{

case “bmp”:

curImage.Save(fileName, ImageFormat.Bmp);

break;

case “jpg”:

curImage.Save(fileName, ImageFormat.Jpeg);

break;

case “gif”:

curImage.Save(fileName, ImageFormat.Gif);

break;

case “tif”:

curImage.Save(fileName, ImageFormat.Tiff);

break;

case “png”:

curImage.Save(fileName, ImageFormat.Png);

break;

default:

break;

}

}

}

First save dialog box is shown with acceptable extensions. Then from the file name returned by the dialog box the extension is retrieved and according to the extension Save() method is called with corresponding image format parameter.

Next comes the handler for mnu200Zoom. But before that certain things have to be done. First add the following line to the class at the application level:

private double curZoom = 1.0;

Then the mnuLoad (from previous part) has to be changed slightly. The added code is shown in bold:

private void mnuLoad_Click(object sender,

System.EventArgs e)

{

//Change the AutoScrollMinSize property

this.AutoScrollMinSize = new Size

((int)(curImage.Width * curZoom),

(int)(curImage.Height * curZoom));

// Create OpenFileDialog

OpenFileDialog opnDlg = new OpenFileDialog();

// Set a filter for images

opnDlg.Filter =

“All Image files|*.bmp;*.gif;*.jpg;*.ico;”+

“*.emf;,*.wmf|Bitmap Files(*.bmp;*.gif;*.jpg;”+

“*.ico)|*.bmp;*.gif;*.jpg;*.ico|”+

“Meta Files(*.emf;*.wmf;*.png)|*.emf;*.wmf;*.png”;

opnDlg.Title = “ImageViewer: Open Image File”;

opnDlg.ShowHelp = true;

// If OK, selected

if(opnDlg.ShowDialog() == DialogResult.OK)

{

// Read current selected file name

curFileName = opnDlg.FileName;

// Create the Image object using

// Image.FromFile

try

{

curImage = Image.FromFile(curFileName);

}

catch(Exception exp)

{

MessageBox.Show(exp.Message);

}

}

// Repaint the form, which forces the paint

// event handler

Invalidate();

}

What the added code does is that it multiples the image width and height with zoom factor to render an image with appropriate zoom setting. Next the paint event handler has to be changed. The DrawImage() method has to be changed into the following:

g.DrawImage(curImage, new Rectangle

(this.AutoScrollPosition.X,

this.AutoScrollPosition.Y,

(int)(curRect.Width * curZoom),

(int)(curRect.Height * curZoom)));

The image should have the height and width according to the zoom factor. For that the current width and height is multiplied with the current zoom factor represented by curZoom variable. Last step in zooming is the event handler for mnu200Zoom:

private void mnu200_Click(object sender,

System.EventArgs e)

{

if(curImage != null)

{

curZoom = (double)200/100;

Invalidate();

}

}

Lastly comes the event handler for the mnuThumbNail:

private void mnuThumbNail_Click(object sender,

System.EventArgs e)

{

if(curImage != null)

{

// Callback

Image.GetThumbnailImageAbort tnCallBack =

new Image.GetThumbnailImageAbort(tnCallbackMethod);

// Get the thumbnail image

Image thumbNailImage = curImage.GetThumbnailImage

(100, 100, tnCallBack, IntPtr.Zero);

// Create a Graphics object

Graphics tmpg = this.CreateGraphics();

tmpg.Clear(this.BackColor);

// Draw thumbnail image

tmpg.DrawImage(thumbNailImage, 40, 20);

// Dispose of Graphics object

tmpg.Dispose();

}

}

// Must be called, but not used

public bool tnCallbackMethod()

{

return false;

}

It first creates a variable of type GetThumbnailImageAbort and assign the tnCallbackMethod() to it by passing the method to the GetThumbnailImageAbort. Then it creates a new instance of Image class to hold the image returned by the GetThumbnailImage method, which is then used to draw the thumbnail onto the screen.

This brings us to the end of this discussion. In this part I discussed more advanced features of GDI+. I will continue along the same lines in next part. Till then…

JEE and Ajax – I: Servlets and Ajax

Non-obtrusiveness, responsiveness and high interactivity are the areas where desktop applications still have an edge over the web-applications. The intelligent use of JavaScript can create highly interactive web-sites. However, responsiveness and non-obtrusiveness would still be a distant dream. The responsiveness can be achieved by careful implementation at server-side by using technology such as J2EE that uses threading mechanism to service requests. But, to achieve non-obtrusiveness, a component is required that can provide asynchronous means of communication so that complete re-rendering of a page during the response phase can be bypassed. That is where AJAX comes into picture. AJAX provides asynchronous communication service through JavaScript and XML. Thus a good combination can be formed by using AJAX at client-side and Servlet at server-side providing non-obtrusive, responsive and highly interactive web experience. In this discussion, I would be focusing on utilizing such a winning combination. The first section would be detailing the steps required for setting up of application for utilizing AJAX along with servlet. In second and the last section I would be developing a registration module that would use AJAX to check the availability of the username. That’s what’s in store for this discussion.

AJAX and Servelets- The Steps for Implementation:

AJAX or Ajax is really not a technology in itself but it is a combination of existing technologies. These form the basis of the asynchronous communication, XML and HTML manipulation. So lets have look at these components:

1. XML

2. XMLHttpRequest (JavaScript)

3. HTML/XHTML with CSS

4. Server-side component.

The steps to implement AJAX cover these entire components. The JavaScript communicates with the server using XMLHttpRequest, receives response in the form of XML from the server side component which is used by the JavaScript to manipulate the HTML to present data to the user. That is the complete cycle of AJAX request-response cycle in nut-shell. The implementation that gives raise to the aforementioned cycle constitutes the following steps:

1. Setting up the XMLHttpRequest

2. Calling the server-side component

3. Registering and implementing call-back handler and at the server side

4. Generate the XML response.

How the four components fits with the implementation steps is detailed below.

1. Setting up the XMLHttpRequest:

The very first step of AJAX setup comes in the form of instantiating XMLHttpRequest. It exists in two varieties- first as an ActiveX control and second as a JavaScript object. The Internet Explorer considers it as an ActiveX while Mozilla, Firefox and Opera consider it as a JavaScript. So to set up XMLHttpRequest the browser type has to be checked. The best way to check the type is to determine whether the client browser supports ActiveX or not. If ActiveX is supported then instantiate using CreateObject() method otherwise use XMLHttpRequest’s constructor to do the same. In code, it would be:

var xmlHttp;

if(window.ActiveXObject)

{

xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);

}

else if(window.XMLHttpRequest)

{

xmlHttp=new XMLHttpRequest();

}

Instead of directly using else part, the check can be done on the browser supporting XMLHttpRequest as an object or not. To instantiate the XMLHttpRequest object as an ActiveX, then the object name which in this case is Microsoft.XMLHTTP, has to be passed to the CreateObject method. To instantiate it using the constructor, new XMLHttpRequest() has to be used. That completes the setting up step.

2. Calling Server-Side Component:

To make a call to the server-side component (in this case servlets) the methods of XMLHttpRequest instance have to be used. Which method to be used depends on the type of method to be used. following are the methods:

i. setRequestHeader

ii. open

iii.send

The first method comes into picture when the method of HTTP request has to be POST. The parameters taken by the second and third methods change according to the method used.

i. setRequestHeader:

It sets the value of the header given as parameter. This method takes two parameters-the name of the request header, the value of the header. This method comes into picture when POST method is used. For example, if POST has to be used, the statement would be:

xmlHttp.setRequestHeader(“Content-Type”, “application/x-www-form-

urlencoded; charset=UTF-8″);

The first parameter sets the name of the header as Content-Type and its value as application/x-www-form-urlencoded. Also its sets the character set of the content as UTF-8. But it is important to call open before setting the header.

ii. open:

This is the method that actually sets up the communication with the server. The URL corresponding to the servlet is given as the second of the parameters. The first parameter is the type of the method to communicate with the server. It can be either GET or POST or PUT. If GET is used, the data sent as query string by appending it to the URL i.e. the first parameter. The third parameter, which takes a Boolean value decides whether the communication would be synchronous or asynchronous. A true value makes the communication asynchronous whereas a false value makes the communication synchronous. The last two optional parameters are required only when the server requires authentication. For example, to call a servlet having a URL http://localhost:81/SCM/register having asynchronous communication, the statement would be:

xmlHttp.open(“GET”,”http://localhost:81/SCM/register?user=”+user, true);

Here the value to be sent to the server is passed as a query string appended to the URL.

iii. send:

This sends the data to the server when the method is POST. If it is GET, then

null is send to the server. In case of POST, a string of name-value pair is set as its parameter. For example, to send user name and password to the server and the method is POST, the statements would be:

var params=”user=”+user+”&pass=”+pass;

xmlHttp.send(params)

That completes setting up the XMLHttpRequest.

3. Registering and implementing call-back handler:

There needs to be a handler that can be invoked when the response arrives. It is the callback handler. A callback handler is simply a function that is registered with the system and that is invoked by the system when the event for which it is registered. So in this case the event is arrival of data along with the response. To handle this event, a function has to be registered with the XMLHttpRequest which is done by the onreadystatechange property of XMLHttpRequest. So to register a function named handleStateChange(), the statement would be:

xmlHttp.onreadystatechange=handleStateChange;

The next step is to implement the handler. The basic functionalities that a handler should implement are retrieving data from XML response sent from the servlet and manipulating the current page on the browser according to the data received from the server. For example, to display the result coming from the server on the page, the code would be:

function handleStateChange()

{

if(xmlHttp.readyState==4)

{

if(xmlHttp.status==200)

{

document.getElementById(“results”).innerHTML=xmlHttp.responseText;

}

else

{

alert(“Error loading page\n”+ xmlHttp.status +”:”+ xmlHttp.statusText);

}

}

}

Here the element having the id results is a <div> tag. So whatever be the data coming from the server is displayed as child nodes of the results. The three properties that are being used here are-readyState, status and responseText. The readyState specifies whether data load operation is successful or not. Any value except 4 indicates that data is not yet available. Even then if the data contains a ‘file not found message’, then also the next part wouldn’t work as required. Hence, it is always better to check the status. The data is usable only if the status is 200. The next part is to extract the data and use it. The XMLHttpRequest instance has two properties-responseText and responseXML to extract data from the response. If data is in the form of text then responseTest can be used otherwise responseXML can be used.

The only piece of the puzzle is the server-side part. That’s what coming up.

4. Generate the XML response:

Whatever be the server-side technology, the implementation has to generate XML. In this case the technology is servlet. To generate the response the three things have to be done- first set the content type to text/xml, secondly get a writer object and then set the XML into the response using the writer object. The code would be something like:

response.setContentType(“text/xml”);

response.getWriter().write(“<valid>true</valid>”);

where response is an object of HttpServletResponse. That’s it. In the next section I would be putting it all together to develop a registration module that would check the availability of the user id.

AJAX and Servlets- In the Real World:

The module to be developed has to check the availability of a user id. Why use AJAX here? The answer is that if the user id is already taken, then it is always better to tell the user as soon as possible. By using AJAX this can be done once the user id has been entered. The AJAX would come into picture when the user id is filled and the user moves to next field. This module contain three major components:

1. ValidateAvail.js – JavaScript file containing all the client-side AJAX functions

2. Register.html – The registration page

3. CheckAvail.java – Servlet that does the server-side processing

So here is the code.

First lets have a look at the ValidateAvail.js. The first thing to do is setting up the XMLHttpRequest. Its being done by the following function:

var xmlHttp;// global instance of XMLHttpRequest

function createXmlHttpRequest()

{

if(window.ActiveXObject)

{

xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);

}

else if(window.XMLHttpRequest)

{

xmlHttp=new XMLHttpRequest();

}

}

Next the function that sets up the communication with the server

function startRequest()

{

createXmlHttpRequest();

var u1=document.f1.user.value;

xmlHttp.open(“GET”,”http://localhost:8080/SCM/checkAvail?user=”+u1

,true)

xmlHttp.onreadystatechange=handleStateChange;

xmlHttp.send(null);

}

This function also registers the callback handler which is handleStateChange. Next is the code for the handler.

function handleStateChange()

{

if(xmlHttp.readyState==4)

{

if(xmlHttp.status==200)

{

var message =

xmlHttp.responseXML

.getElementsByTagName(“valid”)[0]

.childNodes[0].nodeValue;

document.getElementById(“results”).innerHTML=message;

}

else

{

alert(“Error loading page\n”+ xmlHttp.status +”:”+

xmlHttp.statusText);

}

}

}

After checking the readyState and the status, the data is extracted from the response using JavaScript XML parsing APIs. The data is then passed on to the HTML page using DOM API. Now lets have a look at the HTML page. Only the relevant portion is being shown.

<tr>

<td width=”36%”>Userid</td>

<td width=”33%”>

<input type=”text” name=”user” onBlur=” startRequest();”/>

</td>

<td width=”31%” id=”results”>&nbsp;</td>

</tr>

The startRequest() function is called on the Blur event. Thus starting the AJAX process.

The next in line is the servlet code. Here it is:

package someorg;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

public class CheckAvail extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException {

UserOp userOp=new UserOp();//business layer class.

//implementation not shown for brevity

//get the userId

String targetId = request.getParameter(“user”);

//check the id. If it is not existing already then return true else false

if ((targetId != null) && !userOp.containsKey(targetId.trim())) {

response.setContentType(“text/xml”);

response.setHeader(“Cache-Control”, “no-cache”);

response.getWriter().write(“<valid>true</valid>”);

} else {

response.setContentType(“text/xml”);

response.setHeader(“Cache-Control”, “no-cache”);

response.getWriter().write(“<valid>false</valid>”);

}

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException {

doGet(request, response);

}

}

}

The servlet retrieves the value of parameter and then checks whether the user id is already existing in the database or not using the business layer class. If it does not exists, then the XML out put contains true as the node value of the node <valid> otherwise it would contain the value false. That’s it. This brings us to the end of this discussion. Using AJAX with servlet is just one of the many option available to a JEE developer. In the future I would be discussing other options including Struts and JSF. Till then…

SDL Programming in Linux: Introducing SDL

Game programming has come a long way since early Linux and Windows days. The time is gone when games were limited to Windows or to an extend Mac. Today, as Linux is gaining foothold in desktop market, the demand for Linux based games is growing. This has brought portability to the forefront even in the gaming segment. Birth of OpenGL was the first step in this regard. But OpenGL addressed only the rendering aspect of game programming. The major part that is communicating with varied input devices was left to the operating system. That is reason for the existence of various extensions to the OpenGL including GLUT(platform independent), MESA(OpenGL extension for *nix systems) and WOGL(OpenGL extension for Windows). Each of them has its own pros and cons. If a library is OS independent, then it was limited in utilization of all the available resources. If it was able to harness the power of underlying system, then such a library would be platform dependent. It was during such times of extreme choices that SDL came into picture. SDL is a library “by the game programmers for the game programmers”. Hence it doesn’t try to achieve the ‘unachievable’ by starting from the scratch. Instead it is built upon the existing libraries for each OS i.e. it uses DirectX for Windows and XWindows APIs for *nix systems. So the obvious question arises is how to harness the power of SDL on Linux? In this article, first in the series of four, I would discuss the steps to be followed in order to setup your Linux box for SDL programming and then a small application would be developed that would not only test the setup but also introduce you to the world of SDL programming. So lets get started.

What is SDL?

As already stated, SDL is library developed by the game programmers themselves. Hence the implementation is in such a way that it never gets in the way of programmers code. In nutshell one can say that it follows the philosophy of SMILE (Simple Makes It Lot Easier). This philosophy is evident in the functionalities provided by it which are:

  1. Initialization and Shutdown

  2. Input processing

  3. Timers

  4. Sound effects

  5. Graphics manipulation

  6. Network integration

  7. Threading requirements

All of these functionalities come into the gaming scenario now and again especially first five are the basis of any game. SDL makes dealing with each of them easier. Lets see how.

  1. Initialization and Shutdown:

Whenever a game starts, it must perform initialization routines including memory allocation, resource acquisition, loading any required data from the disk etc. To perform these routines, the programmer has to query the underlying OS to know the boundaries set by it. To achieve this end some code has to be written and again code has to be written to use the result of the query. SDL abstracts this with a single function: SDL_Init(). More about it in the next section.

  1. Input Processing:

In a gaming environment the input can be in the form of keyboard input, joystick, mouse and so on. The processing model provided by SDL is event based. Anyone who has worked in VB, Delphi or Xlib(or any of its variants) would feel at home with SDL’s event model. The base of this model is SDL_WaitEvent() method that takes SDL_Event as reference.

  1. Timers:

Without timers it is nearly impossible to imagine any challenging game. If one goes by standard methods, one would have to relay on the Timers provided by the platform. But with SDL, this is a thing of past. The Time and Timer APIs provided by it are lean, mean and clean in a platform and OS independent way. SDL_getTicks() is the core of SDL timer API.

  1. Sound Effects:

As with other functionalities provided by SDL, the functionalities related with sound is provided with minimum hassles. The sound support as a core sub-system is minimal in nature adhering to the keep-it-lean philosophy of SDL. But there are other libraries that provide the extended capabilities around SDL’s APIs.

  1. Graphics Manipulation:

With SDL one has option to work at raw pixel level or at higher level using OpenGL. Since OpenGL is available for every platform and it can render both 2D and 3D graphics in hardware accelerated mode, it is better to use OpenGL in conjunction with SDL.

  1. Networking Requirements:

Like other functionalities, networking is also important in the current genre of games. Understanding this importance, the developers of SDL provided APIs that does the ground-level works to setup the network connections and managing them, thus making networked multiplayer game less of enigma.

  1. Threading Requirements:

The pthreads library provided by POSIX is a platform independent way of working with threads. But the API works at low-level which can be confusing. In order to make threading simpler, SDL provides all the required functionalities in a high-level manner.

In essence, SDL provides for all the gaming requirements in a simple and portable way. Now that the intro to the functionalities is out of our way, we can actually see how the theory works out in real world.

Entering the world of SDL:

Now lets get into some coding using SDL for which following are steps:

1. Checking SDL configuration:

The best thing about Linux is that it is configured for various development environments if the selections are done correctly(and if a distro is being used). To check whether the SDL library is present or not just use the locate command at the prompt:

raj@linuxden# locate SDL.h

If locate doesn’t return anything, then you will have to download either the binaries or the source from the following site:

http://www.libsdl.org/

If the planning is to use OpenGL then do the same for it(just check out for MESA).

2. Initialization and Shutting down:

In this article, I will deal with initialization and shutting down of a game system. Before starting lets include the required headers:

#include “SDL.h”

#include<stdio.h>

All the required function are declared within SDL.h. next comes the well-known function main().

#include “SDL.h”

#include<stdio.h>

int main(int argc,char* argv[])

{

:

:

}

As stated earlier, SDL provides two functions to perform initialization and shutdown routines. For initialization the method provided is SDL_Init() which has to be used thus:

#include “SDL.h”

#include<stdio.h>

int main(int argc,char* argv[])

{

/*The following code does the initialization for Audio and Video*/

int i_error=SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|

SDL_INIT_CDROM);

:

}

The SDL_Init takes as a parameter the subsystems that need to be initialized apart from the default subsystems. Here I am initializing Video, audio and CDROM subsystems. If the initialization is unsuccessful then -1 will be returned i.e.

#include “SDL.h”

#include<stdio.h>

int main(int argc,char* argv[])

{

/*The following code does the initialization for Audio and Video*/

int i_error=SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|

SDL_INIT_CDROM);

/*If initialization is unsuccessful, then quit */

if(i_error==-1)

exit(1);

atexit(SDL_Quit);

:

}

To cleanup while exiting, the atexit can be used for small programs. Otherwise before calling quits, the dynamically loaded memory have to be freed using custom cleanup code. The atexit() function is passed the SDL_Quit function.

Now its time to find out how many CDROM drives are there in the system. Following code deals with it:

#include “SDL.h”

#include<stdio.h>

int main(int argc,char* argv[])

{

/*The following code does the initialization for Audio and Video*/

int i_error=SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|

SDL_INIT_CDROM);

int i_num=-1;

/*If initialization is unsuccessful, then quit */

if(i_error==-1)

exit(1);

atexit(SDL_Quit);

/*Enumerate the CDROM drives in the system*/

printf(“Drives available: %d\n”, SDL_CDNumDrives());

for ( i_num=0; i_num<SDL_CDNumDrives(); ++i_num )

{

printf(“Drive %d: \”%s\”\n”, i_num, SDL_CDName(i_num));

}

}

The SDL_CDNumDrives() returns the no. of CD drives present in a system. The next one i.e. SDL_CDName() takes an integer parameter and returns the corresponding drive name. that concludes our code section.

To run the code I have used the following command:

gcc `sdl-config –libs` enumCD.c -o enumCD

the `sdl-config –-libs` would include the necessary libraries. On the otherhand if make file is being used then:

all: enumCD

enumCD: enumCD.o

gcc `sdl-config –libs` enumCD.o -o enumCD

enumCD.o: enumCD.c

gcc -c `sdl-config –cflags` enumCD.c

Thus this brings us to the end of first part of this series. In this part I have just given you a taste of SDL programming and an entry point into the world of SDL. In the coming articles I will take up each subsystem and will take you deep into the world of SDL. So until next time.

Soya3D: First Look

I am back with more news from Soya3D. Having developed a ‘Hello World’ kinda application, I am both happy as well as a bit disappointed with the library. Before going into my impressions about the library have a look at the ‘Hello World’ kinda app’s code:

import sys,os, os.path, soya

#initialize soya
soya.init(title = “First”, width = 640, height =480)

#set the data path
soya.path.append(os.path.join(os.path.dirname(sys.argv[0]), “data”))

#create the root of the scene graph

scene = soya.World()

#load model
sun_model = soya.Model.get(“sun”)

#class that rotates the model. The class has been inherited from soya.Body. And it overrides advance_time for adding #rotation

class rotating_sun(soya.Body):
def advance_time(self, proportion):
soya.Body.advance_time(self, proportion)
self.rotate_y(proportion*15.0)
self.rotate_x(10)
#create and attach the model to the scene graph a.k.a world
sun = rotating_sun(scene, sun_model)

#create a light source
light = soya.Light(scene)
light.set_xyz(0.5, 0.0, 2.0)

#set the camera
camera = soya.Camera(scene)
camera.z = 2.0

soya.set_root_widget(camera)

soya.MainLoop(scene).main_loop()

The app loads a model and then rotates it. If you have programmed using TKinter library, you can notice the similarity. Now the good bits about Soya3D:

  • Ease of use in terms of library
  • Simple API model
  • Good amount of example codes
  • Step-by-step explanation
  • Rendering time is good

Now what disappoints me are:

  • The loading time for this simple app ~ 10  secs on my centrino core duo laptop. Thats a bit high. The load time can be discounted due to the interpreted nature of Python
  • Whenever I move the window of the app, the app freezes. Why does this happen – no idea. Couldnt get anything from the docs as well.

Apart from these two I did not encounter any dissapointments. If anyone has any work arounds for this do post. Till next time

Socket Programming in Java

In a world which is wired, standalone applications are becoming obsolete. The felicitators for the connectivity of applications, at low-level, are sockets. Any language, whether high-level or low-level, must provide APIs to handle sockets if they desire wide acceptance. Java is no exception. Java facilitates socket programming through its java.net package. And true to its philosophy, it abstracts out the most of the low-level ‘nitty-gritty’ associated with socket and provides a clean object-oriented API to work with. In this article I would discuss about how to use the java.net package, in order to net enable any application (CLI or GUI based) with TCP based sockets. The first section would be about what sockets are and how they have been supported in Java. In the second section, I would enumerate the steps to use sockets within an application. In the last section I would develop a real world application using sockets. That sets the course for this discussion.

Sockets – What are They:

If one looks up the definition, the most common one would be “A socket is one endpoint of a two-way communication link between two programs running on the network”. To put it differently, it is through sockets that applications access the network and transmit data. As varied are the purpose and platforms of applications, so are the types of sockets. There are three types of sockets:

1. Unix Domain Sockets

2. Internet Domain Sockets

3. NS Domain Sockets

Of these only Internet Domain Sockets are supported across all the platforms. So to maintain the cross-platform characteristic intact, Java supports only Internet Domain Sockets. The next question that arises is what are the characteristics of an Internet Domain Socket and what protocols are supported by it? Here are the answers:

Internet Domain Sockets:

By definition “An Internet socket (or commonly, a socket or network socket), is a communication end-point unique to a machine communicating on an Internet Protocol-based network, such as the Internet”. All applications communicating through the internet use network socket. The feature that distinguishes network socket from other sockets is the protocols that it supports. The supported protocols are:

1. TCP

2. UDP

3. Raw IP

The difference between them is based on whether the protocol is connection oriented or not. Here are the details:

1. TCP:

It is one of the core protocols of internet protocol suite. The protocol guarantees reliable and in-order (correct order of packets) delivery of data from sender to receiver. In other words it’s reliable. Second aspect of TCP is that it is connection oriented. That means, TCP requires that connection be made between sender and receiver before data is send. The socket associated with TCP is known as Stream Socket.

2. UDP:

Like TCP, UDP is also one of the core protocols of IP suite. However, unlike TCP, it neither guarantees in-order delivery of data nor does it requires a connection being established for sending the data. To put in short, UDP is unreliable and connectionless protocol. Sockets associated with UDP are known as Datagram Sockets.

3. Raw IP:

It is the non-formatted protocol as opposed to the TCP and UDP. It works at network and transport layers. A socket associated with Raw IP is known as Raw Sockets. UDP and TCP sockets just receive the payload or the data whereas Raw Sockets receive the header info of the packet along with the data. The downside of Raw Sockets is that it is tightly coupled with the implementation provided by the underlying host operating system.

Next lets see how Java places the different type of sockets in its libraries.

Sockets in Java:

Like all other functionalities provided by Java, functionalities to work with sockets are also ‘packaged’ as package and its classes. Following are the package and its main classes that help in accessing sockets:

1. java.net package

2. ServerSocket

3. Socket

Among the above Java, abstracts out, most of the low-level aspects of socket programming. Here are the details:

1. java.net package:

It contains all the classes required to create network enabled applications. ServerSocket and Socket are also part of this package. Apart from these classes, it also contains classes to connect to web server, create secured sockets etc.

2. ServerSocket:

This class provides server sockets or sockets at server side. Such sockets wait for requests over the network. Once such requests arrive, server socket performs operation based on the request and may return a result. The ServerSocket class wraps most of the options required to create server-side sockets.

3. Socket:

This class provides client-side socket or simply sockets. They are at the client side connecting to the server and sending the request to the server and accepting the returned result. Just like ServerSocket exposes only the compulsory parameters required to create a server-side socket, similarly, Socket asks the user to provide only those parameters that is most necessary.

That’s all about sockets and Java. In the next section, I would discuss about the steps involved in creating socket based applications.

Socket Programming- Step By Step:

Any net enabled application has two important parts – the code that executes at client-side and the code that executes at server-side. So the steps to use functionality of sockets can be partitioned into two major steps:

1. The Server or the server-side code

2. The Client or the client-side code

The multi-threaded nature of former can always be guaranteed whereas the later may or may not be multi-threaded.

1. The Server:

The main function of the server is to wait for the incoming requests and once such a request comes, service it. So the code to implement Server can be further broken down to following steps:

i. Establish a Server that monitors a particular port:

This is done by creating an instance of the ServerSocket class. There are four different ways to create an instance of ServerSocket. They are –

a. ServerSocket() – it simply sets the implementation that means everything is

taken as default values.

b. ServerSocket(int port)- it creates a server-side socket and binds the socket

to the given port no.

c. ServerSocket(int port, int backlog) – it not only binds the created socket to

the port but also create a queue of

length specified by the no. passed as

backlog parameter.

d. ServerSocket(int port, int backlog, InetAddress bindAddr)-

it creates a server-side socket that is bound to the specified port no. with the queue of length specified by backlog and bound to the address specified by bindAddr argument.

So to create a socket bound to port no. 8888 with a backlog queue of size 5 and bound with address of local host the statement would be:

ServerSocket server = new ServerSocket(8888, 5, InetAddress.getLocalHost() );

One point to keep in mind is that the above mentioned constructors return TCP sockets and not UDP sockets.

ii. Listen for incoming Requests:

Next step is to tell the newly created server socket to listen indefinitely and accept incoming requests. This is done by using the accept() method of ServerSocket class. When a request comes, accept() return a Socket object representing the connection. In code it would be:

Socket incoming = server.accept();

iii. Communicating with the Socket:

In other words, communicating with the Socket means reading from and writing to the Socket object. To communicate with a Socket object two tasks have to be performed. Firstly the Input and Output stream corresponding to the Socket object has to be obtained. That can be done by using getInputStream() and getOutputStream() methods of Socket class. In code it would be:

BufferedReader in = new BufferedReader

(new InputStreamReader(incoming.getInputStream()));

PrintWriter out = new PrintWriter

(incoming.getOutputStream(), true /* autoFlush */);

The second task is to read from and write to the Socket object. Since the communication has to continue till the client breaks the connection, the reading from and writing to is done within a loop as thus:

boolean done = false;

while (!done)

{

String line = in.readLine();

if (line == null) done = true;

else

{

out.println(“Echo: ” + line);

if (line.trim().equals(“BYE”))

done = true;

}

}

The actual syntax for reading and writing is not different from the I/O done for simple files.

iv. Closing the connection:

Once the client breaks the connection or stops sending the request, the Socket object representing the client has to be closed. This can be done by calling close() method on the Socket object. The statement would be:

incoming.close();

That’s how a Server is coded. Next section deals with creating a client.

2. The Client:

The main purpose of client is to connect to the server and communicate with it using the connection. So to code a client has following steps:

i. Connect to the Server:

Connecting with the server can be accomplished in two steps:

a. Creating a Socket object:

The socket at client side just needs to know the host name (the name of the machine where server is running) and the port where the server is listening. To create a Socket object, there are seven constructors provided by the Socket class of which the most commonly used are:

  • Socket() – Creates a new instance of Socket without connecting to

host

  • Socket(InetAddress address, int port) – creates a new Socket object and connects to the port specified at the given address.

  • Socket(java.lang.String host, int port) – same as first one except that instead of address, host name is used.

So to create a Socket object that connects to ‘localhost’ at 8888, the statement would be:

Socket s=new Socket(“localhost”,8888);

b. Connect to the Server:

This step comes into picture, if no argument constructor is used. It takes object of SocketAddress object as argument. So to connect to localhost at port 8888, the code will be:

Socket s= new Socket();

s.connect(new SocketAddress(“localhost”,8888));

ii. Communicating with the Server:

Communicating with the server using a socket at client side is not different when compared with how server communicates with client. Firstly, the input and output streams connected with the Socket object is to be retrieved thus:

BufferedReader in = new BufferedReader

(new InputStreamReader(s.getInputStream()));

PrintWriter out = new PrintWriter

(s.getOutputStream(), true /* autoFlush */);

Then read and write using the corresponding streams. For example, if the client just waits for the data sent by the server, the code would be

boolean more = true;

while (more)

{

String line = in.readLine();

if (line == null)

more = false;

else

System.out.println(line);

}

That’s all about steps in creating network enabled application. In the next section I would be developing a file server application with multi-threading to handle multiple clients.

Socket Programming – In Real World:

Its time to put theory to practice. The file server to be developed would provide the following services:

1. List the files that can be downloaded

2. Send the selected file

3. Process each request in a separate thread

It is from the solution to an exercise from Professor David Eck’s on-line textbook, published under an open content license at http://math.hws.edu/eck/cs124/javanotes4/c10/ex-10-4-

answer.html

There are two classes that form the server:

1. FileServer – sets up the server

2. ConnectionHandler – services the requests for sending of file to clients

Lets look at the implementation. First comes the FileServer class. It does the following tasks:

1. Checks the existence of the directory name specified

2. Sets up the server

3. Delegates the requests to be handled to object of ConnectionHandler class.

Following is the implementation of the class:

import java.net.*;

import java.io.*;

public class FileServer {

static final int LISTENING_PORT = 3210;

public static void main(String[] args) {

File directory; // The directory from which the

// gets the files that it serves.

ServerSocket listener; // Listens for connection requests.

Socket connection; // A socket for communicating with

// a client.

/* Check that there is a command-line argument.

If not, print a usage message and end. */

if (args.length == 0) {

System.out.println(“Usage: java FileServer <directory>”);

return;

}

/* Get the directory name from the command line, and make

it into a file object. Check that the file exists and

is in fact a directory. */

directory = new File(args[0]);

if ( ! directory.exists() ) {

System.out.println(“Specified directory does not exist.”);

return;

}

if (! directory.isDirectory() ) {

System.out.println(“The specified file is not a directory.”);

return;

}

/* Listen for connection requests from clients. For

each connection, create a separate Thread of type

ConnectionHandler to process it. The ConnectionHandler

class is defined below. The server runs until the

program is terminated, for example by a CONTROL-C. */

try {

listener = new ServerSocket(LISTENING_PORT);

System.out.println(“Listening on port ” + LISTENING_PORT);

while (true) {

connection = listener.accept();

new ConnectionHandler(directory,connection);

}

}

catch (Exception e) {

System.out.println(“Server shut down unexpectedly.”);

System.out.println(“Error: ” + e);

return;

}

} // end main()

:

:

}

Next comes the ConnectionHandler class. The important aspect of this class is that it is a static inner class of FileServer class. The tasks carried out by this class are:

1. Start the thread – it is done in the constructor of the class

2. Send the list of downloadable files – the sendIndex() method contains the logic

for sending the list.

3. Sending the selected file – this task is performed by sendFile() method

4. Communication with client – this task is done in the run() method. This method

also calls other methods as required.

Following is the implementation. The class is

import java.net.*;

import java.io.*;

public class FileServer {

static final int LISTENING_PORT = 3210;

public static void main(String[] args) {

File directory; // The directory from which the

// gets the files that it serves.

ServerSocket listener; // Listens for connection requests.

Socket connection; // A socket for communicating with

// a client.

/* Check that there is a command-line argument.

If not, print a usage message and end. */

if (args.length == 0) {

System.out.println(“Usage: java FileServer <directory>”);

return;

}

/* Get the directory name from the command line, and make

it into a file object. Check that the file exists and

is in fact a directory. */

directory = new File(args[0]);

if ( ! directory.exists() ) {

System.out.println(“Specified directory does not exist.”);

return;

}

if (! directory.isDirectory() ) {

System.out.println(“The specified file is not a directory.”);

return;

}

/* Listen for connection requests from clients. For

each connection, create a separate Thread of type

ConnectionHandler to process it. The ConnectionHandler

class is defined below. The server runs until the

program is terminated, for example by a CONTROL-C. */

try {

listener = new ServerSocket(LISTENING_PORT);

System.out.println(“Listening on port ” + LISTENING_PORT);

while (true) {

connection = listener.accept();

new ConnectionHandler(directory,connection);

}

}

catch (Exception e) {

System.out.println(“Server shut down unexpectedly.”);

System.out.println(“Error: ” + e);

return;

}

} // end main()

static class ConnectionHandler extends Thread {

// An object of this class is a thread that will

// process the connection with one client. The

// thread starts itself in the constructor.

File directory; // The directory from which files are served

Socket connection; // A connection to the client.

TextReader incoming; // For reading data from the client.

PrintWriter outgoing; // For transmitting data to the client.

ConnectionHandler(File dir, Socket conn) {

// Constructor. Record the connection and

// the directory and start the thread running.

directory = dir;

connection = conn;

start();

}

void sendIndex() throws Exception {

// This is called by the run() method in response

// to an “index” command. Send the list of files

// in the directory.

String[] fileList = directory.list();

for (int i = 0; i < fileList.length; i++)

outgoing.println(fileList[i]);

outgoing.flush();

outgoing.close();

if (outgoing.checkError())

throw new Exception(“Error while transmitting data.”);

}

void sendFile(String fileName) throws Exception {

// This is called by the run() command in response

// to “get <fileName>” command. If the file doesn’t

// exist, send the message “error”. Otherwise,

// send the message “ok” followed by the contents

// of the file.

File file = new File(directory,fileName);

if ( (! file.exists()) || file.isDirectory() ) {

// (Note: Don’t try to send a directory, which

// shouldn’t be there anyway.)

outgoing.println(“error”);

}

else {

outgoing.println(“ok”);

TextReader fileIn = new TextReader( new FileReader(file) );

while (fileIn.peek() != ”) {

// Read and send lines from the file until

// an end-of-file is encountered.

String line = fileIn.getln();

outgoing.println(line);

}

}

outgoing.flush();

outgoing.close();

if (outgoing.checkError())

throw new Exception(“Error while transmitting data.”);

}

public void run() {

// This is the method that is executed by the thread.

// It creates streams for communicating with the client,

// reads a command from the client, and carries out that

// command. The connection is logged to standard output.

// An output beginning with ERROR indicates that a network

// error occurred. A line beginning with OK means that

// there was no network error, but does not imply that the

// command from the client was a legal command.

String command = “Command not read”;

try {

incoming = new TextReader( connection.getInputStream() );

outgoing = new PrintWriter( connection.getOutputStream() );

command = incoming.getln();

if (command.equals(“index”)) {

sendIndex();

}

else if (command.startsWith(“get”)){

String fileName = command.substring(3).trim();

sendFile(fileName);

}

else {

outgoing.println(“unknown command”);

outgoing.flush();

}

System.out.println(“OK ” + connection.getInetAddress()

+ ” ” + command);

}

catch (Exception e) {

System.out.println(“ERROR ” + connection.getInetAddress()

+ ” ” + command + ” ” + e);

}

finally {

try {

connection.close();

}

catch (IOException e) {

}

}

}

} // end nested class ConnectionHandler

}

That completes the implementation of the File Server. The discussion has left out the UDP based sockets. I will be dealing with it in the next part. Till then…