Tuesday, December 14, 2010

String matching in a file using (sed/grep) commands in LINUX

SED command using & for match string:
The special character "&" corresponds to the pattern found.
Suppose the filename ch.txt contains following lines.  And we want for each function name to add (* ) brackets .
xpcom_ProcessNextEvent(int state); 
loc_wer_test(int state);
Following command converts content in ch.txt into following format and stored output in ch1.txt file.
$sed 's/[a-zA-Z]*_*[a-zA-Z]*_*[a-zA-Z]*(/int (*&)/' < ch.txt >  ch1.txt
The Output of above command in ch1.txt file is as per follows:
int (*xpcom_ProcessNextEvent()int state); 
int (*loc_wer_test()int state);


Now we want to swap "()" bracket with ")(" from the output of above command. Following commands does that job.
$sed 's/()/)(/'  < ch1.txt > ch2.txt
int (*xpcom_ProcessNextEvent)(int state); 
int (*loc_wer_test)(int state);

You could also double a pattern, e.g. the first number of a line:
$ echo "123 abc" | sed 's/[0-9]*/& &/'
123 123 abc
In above command "123 abc" was input and output was "123 123 abc".
You can have any number of "&" in the replacement string.

GREP command to copy a matching string line from a file to another file.
Suppose input_filename contains following:
 //Escape() Function hook
  int js_js_str_fun (...)
 {
    .....
  }
int js_str_fun2 (...)
{
    .....
 }

Using following command we can extract a line with function name:
$grep "int .*(.*)"  input_filename > output_filename

Above commands stores following output in output_filename file:
  int js_js_str_fun (...)
int js_str_fun2 (...)

Wednesday, December 8, 2010

Dynamic Lib using dlopen and dlsym

dlopen system call loads dynamic library and returns handle to dynamic library.  If dlopen() fails it returns NULL
dlsym takes the library handle returnd by dlopen and symbol name as input, and  returns the address where that symbol is loaded. If the symbol is not found, dlsym returns NULL
dlerror returns NULL if no errors have occurred since initialization or since it was last called. (Calling dlerror() twice consecutively, will always result in the second call returning NULL.)

#include <stdio.h>
#include <dlfcn.h>

typedef void *(*func_t)(hooks *);

int main()
{
    // declare handle variable for dynamic library
    void *handle;
  
    double (*cosine)(double);

    // open the dynamic library
    handle = dlopen ("libm.so", RTLD_LAZY);
    if (!handle) {
        fprintf (stderr, "%s\n", dlerror());
        exit(1);
    }

    func_t initializer_fn = (func_t)dlsym(handle, "initializer");
    if (initializer_fn) {
           // call function
 (*initializer_fn)(this);
    }

    // Initialize cosine with function pointer of "cos".
   cosine = dlsym(handle, "cos");
   // call "cos" function using function pointer
   fprintf (stderr, "%f\n", (*cosine)(2.0));

   dlclose(handle);
    return 0;
} // end of main

// functions defined in library file
void initializer(hooks *libifc)
{
}

Monday, December 6, 2010

Firefox about: urls

Firefox can be tweak using about:config url, that allows to change user preferences.
There are other about: urls listed below. I tested them on FF 3.5.3.

about:blank  : shows a blank web page.
about:buildconfig  : shows mozilla build options
about:cache
about:cache?device=memory  : Lists memory cache entries
about:config  : modifies user preferences.
about:credits  : Shows an alphabetical list of mozilla contributors
about:logo  : shows mozilla logo
about:plugins  : shows all installed plugins
about:crashes  : shows Firefox crash reports if any

Other about: URLs showing some messages:
about:mozilla
about:robots
about:privatebrowsing
about:sessionrestore

Friday, December 3, 2010

Firefox Extension and Web Page Script Execution

To access Web page Document from Extension
  webpageDocument = top.window.content.document;

To Execute Web Page defined function from Firefox Extension

 var wm = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator);

    var currentWindow = wm.getMostRecentWindow('navigator:browser').getBrowser().contentWindow;
    var sandbox = new Components.utils.Sandbox(SandboxURL);
    // __.proto__  hack removes need of using window.a, window.alert()
    sandbox.__proto__ = currentWindow.wrappedJSObject;
    //  assume web page script defines variable "a"
    var pageResult = Components.utils.evalInSandbox("alert(a);", sandbox);
    dump("\n\n Web  page Function execution Result = " + pageResult);

In FF Extension to execute a Script in a Sandbox and allowing Extension function to be accessed by Sandbox object
Following code I also added to MDN [1].

 // Chrome (FF Extension) custom Functions:
function sandboxAlert(msg){
    dump("\n Inside sandboxAlert");
    msg = XPCSafeJSObjectWrapper(msg);
    dump("\n msg = " + msg);
}

// variable declared in Chrome code
var tempval = 10;

function sandboxFun1(){
    return tempval;
}

    // Chrome (Firefox Extension) code

    // create sandbox enviornment to execute script.
    // SandboxURL is required for XHR requests. Same domain are allowed.
    var sandbox = new Components.utils.Sandbox(SandboxURL);

    sandbox.y = 5;  // insert property 'y' with value 5 into global scope.
    var scriptText = "var x = 2 + sandboxFun1(); var k = y + 15; sandboxAlert('Testing'); x + 3";

    // // include chrome function into sandbox context.
    sandbox.importFunction(sandboxFun1);
    sandbox.importFunction(sandboxAlert);

    // // execute script into sandbox object
    var sandboxResult = Components.utils.evalInSandbox(scriptText, sandbox);


References:
1. Mozilla FF Extension evalInSandbox

Tuesday, November 30, 2010

Upgrading Ubuntu 10.04 (Lucid) to 10.10 (Maverick)

Steps to upgrade ubuntu v10.04 to v10.10 are very simple.
Option A. Using Update Manager (System -> Adminstration -> Update Manager)
 1. Start Update Manager.
 2. Click on Settings button
 3. Choose the Update Tab in Software Sources.
 4. Select Normal releases in the Show new distribution releases: drop-down menu and click on Close button.
 5. Back in Update Manager  and click on Check Button.
 6. Update Manager shows the new release is available.  Click on Upgrade button to start new distribution upgrade on your system.

Option B.
 1. Open Software Sources (System -> Adminstration -> Software Sources)
 2. Choose the Update Tab in Software Sources.
 3. Select Normal releases in the Show new distribution releases: drop-down menu and click on Close button. 
 4. Open Update Manager (System -> Adminstration -> Update Manager) and click on Check Button. 
 5. Update Manager shows the new release is available.  Click on Upgrade button to start new distribution upgrade on your system.

Hope this simple tutorial helps! 

Monday, November 15, 2010

Food to control Abdominal Fat

It's better to know which food is good for healthy and provides nutrition to our body, so that we can control abdominal fat.
First I will describe vegetables that helps against fighting abdominal fat, then I will explains fruits useful for the same purpose.

A. Vegetables
1. Broccoli: Broccoli is high in vitamins C, K, and A, as well as dietary fiber. Broccoli is also an excellent source of indole-3-carbinol, a chemical which boosts DNA repair in cells and appears to block the growth of cancer cells. Broccoli is a potent modulator of the innate immune response system with anti-viral, anti-bacterial and anti-cancer activity.
2. Tomatoes:  It contains lycopene, one of the most powerful natural antioxidants. Tomato consumption has been associated with decreased risk of breast cancer, head and neck cancers and might be strongly protective against neurodegenerative diseases.
3. Cauliflower: Cauliflower is low in fat, high in dietary fiber, folate, water and vitamin C, possessing a very high nutritional density.  Cauliflower is a source of indole-3-carbinol, a chemical which boosts DNA repair in cells and appears to block the growth of cancer cells.
4. Cabbage: Cabbage is an excellent source of vitamin C. It also contains significant amounts of glutamine, an amino acid that has anti-inflammatory properties. Fresh cabbage juice has been shown to promote rapid healing of peptic ulcers. Cabbage can also be included in dieting programs, as it is a low calorie food.
5. Mushroom: Mushrooms are high in dietary fiber, protein, and vitamins such as thiamine, riboflavin, niacin, biotin, cobalamins, and ascorbic acid.

B. Fruits
1.  Apple: Apples may reduce the risk of colon cancer, prostate cancer and lung cancer.[53] Compared to many other fruits and vegetables, apples contain relatively low amounts of vitamin C, but are a rich source of other antioxidant compounds. However, apple seeds are mildly poisonous, containing a small amount of amygdalin, a cyanogenic glycoside; it usually is not enough to be dangerous to humans, but can deter birds.
2.  Pineapple: Pineapple is a good source of manganese, and also contains significant amounts of vitamin C, and vitamin B1. Consumers of pineapple have claimed that pineapple has benefits for some intestinal disorders, and others believe it serves as a pain reliever; still others claim that it helps to induce childbirth when a baby is overdue.
3.  Orange: Oranges contains carbohydrates and is a good source of dietary fibers.

Above list may not be complete. But it gives some awareness to readers that use of fruits and vegetables in our daily diet not only provides nutritions but also dietary fiber to fight against abdominal fat.

Thursday, November 4, 2010

Examples of Creating Map of Maps in C++ or Multilevel Maps in C++

To create map of map in C++ is very simple.
Map is a sorted associative array of unique keys and associated data. The elements of the map are internally sorted from lowest to highest key value.

Example 1:
//Program to create multi level map in C++
#include <iostream>
#include <map> // header file needed for to use MAP STL

using namespace std;

int main(void)
{
//Define multilevel map. map within a map.
map<int, map<int,char> > myMap;
myMap[1][1] = 'A';
myMap[1][2] = 'B';
myMap[2][1] = 'C';
myMap[2][2] = 'D';

cout << "[1][1] = " << myMap[1][1] << endl;
cout << "[1][2] = " << myMap[1][2] << endl;
cout << "[2][1] = " << myMap[2][1] << endl;
cout << "[2][2] = " << myMap[2][2] << endl;

return 0;
}

//Save a file as multimap.cpp

To Compile and execute it on Ubuntu use following commands:
$ g++ multimap.cpp -o multimap
$ ./multimap

[1][1] = A
[1][2] = B
[2][1] = C
[2][2] = D


Example 2: 

#include <iostream>
#include <string>
#include <map>

using namespace std;

typedef map<int, string> innerMap;
typedef map<double, innerMap> mainMap;

mainMap m;


void print()
{
  map<double, innerMap >::iterator it;
  map<int, string>::iterator inner_it;

  for ( it=m.begin() ; it != m.end(); it++ ) {
    cout << "\n\nNew element\n" << (*it).first << endl;
    for( inner_it=(*it).second.begin(); inner_it != (*it).second.end(); inner_it++)
      cout << (*inner_it).first << " => " << (*inner_it).second << endl;
  }
}

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

  // First insert an element into outermap
  m.insert (make_pair (2.4, innerMap ()));
  // Now insert elements into innermap
  m[2.4].insert (make_pair (2, "two"));
  m[2.4].insert (make_pair (5, "five"));

  // First insert an element into outermap
  m.insert (make_pair (0.6, innerMap ()));
  // Now insert elements into innermap
  m[0.6].insert (make_pair (5, "five"));
  m[0.6].insert (make_pair (1, "one"));
  m[0.6].insert (make_pair (2, "two"));

  // print elements in the mainMap
  print();
    
}

Output of above program (Example 2):
New element
0.6
1 => one
2 => two
5 => five

New element
2.4
2 => two
5 => five

Example 3: Uses "multimap" STL
Note that, "mutimap" STL does not support [], therefore we cannot use syntax "m[].insert( make_pair())"  we used in Example 2 to insert element.


#include <iostream>
#include <string>
#include <map>

using namespace std;

typedef multimap<int, string> innerMap;
multimap<double, innerMap> mainMap;

void print()
{
  multimap<double, innerMap >::iterator it;
  multimap<int, string>::iterator inner_it;

  for ( it=mainMap.begin() ; it != mainMap.end(); it++ ) {
    cout << "\n\nNew element\n" << (*it).first << endl;
    for( inner_it=(*it).second.begin(); inner_it != (*it).second.end(); inner_it++)
      cout << (*inner_it).first << " => " << (*inner_it).second << endl;
  }
}

void insert1(multimap<double, innerMap >::iterator it)
{
  it->second.insert (make_pair (2, "two"));
  it->second.insert (make_pair (5, "five"));
  it->second.insert (make_pair (2, "two"));

}

int main (int argc, char *argv[])
{
  multimap<double, innerMap >::iterator it;

  // First insert an element into outermap
  it = mainMap.insert (make_pair (2.4, innerMap ()));
  // Now insert elements into innermap
  insert1(it);

  // First insert an element into outermap
  it = mainMap.insert (make_pair (0.6, innerMap ()));
  // Now insert elements into innermap
  it->second.insert (make_pair (5, "five"));
  it->second.insert (make_pair (1, "one"));
  it->second.insert (make_pair (2, "two"));
  it->second.insert (make_pair (5, "five"));
  it->second.insert (make_pair (5, "five"));

  // print elements in the mainMap
  print();  
}




Output of the above program (Example 3):

New element
0.6
1 => one
2 => two
5 => five
5 => five
5 => five


New element
2.4
2 => two
2 => two
5 => five


Example 4:
how to find out if a particular key exists in the map or not?



#include <iostream>
#include <string>
#include <map>


using namespace std;


typedef multimap<int, string> innerMap;
multimap<string, innerMap> mainMap;


void insert1(multimap<string, innerMap >::iterator it)
{
  it->second.insert (make_pair (2, "two"));
  it->second.insert (make_pair (5, "five"));
  it->second.insert (make_pair (2, "two"));


}


int main (int argc, char *argv[])
{
  multimap<string, innerMap >::iterator it;


  // First insert an element into outermap
  it = mainMap.insert (make_pair ("1st Element Key", innerMap ()));
  // Now insert elements into innermap
  insert1(it);


  // First insert an element into outermap
  it = mainMap.insert (make_pair ("2nd element Key", innerMap ()));
  // Now insert elements into innermap
  it->second.insert (make_pair (5, "five"));
  it->second.insert (make_pair (1, "one"));
  it->second.insert (make_pair (2, "two"));
  it->second.insert (make_pair (5, "five"));
  it->second.insert (make_pair (5, "five"));


  // Find the key in the mainMap
  it = mainMap.find("2nd element Key");
  if (it != mainMap.end()) {
    cout << "\n Key Found!" << endl;
  } else {
    cout << "\n Key Not Found!" << endl;
  }
}


Output of the above program (Example 4):


 Key Found!




Wednesday, November 3, 2010

Creating C++ Component / Interface using Mozilla Build System

This is a step-by-step guide to create C++ Component / Interface, build using Mozilla build system, and test our component using extension and web page. I tested this on Ubuntu 10.04.

1. Create a directory with the name of your extension under "/mozilla/extensions/" directory. Use only lowercase letter. Let say we created a directory "krpextension"

2. Create "Makefile.in" in krpextension directory.
#/* Makefile.in under /mozilla/extensions/krpextension directory */
DEPTH = ../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = krpextension
DIRS = public src
XPI_NAME = krpextension
INSTALL_EXTENSION_ID = krpextension@mycompany.com
XPI_PKGNAME = krpextension
USE_EXTENSION_MANIFEST = 1
DIST_FILES = install.rdf
include $(topsrcdir)/config/rules.mk
#/* End of Makefile */

3. Create two subdirectories in "krpextension" directory namely "public" and "src". Public subdirectory to hold our ".idl" file and src subdirectory to hold component header and implementation files.  Each subdirectory in-turn contains its own makefile. Step 4 contains Makefile for "public" directory and Step 5 contains Makefile for "src" directory.

4. change directory to "public" and create "Makefile.in"
#/* Makefile.in under "/mozilla/extensions/krpextension/public" directory */

DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = krpextension
XPIDL_MODULE = krpextension
XPI_NAME = krpextension
XPIDLSRCS = \
krpIComponent.idl \
$(NULL)
include $(topsrcdir)/config/rules.mk

#/* end of Makefile */

5. change directory to "src" and create "Makefile.in"
#/* Makefile.in under "/mozilla/extensions/krpextension/src" directory */
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
IS_COMPONENT = 1
MODULE = krpextension
LIBRARY_NAME =  krpExtension
USE_STATIC_LIBS = 1
XPI_NAME = krpextension
REQUIRES = xpcom \
 string \
 $(NULL)
CPPSRCS = \
 krpComponent.cpp \
 krpExtension.cpp \
 $(NULL)
include $(topsrcdir)/config/rules.mk
EXTRA_DSO_LDOPTS += \
  $(XPCOM_GLUE_LDOPTS) \
  $(NSPR_LIBS) \
  $(NULL)
#/* end of Makefile */

6. Change to "public" sub-directory under "/mozilla/extension/krpextension" and now we will create our own Interface definition file (.idl) in public directory, Let say "krpIComponent.idl", if you used other name than "krpIComponent" then replace each occurring of  krpIComponent with your custom name of Interface. 
/* krpIComponent.idl file in public subdirectory */
#include <stdio.h>
#include "nsISupports.idl"
[scriptable, uuid(1c0856f7-ed61-471e-9dac-442565a5d1d2)]
interface krpIComponent : nsISupports
{
  unsigned long long Add(in unsigned long long num1, in unsigned long long num2); 
  unsigned long long Sub(in unsigned long long num1, in unsigned long long num2);
};
/* End of krpIComponent.idl file */

7. Change to src sub-directory under /mozilla/extension/krpextension, now we will create header and implementation file for our interface.
/* krpComponent.h   header file for our component */
#ifndef __KRPCOMPONENT_H__
#define __KRPCOMPONENT_H__
#include  <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "krpIComponent.h"
#include "nsIObserverService.h"
#include "nsServiceManagerUtils.h"
#define KRPCOMPONENT_CLASSNAME "krpcomponent"
#define KRPCOMPONENT_CID                                \
{ /* 1c0856f7-ed61-471e-9dac-442565a5d1d2 */            \
  0x1C0856F7, 0xED61, 0x471E,                           \
  {0x9D, 0xAC, 0x44, 0x25, 0x65, 0xA5, 0xD1, 0xD2}      \
}
#define KRPCOMPONENT_CONTRACTID "@mycompany.com/krpcomponent;1" 
/* Header file */
class krpComponent: public krpIComponent
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_KRPICOMPONENT
  krpComponent();
private:
  ~krpComponent();
protected:
};
#endif // __KRPCOMPONENT_H__
/* End of krpComponent.h header file */


/*krpComponent.cpp C++ Implementation file of our component */
#include "krpComponent.h"
/* Implementation file */
NS_IMPL_ISUPPORTS1(krpComponent, krpIComponent)
krpComponent::krpComponent()
{
  /* member initializers and constructor code */
}
krpComponent::~krpComponent()
{
  /* destructor code */
}
/* unsigned long long Add (in unsigned long long num1, in unsigned long long num2); */
NS_IMETHODIMP krpComponent::Add(PRUint64 num1, PRUint64 num2, PRUint64 *_retval NS_OUTPARAM)
{
  *_retval = num1 + num2;
    return NS_OK;
}
/* unsigned long long Sub (in unsigned long long num1, in unsigned long long num2); */
NS_IMETHODIMP krpComponent::Sub(PRUint64 num1, PRUint64 num2, PRUint64 *_retval NS_OUTPARAM)
{
  if(num1 > num2)
    *_retval = num1 - num2;
  else
    *_retval = num2 - num1;
    return NS_OK;
}
/* End of implementation class of our component. */

8. Now we will create module definition file lets say "krpExtension.cpp". If you use other name then replace all occurrences of krpExtension or krpExtension.cpp with your custom name. 
/*krpExtension.cpp Module definition file */
#include "nsXPCOM.h"
#include "nsIGenericFactory.h"
/**
 * Components to be registered
 */
#include "krpComponent.h"
NS_GENERIC_FACTORY_CONSTRUCTOR(krpComponent)
//----------------------------------------------------------
static const nsModuleComponentInfo components[] =
{
{
KRPCOMPONENT_CLASSNAME,
KRPCOMPONENT_CID,
KRPCOMPONENT_CONTRACTID,
krpComponentConstructor
},
};
NS_IMPL_NSGETMODULE(krpExtension, components)
/* end of krpExtension.cpp File */

9. Now to integrate our component into Extension, we will create a custom extension. In "/mozilla/extensions/krpextension" create "install.rdf" file.
/*install.rdf file contents */
  <?xml version="1.0" encoding="UTF-8"?>
<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
     xmlns:em="http://www.mozilla.org/2004/em-rdf#">
  <Description about="urn:mozilla:install-manifest">
    <em:id>krpextension@mycompany.com</em:id>
    <em:version>0.1</em:version>
    <em:targetApplication>
      <!-- Firefox -->
      <Description>
        <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
        <em:minVersion>3.0</em:minVersion>
        <em:maxVersion>3.6.*</em:maxVersion>
      </Description>
    </em:targetApplication>
    <!-- front-end metadata -->
    <em:name>My First Interface Extension</em:name>
    <em:description>Just an FF Interface Example.</em:description>
    <em:creator>kailas</em:creator>
    <em:homepageURL>http://kailaspatil.blogspot.com/</em:homepageURL>
  </Description>
</RDF>
/*install.rdf file ends here */

10. Now create another file "jar.mn" in "/mozilla/extensions/krpextension" directory.
/* jar.mn file contents */
krpextension.jar:
% content krpextension %content/
% locale krpextension en-US %locale/en-US/
% skin krpextension classic/1.0 %skin/
% overlay chrome://browser/content/browser.xul  chrome://krpextension/content/ff-overlay.xul
  content/overlay.js          (chrome/content/overlay.js)
  content/ff-overlay.xul         (chrome/content/ff-overlay.xul)
  content/ff-overlay.js (chrome/content/ff-overlay.js)
  content/about.xul         (chrome/content/about.xul)
  locale/en-US/overlay.dtd         (chrome/locale/en-US/overlay.dtd)
  locale/en-US/about.dtd         (chrome/locale/en-US/overlay.dtd)
  locale/en-US/overlay.properties (chrome/locale/en-US/overlay.properties)
  skin/overlay.css         (chrome/skin/overlay.css)
/* end of jar.mn file */
The files in jar.mn reflects the XUL/JavaScript files in your custom Extension.
Use Mozilla addon to build an empty extension for Firefox, with name krpextension. Copy its "chrome" directory including subdirectories "content, locale, and skin" in chrome directory into our extension directory, i.e "/mozilla/extensions/krpextension". Note that the paths in parentheses point to actual files.

11. Now run "make" command in "mozilla/$(OBJ_DIR)$" or "make -f client.mk build" command in "/mozilla" directory. If you are using make -f client.mk build command then make sure that you setup ".mozconfig" file.  Pls read an article https://developer.mozilla.org/en/build_documentation to build firefox and prerequisites required to build Firefox. 

12. Our component should be build successfully, and in "Tools->Addons->Extension" Tab you should see our custom Extension.

13. To test our component with Extension and Webpage.  First we will test it with Extension. Open overlay.js file in our extension folder "/mozilla/extensions/krpextension/chrome/content/overlay.js".  In OnLoad: function, add following lines of code to test our component. 
/*********************/
   var instance = Components.classes["@mycompany.com/krpcomponent;1"].getService();
    var obj =instance.QueryInterface(Components.interfaces.krpIComponent);
    var result = obj.Sub(10, 5);
    alert("Sub(10-5) = " + result);
/******************/
Each time firefox will start, our custom extension will start, and during initialization of our extension it will call our component method (i.e Sub(10,5) which will return result of Subtraction operation and its get displayed to user using alert box. 

Now we test our component using a Web page. Create a HTML file on local system, and use following script to test our component. It should display the correct result of Addition operation.
/************************/
<script>
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
const cid = "@mydomain.com/XPCOMSample/krpComponent;1";
var obj = Components.classes[cid].createInstance();
var obj1 = obj.QueryInterface(Components.interfaces.KFFComponent);


               var res = obj1.Add(10, 5);
alert('Performing 10 + 5  =  ' +  res );

} catch (err) {
alert(err);
}
</script>
/************************************/

Tuesday, November 2, 2010

Creating C++ Component / Interface of Firefox Using Gecko-SDK

This is step-by-step guide to create, build, register and use a XPCOM component/Interface on Linux (Ubuntu)

A. Creating A Component
Step 1: Download Gecko SDK (gecko-sdk-i686-pc-linux-gnu-X.X.X.X) and Extract it to local directory  "gecko-sdk".
Step 2: Use a utility "uuidgen" to generate UUID for our main Interface.
Step 3: Create an Interface defination file "KFFComponent.idl", use following template, simply replace uuid(1c0856f7-ed61-471e-9dac-442565a5d1d2) with your unique uuid(your_UUID) field.


#include "nsISupports.idl"
[scriptable, uuid(1c0856f7-ed61-471e-9dac-442565a5d1d2)]
interface KFFComponent : nsISupports
{
  unsigned long long Add(in unsigned long long num1, in unsigned long long num2);
  unsigned long long Sub(in unsigned long long num1, in unsigned long long num2);
};

Step 4: Open command prompt and go to "gecko-sdk/bin" and run following command:
$ ./xpidl  -m  header  -I_DIR_    KFFComponent.idl

Replace "_DIR_" with the full path to the "gecko-sdk/idl". Above command will create "KFFComponent.h" header file.

Step 5: Now to create typelib file, execute following command
$ ./xpidl  -m  typelib  -I_DIR_   KFFComponent.idl
Replace "_DIR_" with the full path to the "gecko-sdk/idl". Above command will create  "KFFComponent.xpt" typelib file

Step 6: Interface header file contains the template for building our component header file as well as C++ Implementation file.

Step 7: Create our own component Header file "krpComponent.h", use following contents:

#ifndef _KRP_COMPONENT_H_
#define _KRP_COMPONENT_H_
#include "KFFComponent.h"
#define KRP_COMPONENT_CONTRACTID "@mydomain.com/XPCOMSample/krpComponent;1"
#define KRP_COMPONENT_CLASSNAME "First XPCOM Sample Interface"
#define KRP_COMPONENT_CID {0x462EF8EF, 0x9A05, 0x49DE, {0x97, 0xAC, 0x82, 0x2A, 0x6C, 0x46, 0xD2, 0xDC } }


/* KRP_COMPONENT_CID = GUID (462EF8EF-9A05-49DE-97AC-822A6C46D2DC)
    Note: Replace GUID with your own GUID field
*/
/* Header file */
class krpComponent : public KFFComponent
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_KFFCOMPONENT
  krpComponent();
private:
  ~krpComponent();
protected:
  /* additional members */
};
#endif  /* end of _KRP_COMPONENT_H_ */

Step 8: Create our won C++ Implementation file for the Componenet "krpComponent.cpp".

#include "krpComponent.h"
/* Implementation file */
NS_IMPL_ISUPPORTS1(krpComponent, KFFComponent)
krpComponent::krpComponent()
{
  /* member initializers and constructor code */
}
krpComponent::~krpComponent()
{
  /* destructor code */
}
/* unsigned long long Add (in unsigned long long num1, in unsigned long long num2); */
NS_IMETHODIMP krpComponent::Add(PRUint64 num1, PRUint64 num2, PRUint64 *_retval)
{
  *_retval = num1 + num2;
  return NS_OK;
}
/* unsigned long long Sub (in unsigned long long num1, in unsigned long long num2); */
NS_IMETHODIMP krpComponent::Sub(PRUint64 num1, PRUint64 num2, PRUint64 *_retval)
{
  *_retval = num1 - num2;
  return NS_OK;
}
/* End of implementation class template. */

Step 9: Create our own Module definition file "krpComponentModule.cpp".
// This is necessary file to include Mozill Generic definations
#include "nsIGenericFactory.h" 
//My Component Header File 
#include "krpComponent.h" 
NS_GENERIC_FACTORY_CONSTRUCTOR(krpComponent)
static nsModuleComponentInfo components[] =
{
    {
       KRP_COMPONENT_CLASSNAME, 
       KRP_COMPONENT_CID,
       KRP_COMPONENT_CONTRACTID,
       krpComponentConstructor,
    }
};
NS_IMPL_NSGETMODULE("krpComponentsModule", components) 

B: Building our Component / Interface
Step 1: Create Makefile or use your own template
CXX   = c++
CPPFLAGS +=     -fno-rtti              \
-fno-exceptions        \
-shared  
# Change this to point at your Gecko SDK directory. 
GECKO_SDK_PATH = /home/username/cprogs/gecko-sdk
# GCC only define which allows us to not have to #include mozilla-config 
# in every .cpp file.  If your not using GCC remove this line and add 
# #include "mozilla-config.h" to each of your .cpp files. 
GECKO_CONFIG_INCLUDE = -include mozilla-config.h 
GECKO_DEFINES  = -DXPCOM_GLUE
GECKO_INCLUDES = -I $(GECKO_SDK_PATH)/include 
GECKO_LDFLAGS =  -L $(GECKO_SDK_PATH)/lib -lxpcomglue \
                 -lnspr4      \
                 -lplds4      

FILES = krpComponent.cpp krpComponentModule.cpp 
TARGET = krpComponent.so
build: 
$(CXX) -Wall -Os -o $(TARGET) $(GECKO_CONFIG_INCLUDE) $(GECKO_DEFINES) $(GECKO_INCLUDES) $(GECKO_LDFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(FILES)
chmod +x $(TARGET)
strip $(TARGET)
clean: 
rm $(TARGET)

Step 2: Run "make" command, and it "krpComponent.so" file will be created.

C: Registering the Component
Step 1: Copy krpComponent.so and KFFComponent.xpt file to "~/.mozilla/component" directory
Step 2: use command "regxpcom" to register component
$ ./regxpcom  -x  _DIR_PATH_OF_COMPONENT_
 Replace _DIR_PATH_OF_COMPONENT with the path of component (krpComponent.so)
Step 3: Restart Mozilla.

D: Testing Component
You can either use Extension or HTML page to test our new Firefox C++ Component.
HTML Code of "TestComponent.html" page is as follows



<script>
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
const cid = "@mydomain.com/XPCOMSample/krpComponent;1";
var obj = Components.classes[cid].createInstance();
var obj1 = obj.QueryInterface(Components.interfaces.KFFComponent);

               var res = obj1.Sub(10, 5);
alert('Performing 10 - 5  =  ' +  res );

} catch (err) {
alert(err);
}

</script>


Thursday, October 21, 2010

Narcissus/Zaphod JavaScript Research VM for Firefox

Narcissus is a JavaScript virtual machine written in JavaScript. Firefox extension Zaphod allows using Narcissus as the default JavaScript engine in Firefox.
Developers can write scripts specifically for the Narcissus engine (by specifying script tags with a type of "application/narcissus"), or they can replace SpiderMonkey with Narcissus as the default engine.

References:
More info about Zaphod 
Example Pages

Saturday, October 9, 2010

How to use Huawei E1550 USB Modem On Ubuntu 10.04

I am using StarHub MaxMobile SurfLite plan. A USB modem device that comes with the plan is supported on Mac and Windows OS bydefault. 
I use Ubuntu and like to work on ubuntu than windows. It was very troublesome for me to change to windows whenever I needed Internet access. I was fed up with doing back and forth in windows and ubuntu OS. And desperately wanted to use my USB stick on ubuntu. 
My previous USB stick was ZTE MF628. And I don't know how to use it on ubuntu. If anyone knows it, I will appreciate if you post how to make it work on ubuntu.
When I renewed my contract with StarHub, I got new USB stick Huawei E1550 that worked on ubuntu without any hurdles. 

Step by Step guide to use Huawei E1550 USB stick on Ubuntu:
1. Plug in Huawei E1550 USB modem to USB port. You can notice its icon is loaded on Desktop. 
2.  Type following command at command prompt:
         $ gksu gedit /etc/udev/rules.d/15-huawei-e1550.rules
3. It will open gedit. Type following lines in it and then save it and close the file.
      SUBSYSTEM=="usb",
     SYSFS{idProduct}=="1446",
     SYSFS{idVendor}=="12d1",
     RUN+="/lib/udev/modem-modeswitch --vendor 0x12d1 --product 0x1446 --type option-zerocd" 

4. Restart the computer. After restart click on "Network connection" icon in the top panel. You will see new menu item under "Mobile Broadband" category.
5. Click on that new entry. It will open a New Mobile Broadband Connections dialog. Click Forward to continue.
6.  Select you country (Singapore in my case) and click Forward. Then select service provider from the list and click forward. Then choose your Billing plan and click Forward. Then finally Click on Apply to save setting. 

It will connect you to the Internet. Enjoy, hurdle free Internet connectivity on ubuntu using USB Modem (Huawei E1550).

Wednesday, August 18, 2010

Mac OS theme on Ubuntu 10.04 (Lucid)

Installing Mac OS theme on Ubuntu 10.04 (Lucid) is easy and straightforward. 

Step 1:  Install Gstyle (Gstyle is a full Gnome Theme Manager)
             sudo add-apt-repository ppa:s-lagui/ppa
             sudo apt-get update
             sudo apt-get install gstyle
Step 2:  Once it is installed successfully. Launch Gstyle application (System -> Preferences - > Gstyle).
Step 3:  Click on Download button and then Click on Refresh button.  Select Mac4Lin theme from the list.
Step 4:  Then in each category option in the left panel of Gstyle, select Mac4Lin. I choose Mac4Lin Aqua.
Step 5A:  Now to Configure Global Menu (Top panel bar). Perform following steps:
             sudo add-apt-repository ppa:globalmenu-team
             sudo apt-get update && sudo apt-get install gnome-globalmenu
             killall gnome-panel
Step 5B:  Once done, remove all stuffs from top left panel (Right click on the panel and select “Remove from Panel”).  Right click on the top panel and select Add to Panel. Select Main Menu, follow by the Global Menu Panel Applet. Close the window. Now move the two items (right click and select Move) to the left hand corner and make sure they are side by side.

Step 6A: Now to configure Dock (Bottom panel bar). Perform following Steps:
            sudo apt-get install cairo-dock
            There are lot of dock application, but I found this one is easy to use. 
Step 6B: Before you launch the Cairo dock application, remove the bottom panel (right click at the bottom panel and select Delete This Panel).  Cairo dock needs a compositing manager to work, so make sure that your system support Compiz before launching the app. Launch Cairo dock (Menu -> Accessories -> Cairo Dock). Make sure to set it to launch everytime you startup your computer.

             Only if your system does not support Compiz: You can activate the in-built metacity compositing manager with the command:
            gconftool-2 --type boolean --set /apps/metacity/general/compositing_manager TRUE 



To change the logo in the panel bar with apple logo:
1. Download apple logo from google.
2.  Then go to /home/urprofilename/.icons/Mac4Lin_Icons_v1.0/scalable/places folder.  Check the resolution of distributor logo.png file. It may be 78 * 96. Now rescale the image you downloaded into 78 *96 or 96*96 size.
3. Then replace distributor-logo.pnggnome-main-menu.pngmain-menu.png, and start-here.png with the apple logo file.
4. Open the terminal window and type  killall gnome-panel to restart the gnome-panel. Now you should see your new icon.