Sunday, September 30, 2007

Getting browser's progress status

Ever wonder how to correctly get the page's progress of the browser (loading, transferring, waiting, etc)? Well here it is:

There are several states that can be detected using this interface
  • onStateChange
  • onLocationChange
  • onProgressChange
  • onStatusChange
  • onSecurityChange
  • onLinkIconAvailable
even though their names can seem self-explanatory, you better check the full documentation.

1) create an object that will withhold the Progress Listener Interface

var oProgressListener = new Object(); //on top of all codes, or with global scope


2) get the Progress Listener interface and assign preliminary values.

wpl = Components.interfaces.nsIWebProgressListener;

//I'm still not very sure what this function does :D
oProgressListener.QueryInterface = function(aIID) {
if (aIID.equals(oProgressListener.wpl) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
aIID.equals(Components.interfaces.nsISupports)) return this;
throw Components.results.NS_NOINTERFACE;

}


3) assign appropriate functions to the state you wants to:

//detect URL changes
oProgressListener.onLocationChange = function(aProgress, aRequest, aURI) {

alert('my URL was changed');
return 0;

}

//detect the starting of loading a new page / document
oProgressListener.onStateChange = function(aProgress, aRequest, aFlag, aStatus) {
if (aFlag & oProgressListener.wpl.STATE_IS_DOCUMENT){
alert('New page is being loaded');
}
}

//detect when a page is fully loaded
if (aFlag & oProgressListener.wpl.STATE_STOP) {
if ( aFlag & oProgressListener.wpl.STATE_IS_DOCUMENT ) {
alert('New page has finished loading');
}
}


4) Associate the progress listener for a "browser" to a listener object

browser.addProgressListener( oProgressListener,
Components.interfaces.nsIWebProgress.NOTIFY_STATE_WINDOW);

How to put log messages in Firefox's Error Console

Found out about how to add comments/logs to Firefox built-in Error Console. Really helps in debugging process.

1) get the Console Service component

var ConsSrv = Components.classes['@mozilla.org/consoleservice;1'].getService(Components.interfaces.nsIConsoleService);


2) write your logs!

ConsSrv.logStringMessage('here is my logs.. Hello!!!!');

Friday, September 21, 2007

Change multiple textbox value simultenously

Ever tried duplicating values from one main textbox to another (in XUL)? or to many others? Right after every keypresses from the user? Well, the JavaScript way is to call the onchange / onkeypress / onkeydown / onkeyup event for the main textbox, and when the event occurs, duplicate it's content to the target textboxes.

Well, this is not the same in case of XUL textboxes. Using onchange / onkeypress / onkeydown / onkeyup will always get the second latest char, as illustrated in this example:

Main textbox
-------------------------
| 12345 |
-------------------------

Duplicating textbox
-------------------------
| 1234 |
-------------------------

So the correct way is to use the oninput event handler, then you'll get the latest update from the main textbox.

Sample code:

<textbox id="main" oninput="duplicateValue()" />
<textbox id="duplicate" />

function duplicateValue()
{
var main = document.getElementById('main');
var duplicate = document.getElementById('duplicate');

duplicate.value = main.value;

}

Running multiple instances of firefox

Here is a very helpful article that elaborates (with pictures) on how to run multiple instances of Firefox(es) at the same time. This may be a requirement if you are trying to develop a Firefox extension and need to test it on 2 or more Firefox windows at the same time.

ref:
http://lifehacker.com/software/firefox/geek-to-live--manage-multiple-firefox-profiles-231646.php

Concatenating Object with String using eval()

eval() is a neat function that evaluates a string and executes it as if it was script
code.

Consider this code:

function displayItem(itemNo){
var item1 = "111";
var item2 = "222";
var item3 = "333";

eval("alert(item"+itemNo+")"); // the 'item' variable is concatenated with the parameter passed
}

and when call with this statement:

displayItem(1);

it will alert:

111

or in other case:

displayItem(3);

it will alert:

333

Getting X node value

Consider the following stanza:

<message>
<body>bar</body>
<x xmlns="myns">
<content>foo</content>
</x>
</message>

which is then passed to a function called getFoo(message), that will extract the value of <content>. I was having trouble getting that value using message.stanza.x.content, so I found an alternative way, by parsing the xml stanza through xml string.


What we need to do:


//declare a namespace var to make things easier...to read
ns = "myns";

//get the <x> node only
var x = message.stanza.ns::x;

//extracting the position value
var foovalue = loadXMLString(x);

//function to parse through XML String .. from w3schools.com
function loadXMLString(XMLtext)
{
//alert(XMLtext);
var parser=new DOMParser();
var doc=parser.parseFromString(XMLtext,"text/xml");

// documentElement always represents the root node
var x=doc.documentElement;

return x.childNodes[1].childNodes[0].nodeValue; //the <content> value..... Why so many childNodes? see below.


}

Why so many childNodes?

Even though the xml string we extracted (<x> node only) will be something like this:

<x xmlns="myns">
<content>foo</content>
</x>

In plain eyes, it looks like <x> have only 1 child node (content), but instead it has 3 nodes actually. The real stanza would be something like this:

<x xmlns="myns">
--- invisible textnode ---
<content>foo</content>
--- invisible textnode ---
</x>

you can prove this by displaying the nodeType for all the children:

x.childNodes[0].nodeType; // text
x.childNodes[1].nodeType; // element (<content>)
x.childNodes[2].nodeType; // text

ref:
http://www.w3schools.com/dom/dom_parser.asp
http://truetalkdev.blogspot.com/2007/06/sps-chat-events-stanzas.html

Tuesday, September 4, 2007

Get the previous sibling of a node

Consider this DOM tree:

<book>
<title>Magic Mayhem</title>
<author>Merlin</author>
<publisher>King Arthur Inc.</publisher>
</book>

and you would like to know who is the TITLE of the book, by passing the AUTHOR node to a function, i.e: getSibling(node); . You may use a handy function called element.previousSibling but there is matters to consider.

Must use a loop
The correct way (in IE & Mozilla) to get the previous sibling of a certain node is by using a loop that iterates through the child nodes:

function get_previoussibling(n)
{
//n = <author>
var x=n.previousSibling;
while (x.nodeType!=1)
{
x=x.previousSibling;
}
return x;
}

The nodeType = 1 will only be TRUE if the element is an element node (not a textnode or any other nodes). So the loop will keep on iterating until it find the correct element node (<title>) and returns that node. However, this may requires hevery processing when we have thousands of child nodes. Hence, if you are sure and know where is the place [index] of the child node you want, you may try this instead:

//n = <author>
var prevSibling = document.getElementById(n).parentNode.childNodes[0]; //returns <title> --- no loops required.

ref:
http://www.w3schools.com/dom/prop_element_previoussibling.asp

Detecting mouse over event

I was trying to register an event handler with a div's onmouseover event, there's something interesting that I found.

div.onmouseover = alert('yatta!');
- this event will be triggered every time the div is appended to another element (weird?), because u cant trigger a function with params with this statement.

div.setAttribute("onmouseover", "alert('yatta!');");
- this event will be triggered only when the mouse is over the div

Sunday, August 26, 2007

Load image from chrome

Previously, we load images from my googlepage. Now there's a faster way, that is, loading it from Chrome. What we need to do is just include this in chrome.manifest:

skin exte_name classic/1.0 chrome/skin/classic/

and load all images into the \chrome\skin\classic folder.

after that, we can simply load image using:

img.src = "chrome://exte_name/skin/image_name.jpg";

drawWindow can't grab flash videos?

drawWindow() is a handy function included with Mozilla's <canvas> tag. With it you can capture or grab the snapshot of what's in the content area of your browser.

Since it only takes snapshots, sometimes, it can grab flash video, but only after the video has finished loading. (proved by tabpreview) and will only get 1 frame of the video at 1 time, so will look awkward.

Setting online/offline to buddies

- able to get each incoming presence, using channel
- can't re-populate buddy list
- when disable channel and get presence only using xmpp.cache, it detects buddies on re-login only

-random development notes that relates to presence:
http://dev.hyperstruct.net/xmpp4moz/wiki/DocDevelopmentNotes

Monday, August 13, 2007

Checking whether windows has focus or not

- first... set focus on the window first with window.focus
- then.. add event listener to the window onblur event :
window.onblur = afunction()
- you're set!

Issues:
onBlur =
called when lost focus
onFocus =
called when got focus

There are 2 big areas that may clashes with focus, namely <window> and document <body>. Normally we want to detect when the user is not 'looking' at the browser window, maybe while doing work in MS Word. But if the last focus was given to the <body>, not <window>, even when you are looking at the browser window (but with a body element, such as a textbox is currently in focus), the onBlur event for window will be triggered.

Getting image width and height

- attach a function that gets the width and height of an image to the onload event for each images.
- once the images is finished loading, the function will be called, and we can get the values.
- 3 ways of attaching function to event:
myImage.setAttribute("onload", "getWH();");
myImage.onload = getWH;
myImage.addEventListener("load", getWH, true);

- we can pass parameters for the function only using the 1st method.
- loading animated gif requires longer time than still gif.

Image loaded directly inside browser, had no &lt;head&gt; tag

- try loading an image directly using a URL ending with image format extensions (.jpg, .png, .bmp)
- using DOM Inspector, try to view the hierarchy, there's no <head> tag !

Thursday, August 2, 2007

XEP-0104: HTTP Scheme for URL Data

XEP-0104: HTTP Scheme for URL Data

An article that relates to sending URLs inside xmpp stanza.

Animation-like behaviour in Javascript

I came across a website called Super Maryo World :D As you can figure out by its name, its another remake of the infamous Super Mario Bros. What catches my attention is that it's a game, created entirely in Javascript and can be played in the browser!

To satisfy my curiosity, I tried to somewhat try to code the character movements (move left, right and jump). It does requires some pretty tricky algo.

I was trying to move a div around. First I start of by some basic algo, which is:

OnPress Left
    Move Div Left by 10px

OnPress Right
    Move Div Right by 10px

OnPress Shift
    Move Div Up by 10px

Issues:
  • There's a 0.5 second pause after first movement of 10px, when pressing LEFT or RIGHT before the div continuously moving
  • You can only jump and move... by pressing UP, then DIRECTIONs, not by pressing DIRECTIONs first, then UP.
I'm not quite sure what is really the problem, but I do know that pressing keys may cause events to 'bubble' up (events are collected before it triggers). So it doesn't feels 'real'

Hence, inspired by ActionScript's onEnterFrame() method, a more realistic approach would be:

Use timer to create movements and jump 
OnPress Left
    startTimer To call MoveDiv(left)
       When timer expires, calls MoveDiv(left) recursively while pressing LEFT

OnPress Right
    startTimer To call MoveDiv(right)
       When timer expires, calls MoveDiv(right) recursively while pressing RIGHT

OnPress Shift
     startTimer To call MoveDiv(up)
       When timer expires, calls MoveDiv(up) recursively while pressing UP

and also you must put RETURN FALSE onkeypress ENTER key, to avoid unwanted auto-move bugs :D

Tuesday, July 31, 2007

Get the viewing plane .. correctly

As I've mentioned in previous post, we can use window.innerHeight to get the current viewing plane for the browser. However, since there are 2 documents inside a browser, putting them in either of them gave different values.

- reason:
- window.innerHeight called in Chrome level, return the browser's height
- window.innerHeight called in document level, return the viewpoint's height

- fixed using document.defaultView

This is a diagram taken from MDC:


#document
window main-window
...
browser
#document
window myExtensionWindow)

As you can see, since they are on different levels, calling window.innerHeight will gave different values. The higher <window> is the window for the whole browser, whereas the lower <window> is the window of the viewing plane.

get image size after image is fully loaded

If we need to get the size (width and height) of an image, in order to manipulate it, we first need to make sure that the image is fully loaded inside the web document. But at most time, we may not need to render the image, we just need the size. so here is a neat way to do this:

- using Image() object to load an image internally, without displaying the image in the doc, and then get the size.
function getWidthAndHeight() {
alert("'" + this.name + "' is " + this.width + " by " + this.height + " pixels in size.");
return true;
}
function loadFailure() {
alert("'" + this.name + "' failed to load.");
return true;
}
var myImage = new Image();
myImage.name = "someimg.jpg";
myImage.onload = getWidthAndHeight;
myImage.onerror = loadFailure;
myImage.src = "someimg.jpg";

With this code, the image is 'silently' being loaded into the current document. The image is attached with an 'onload' event listener, that calls a function named getWidthAndHeight() Note that onload event for images are only triggered after the image is fully downloaded to the browsers cache. So then, they will be no problem for us to get the correct size.

Thanks to phpnovice for his solution taken from webdeveloper.com

Detect when user resizes browser

There is a couple of ways to listens to the event triggered when a user resizes Firefox:

body.onresize
- when put an alert function for testing purpose, it alerts only once
- must be put inside loaded doc body, otherwise can't utilize 'body' var
- not valid HTML 4.0 spec

window.onresize
- alert twice
- can be put on chrome level or in document level
- valid HTML 4.0 spec

after some more tests:
- self.screen.availHeight = the whole screen height - taskbar height // not reliable
- window.innerHeight
- seems to be working accurately

Monday, July 23, 2007

XPCNativeWrapper : The DOM and Javascript Access Protector

During my search for solution for the previously mentioned problem, I stumbled upon a XPCNativeWrapper, a wrapper that wrap around DOMs and javascript codes, to protect if from XSS (Cross side server script) or unprivileged codes that may change the behavior of one's website or in Mozilla's case, the browser itself.

The praised functionality of a browser to allow DOM manipulation has make web-based and browser-based development more exciting. Yet, malicious codes will always try to do unethical thing, such as steal usernames and passwords as reported by Greasemonkey community.
Hence, a protector such as this is adequate.

Thanks to developers of Mozilla-based browsers, XPCNW has been enabled by default for Firefox version 1.5 and above.

Master document handling issues on different OSes

A new phenomenon has been discovered as we were testing TT on different OSes, just to try and see whether TT is stable. Here is the summary:

Test run on:
WinXP Home..... OK
Ubuntu 7.04..... OK
WinXP Pro........ NOT WORKING
Mac Os X........ NOT WORKING

The error returned was it can't find a toolbar with the given id, which I placed clearly on top of the status bar. I seems strange that the same codes won't work on different OSes.

After further research and scouring into one of my firefox extension (DownBar), which I'm trying to replicate, I realized that we need to specify the parent node of a an XUL element we are trying to access, as explicitly as possible. Consider my previous codes:

<overlay>
....
<toolbox align="end" insertbefore="status-bar" hidden="true">
<toolbar id="tlbid">
<!--content will be added dynamically-->
</toolbar>
</toolbox>
....
</overlay>

and I was trying to get the <toolbar> element by using document.getElementById('tlbid'). Apparently this works only on WinXP Home and Ubuntu. To overcome this bug, we need to specify the parent of <toolbar> which is actually <window>. so the correct codes will be:

<overlay>
....
<window id="main-window">
<toolbox align="end" insertbefore="status-bar" hidden="true">
<toolbar id="tlbid">
<!--content will be added dynamically-->
</toolbar>
</toolbox>
</window>
....
</overlay>

The piece of code above explicitly told the browser that the toolbar with id 'tlbid' is a child node for the main window for firefox browser. I guess this helps the DOM manager to find the element required, effectively.

Thursday, July 19, 2007

Call function after user is connected...success!

As mentioned in this xmpp4moz thread, I was having problem on my PC, calling an alert() function after a user is connected. But the problem never occurred when tried on a Mac. Fortunately thanks to Bard, who releases a new version of xmpp4moz and SamePlace a couple of days earlier, this problems has been fixed. So everything is working in order now.

Newline / Line break inside layered divs

Imagine this codes:

<div id="layer1" style="position:absolute; width:....."> This is some text <BR> and this is a new line </div>
you will be given the output of:
This is some text and this is a new line

simple right?

But unfortunately, <BR> can't be use to append a line break or a new line in a sentence, dynamically, using innerHTML or textContent:

<script> document.getElementById('layer1').innerHTML = "This is some text <BR> and this is a new line" </script>

<div id="layer1" style="position:absolute; width:....."> no text yet </div>

It will give you:
This is some text and this is a new line

So how to overcome this?

Just use "\n" instead :D

<script> document.getElementById('layer1').innerHTML = "This is some text \n and this is a new line" </script>


Thursday, July 12, 2007

Are You Indie?

I wasn't able to dwelve further into TT develepment since last week till today, because I was assigned to put up a website for the IndieCade festival.

IndieCade: The International Festival of Independent Games

IndieCade is the premiere annual festival for the future of independent games. The festival, planned for three undisclosed days in 2008, will feature continual screenings and hands-on play opportunities, game design jams, a play-testing atelier, large-scale social games, works-in-progress, workshops by creative industry legends, a gamemaking tools emporium, and a special mini-festival honoring the indie spirit in legacy games. Culminating in a gala award game show, IndieCade will be an unprecedented assembly of industry insiders, bellwether gamemakers, and players looking for the newest and most groundbreaking independent games.

- areyouindie.com

They have a booth in E3, happening in LA right now, showcasing some of the participating game videos. We will have another promotional event in London after this. IndieCade will be held on an undisclosed date, in spring 2008.

Tuesday, July 3, 2007

Thursday, June 28, 2007

DEV: Solution accessing element

I was having a problem accessing the <toolbox>'s id due to the fact that I'm using overlay. Here is my previous XML structure:
overlay
---script
---toolbox id="tbxid"

The important thing about <overlay> is, all element inside the <overlay> will be put 'over' the existing elements within the Firefox browser. So it checks for each element's id, in order to lay it over the correct elements. If it doesn't find any id from the <overlay> element that match the element inside Firefox, it will drop that element and all its children. In our case, id = "tbxid" is not define anywhere inside Firefox, so it got dropped.

The solution to this is to give id to the child of the <toolbox>, and not the <toolbox> itself. So our XML structure will look like this:
overlay
---script
---toolbox
------toolbar id="tlbid"


We then get the parent node of <toolbar> by:
var the_parent = document.getElementById('tlbid').parentNode;

And now we can do DOM manipulation using the parent:
alert(the_parent.nodeName); // => alert 'toolbox'


Monday, June 25, 2007

Encapsulating XUL elements in and gave different result

I found an XUL code that enables us to put button and textbox on top of the statusbar. It uses that contains and . The sample codes are encapsulated in much like any other XUL files. Since TT codes are using different approaches, that is we encapsulate elements inside , and use it to lay over the default window, I changed the tag to to see what happen. It does gave a different output as shown in these two screenies:

using <window>- the chatbox is on top of statusbar












using <overlay> - the Chatbox is on the right side

How to add XUL elements on top of status bar?

I've been searching around for ways to add XUL elements on top of the statusbar. On previous findings, only <label> can be put there. But today, I found another way to put XUL elements on top of the status bar. Here are some sample codes:
<toolbox align="end" insertbefore="status-bar">
<toolbar id="nav-toolbar">
<textbox id="urlfield"/>
<toolbarbutton label="Send"/>
</toolbar>
</toolbox>

What is 'preferences'?

I found out 'preference' when I was trying to understand how XMPP.enableContentDocument() works. Somehow, SPS uses preferences to get the XUL content panel element to be passed to the function mentioned, as 1 of its parameter.

So, preferences may be, but not restricted to:
- a way to store values universally (cross-pages?)
- Storing shared data in preferences

DEV: Enable &quot;xmpp session" on TT

I've created a demo that appends dynamic XHTML element, onto the current loaded page, following the SPS hierarchy. I've tested it on google.com, so here's how the hierarchy looks like:
#document
---HTML
---HEAD
---BODY
---DIV id=xmpp-incoming
---DIV id=xmpp-outgoing
---script

Upon testing, I connect to another user through SPS. I send a message using the dinamically added chatbox and append the message to xmpp-outgoing. The message is appended successfully, but there is no message being sent to the other user. Then I activate the "xmpp session" by:
- clicking the user's name in my roster.
- Connect > Current Page
After that, I tried sending message again using the chatbox, and the message was sent successfully to the other user. The other user viewed the message in their SPS sidebar.


Theory:
by doing Connect > Current Page (C>CP), I initiated an xmpp session between me and the other user. According to SPS codes, C>CP invokes a function called XMPP.enableContentDocument(...). This function takes the following argument:
panel - a XUL content panel element (browser or iframe)
account - the account you're connecting from
address - the address of the contact you'll interact with inside the panel
type - 'chat' or 'groupchat' - if a message leaves the page without
type, it will get the type specified by this argument
createSocket - boolean - create the two div's in the page if they're
not already there
Thanks to Bard for his explanation of the parameters in this thread.

I will try to use this function in my codes, to enable xmpp session by itself.

Effort:
- add XMPP.enableContentDocument(...) to current codes.
- statically set XMPP.enableContentDocument(...) params to:
- panel = (still unknown, due to Firefox security restriction)
- account = user1@gmail.com
- address = user2@gmail.com
- type = 'chat'
- createSocket = false
- got these error message:
XMPP not define;
Solution: added script src "chrome://xmpp4moz/content/xmpp.js"
- then got this error:
Error: uncaught exception: Permission denied to get property UnnamedClass.classes
- and message is still not send.
- theory: maybe the value for panel is not correct. Tried all of these:
- doc
- root
- bodyRoot
- windowRoot
- browser



Thursday, June 21, 2007

Share Cursor codeflow

I've got a chance to visit Share Cursor codes again today. I was having problem accessing functions from a dynamically added script. Some people says it couldn't be done directly, so I scoured around and found a workaround for it, as shown in previous post. Accessing anything isn't a problem anymore.

Here's the flow:
- user click Connect > Virtual workspace > Share Cursor ... the extension added <script src="laser.js">
- laser.js initialized everything from drawing the cursor, to creating 2 xmpp divs and all required elements.
- therefore, there is no problem to access anything as everything is generated from the same document and .js file.

Accessing chrome level function from browser's document

For security reasons, Firefox doesn't allow HTML element's inside a document's body to access functions / vars from chrome path files directly. Therefore, we need to append <script> tag at the appropriate places.
- inside <body> ==> didn't work
- inside <head> ==> didn't work
- inside <html> and same level as <head> and <body> ==> SUCCESS!
root.childNodes[0].appendChild(oScript);

Reminder:

windowRoot = document.documentElement;
bodyRoot = content.document.body;
root = content.document;
doc = window.document;

-------------------------------------------------
When in CHROME level
-------------------------------------------------

alert(windowRoot.nodeName); //window
alert(bodyRoot.nodeName); //body
alert(root.nodeName); //#document
alert(doc.nodeName); //#document

alert(root.childNodes[0].nodeName); //HTML
alert(doc.childNodes[0].nodeName); //window

-------------------------------------------------
When in document level
-------------------------------------------------
alert(windowRoot.nodeName); //HTML
alert(bodyRoot.nodeName); //body
alert(root.nodeName); //#document
alert(doc.nodeName); //#document

alert(root.childNodes[0].nodeName); //HTML
alert(doc.childNodes[0].nodeName); //HTML

Best Javascript Practises

During my research, I came across a website that teaches a few best practices for Javascript programmers.

Here are some of them:

- only javascript 1.7 have block scope. Hence its a very good idea to put this code in the script definition:
<script type="text/javascript" version="1.7">
- define variables with 'var', to differentiate variable's scope
global var:
var x; //global
x =0;
function init()
{
var x = 5;
alert(x); // shows 5
}
alert(x); // shows 0



Wednesday, June 20, 2007

Dev: using setTimeout() to delay execution until .js file is successfully loaded

This is done only using html and js file, no XUL.

#1 Launch addButton() and addScript() at the same execution point:
- <a href="#" onclick="addButton();addScript('chrome://truetalk/content/data.js');">START</a>
- expected alert message is displayed.
- success, except in flock : Error: remoteValue is not defined

#2 Execute addScript() first, then addButton()
- addScript() -> addButton() -> click button -> alert messages
- <a href="#" onclick="addScript('chrome://truetalk/content/data.js');">START</a>
- expected alert message is displayed.
- success, except in flock: Error: remoteValue is not defined

#3 Append #2 by adding a new function [sendMessage()] in data.js, try to call it on button click

- oButton.setAttribute("onclick", "sendMessage();");
- success, except in flock: Error: remoteValue is not defined.


Sunday, June 17, 2007

Back in selangor

I'm back in Selangor for this week onwards. So I'll be in the office. Will update Dr. Yunuz about this.

Thursday, June 14, 2007

How to add HTML dom elements dynamically inside a loaded page?

- solution:
- get the content of the loaded document in a tabbedbrowser
- alert(content.document); & alert(gBrowser.selectedBrowser.contentDocument); =>
[ Object XPCNativeWrapper [ object HTMLDocument ] ]
- rootBody = content.document.body; => <body> tag!
- then we can simply add a <div> tag by:
var tmpDiv = document.createElement('div');
rootBody.appendChild(tmpDiv);

- ref:
http://forums.mozillazine.org/viewtopic.php?t=522447&sid=47babc2b5e758ba21458bb73d733
http://developer.mozilla.org/en/docs/Extension_Code_Snippets:Tabbed_Browser#Getting_document_of_currently_selected_tab
http://developer.mozilla.org/en/docs/Working_with_windows_in_chrome_code#Content_windows

Wednesday, June 13, 2007

DEV: client-side demo app (No-GUI)

- connect ... DONE.
- Send Message
- add 3 more popup menu item:
- to login...SUCCESS
- to send message...SUCCESS
- to logout...SUCCESS
- Receive message:
- catch using channel.on() function...SUCCESS
- Display messages
- display in alert box, since no GUI
- ref @ http://dev.hyperstruct.net/xmpp4moz/wiki/DocLocalApplicationDevelopment
- unfortunately, since I don't have any GUI, my username and password must be hardcoded to connect and send message. Therefore, I can't enclose a demo for this post.

How-to run:












0) Install extension! !) Restart/Launch Firefox
2) Right-click anywhere on the page
3) Goto TrueTalk > Login / Send Message / Logout
3.1) Login - login to gmail with hardcoded username and password.
3.2) Send Message - send a fixed message to a fixed receiver.
3.3) Logout - Logout from gmail.
4) Received messages (not fixed) will be displayed in alert box.

Dev: [div] tags app (demo)

- I will call the demo app with this new name.
- It's because I use 2 divs tag to catch incoming and outgoing message.
- The user who wants to use this, must also have xmpp4moz and SPS installed.
- Error: Blank message appeared after a REAL message in SPS sidebar.
- ex:
sender1 : Hi there, Im using Firefox
sender1 :
sender2 : Hi, Im using Flock
sender2 :
- Cause:
- In Flock browser, it might be a bug, because their codebase is on top of Firefox 1.5 framework.
- In Firefox, It post 2 messages because of this piece of code:
if(event.keyCode == event.DOM_VK_RETURN || event.keyCode == event.DOM_VK_ENTER)
sendMessage();
- Solution:
- change it to:
if(event.keyCode == event.DOM_VK_ENTER)
sendMessage();
- here is the downloadable demo

Tuesday, June 12, 2007

Error console to help debugging process

- Firefox has a great built-in tool to help extension developers debug their codes, called the Error Console.
- I happened to stumble upon a problem with xmpp4moz, and Bard adviced me on enabling the Error Console.
- For more details, you can check out http://dev.hyperstruct.net/xmpp4moz/wiki/Report. Look up on how to enable chrome errors display in the console.

Warning: plain-text password in about config, filter xmpp (FireFox only)

This only happens if you have xmpp4moz, and save your jabber a/c password in it's Account Manager.
- Launch Firefox
- type 'about config' (without quotes) in address bar
- type 'xmpp' (without quotes) in filter bar
- look for 'xmpp.account.1180919090843.password' (the numbers may be different). Your password is in the next column.
- just a friendly reminder from your friendly neighbourhood... programmer :D

Setting up for FFox extension development

- create a project folder , somewhere, ex: C:\myext\ . This will be our root.
- inside it, we create another folder call chrome
- inside chrome, we create another folder called content, this is where we keep our .xul and .js files
- Now go back to root, create 2 text files, install.rdf and chrome.manifest
- for stuff to put inside install.rdf and chrome.manifest , and more details, you can check out FF extension tutorial @ MDC

- for development purposes, we don't need to create a .xpi package.
- to test whether our extension can be used or not, do this:
- go into your Firefox Profile's extension folder ex: C:\Documents and Settings\USER\Application Data\Mozilla\Firefox\Profiles\USER_PROFILE.default\extensions\
- create a text file, with your app id (the one you put in tag inside install.rdf) as its name. Just put the id, no .TXT or any other extension required.
- open the text file, put the path of your extension root folder, ex: C:\myext\ , don't forget the following '\'
- start Firefox and your app should run :D

How to use xmpp4moz server-side applications

At least xmpp4moz and SamePlace need to be installed and working to use server-side applications.

== Generic way ==

- Connect your Jabber account.
- Open a conversation with one of your contacts in !SamePlace.
- In the browser, navigate to a server-side application (e.g. http://apps.sameplace.cc/notes/notes.xhtml).
- Click on the `connect` [[Image(connect.png)]] icon in the upper right of the conversation panel.
- Start using the application.

The same steps need to be followed by your contact.

== Quicker way ==

- In the browser, navigate to a server-side application (e.g. http://apps.sameplace.cc/notes/notes.xhtml).
- Bookmark it inside the `SamePlace` folder.
- In the contact list, right-click on your contact, then select '''Communicate in browser using... -> '''


taken from http://dev.hyperstruct.net/xmpp4moz/wiki/DocUsingRemoteApplications?format=txt

SPS Chat events' stanzas

if textbox is empty, then on 1st keypress:
<message to="foo@gmail.com" type="chat">
<x xmlns="jabber:x:event">
<composing />
</x>
<composing xmlns="http://jabber.org/protocol/chatstates" />
</message>

- if on first keypress, we are trying to erase/delete a letter:
<message to="foo@gmail.com" type="chat">
<x xmlns="jabber:x:event" />
<active xmlns="http://jabber.org/protocol/chatstates" />
</message>

- if receiving a message:
<message to="foo@gmail.com" type="chat">
<x xmlns="jabber:x:event">
<composing />
</x>
<active xmlns="http://jabber.org/protocol/chatstates" />
<body>foo is not bar
<html xmlns="http://jabber.org/protocol/xhtml-im" />
<body xmlns="http://www.w3.org/1999/xhtml">foo is not bar
</html>
</message>


Here are some ways to parse the values (according to E4X specification):
============================================================
stanza = <message to="foo@gmail.com" type="chat">
<x xmlns="jabber:x:event">
<composing />
</x>
<active xmlns="http://jabber.org/protocol/chatstates" />
<body>foo is not bar</body>
<html xmlns="http://jabber.org/protocol/xhtml-im" />
<body xmlns="http://www.w3.org/1999/xhtml">foo is not bar</body>
</html>
</message>

stanza.body = "foo is not bar"
stanza.@to = "foo@gmail.com"

but, to get the namespace (xmlns) values, its a little bit different:

var ns = 'jabber:x:event'; //declare a var to hold the required namespace
if(stanza.ns::x != undefined) {
// ok, there is an <x xmlns="jabber:x:event" />, go ahead...
} else {
// no
}

alert(stanza.ns::x.namespace()); //display the namespace in an alert box

so for getting the xmlns value, the general term would be:
stanza.[NAMESPACE_VAR]::[TAG_NAME].namespace();

Thanks to Bard for the help on these codes. Original source is can be found in the forum. If I found a reliable E4X documentation, I'll post it here.

Monday, June 11, 2007

Creating my x4m client-side app

- get codes from here
- message will be send only when I'm connected to a server through SPS.
- mesage is displayed on the sidebar only, can't be displayed in the 'conversation' box on the right.
- there are no xmpp4moz divs, because it catches incoming message by using channel.on() function.
- app is connected to the xmpp4moz library through this code =>
<script type="application/x-javascript" src="chrome://xmpp4moz/content/xmpp.js"/>
- posted this problem in forum

Types of of apps related to Firefox
- Server-side :
- usually in .xhtml format, so it can be understood by most current browsers
- resides on the server
- Client-side :
- usually in .xul format
- understood by Firefox only
- installed as extension within Firefox

Friday, June 8, 2007

XUL-related links

Just a collection of links I've found today:

- XUL Success Stories
- Firefox extension developers guides
- XUL test cases with codes and examples
- Working with windows in chrome code
- Spket IDE: Nice XUL IDE, interface like Eclipse, can also be installed as Eclipse plug-in. But still no viewer like dreamweaver
- Content Management System (CMS) - created using XUL/AJAX
- XML DOM - node object properties reference

How SPS's sidebar can display same message as http://apps.sameplace.cc/chat/chat.xhtml?

Try to log in with a friend, then activate SPS's chat app through Connect > Misc > Chat (new page). You can chat on the sidebar and it will display the same message also in the right panel, and vice-versa. How does this work?
- It's because of the SCHEMA.
- once you follow SPS's schema, its no problem :D

- SPS's xmpp schemas:
- sender sends message, and get this:
--------------------------------------------------------------------------------
<message to="me@gmail.com/Browser" type="chat" id="1024">
<x xmlns="jabber:x:event">
<composing/>
</x>
<active xmlns="http://jabber.org/protocol/chatstates"/>
<body>mesend this in SPS </body>
<html xmlns="http://jabber.org/protocol/xhtml-im">
<body xmlns="http://www.w3.org/1999/xhtml">mesend this in SPS</body>
</html>
</message>
--------------------------------------------------------------------------------

- receiver receives message, and get this:
--------------------------------------------------------------------------------
<message to="me@gmail.com/Browser" type="chat" id="1024" from="u@gmail.com/SamePlace">
<x xmlns="jabber:x:event">
<composing/>
</x>
<active xmlns="http://jabber.org/protocol/chatstates"/>
<body>u send this in SPS </body>
<html xmlns="http://jabber.org/protocol/xhtml-im">
<body xmlns="http://www.w3.org/1999/xhtml">u send this in SPS</body>
</html>
<nos:x xmlns:nos="google:nosave" value="disabled"/>
<arc:record xmlns:arc="http://jabber.org/protocol/archive" otr="false"/>
</message>
--------------------------------------------------------------------------------

- Schema manipulating:
--------------------------------------------------------------------------------
stanza = <message to="me@gmail.com/Browser" type="chat" id="1024" from="u@gmail.com/SamePlace">
<x xmlns="jabber:x:event">
<composing/>
</x>
<active xmlns="http://jabber.org/protocol/chatstates"/>
<body>u send this in SPS </body>
<html xmlns="http://jabber.org/protocol/xhtml-im">
<body xmlns="http://www.w3.org/1999/xhtml">u send this in SPS</body>
</html>
<nos:x xmlns:nos="google:nosave" value="disabled"/>
<arc:record xmlns:arc="http://jabber.org/protocol/archive" otr="false"/>
</message>

stanza.@to = me@gmail.com/Browser
stanza.@from = u@gmail.com/SamePlace
stanza.body = u send this in SPS

Some trials/errors when trying to get xmlns value:
errors (displayed on alert() boxes);
======================================================================
stanza.x.namespace() = cannot call namespace method on an XML list with 0 elements (in Firebug)
stanza.x.namespace = blank (in Alert())
stanza.composing.namespace() = cannot call namespace method on an XML list with 0 elements (in Firebug)
stanza.composing.namespace = blank (in Alert())
stanza.x[0].namespace() = stanza.x[0] has no properties (in Firebug)
stanza.x[0].namespace = stanza.x[0] has no properties (in Firebug)
ToString(stanza.x) = ToString is not a function (in Firebug)
toString(stanza.x) = [object Window] (in Alert())
toString(stanza.x.namespace()) = cannot call namespace method on an XML list with 0 elements (in Firebug)
toString(stanza.x.namespace) = [object Window] (in Alert())
stanza.namespace('x') = "undefined" (in Alert())
stanza.namespace("x") = "undefined" (in Alert())
stanza.namespace("composing") = "undefined" (in Alert())
stanza.namespace() = blank (in Alert())

The syntax are based on E4X Spresification. Documentation are vague for now, but these are the 2 references that I think the most adequate.
http://www.ecma-international.org/publications/standards/Ecma-357.htm
http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/js/html/wwhelp.htm?href=13_Working_with_XML_169_01.html
--------------------------------------------------------------------------------
Stick to this schema. Owh and don't forget, you'll need 2 divs/container at all time. 1 with id="xmpp-incoming" and the other with id="xmpp-outgoing". Both are responsible to catch xmpp packet generated by xmpp4moz.

Here's a screeny to sum it up:












Demo app.

- solution: change codes to suit SPS's schema.
- incoming : DONE.
- outgoing : DONE.

- ERROR: SPS send an event on first keypress on SPS left panel. I can't seem to differentiate it from other messages.










Can't seem to differentiate this message with other REAL message, as result, blank messages may appear on chatroom. Posted this on the forum

Thursday, June 7, 2007

Change of workplace for 11-06-2007 till 15-06-2007

I'll be heading back to JB to prepare my things, before the semester starts. I need to change my workplace, but it will not interfere with my work schedule. Here is the flow:

- Going to JB on Sunday
- Monday till Friday working
- Saturday get back to Cyberjaya

I'll inform Dr. Yunus about this matter.

MPL/LGPL/GPL tri-license

- These licences refers to 'modification' done on the licensed software's (SPS / x4m) codes.
- How 'viral' is the MPL? If I use MPLed code in my proprietary application, will I have to give all the source code away?

The MPL has a limited amount of 'copyleft' - more copyleft than the BSD family of licenses, which have no copyleft at all, but less than the LGPL or the GPL. It is based around the definition of a 'Modification' in the license [1.9].

What is a Modification? Any changes to MPLed files, or new files into which MPLed code has been copied, are Modifications and so fall under the MPL. New files containing only your code are not Modifications, and not covered by the MPL.

Files which fall under the MPL because they are or contain Modifications must be made available as detailed in the license (or elsewhere in this FAQ.) Other files may be kept proprietary.

One well-known example of this is the Netscape-branded browser. It contains (and Netscape makes source code available for) many files from the Mozilla project, which are under the MPL. But it also contains proprietary code, for example to integrate with the AOL Instant Messenger service.

- In our case, we don't modified any of Mozilla/Firefox codes, as well as x4m or SPS codes. All our codes are in separate files, which will be launch using SPS/x4m. Therefor our code is proprietary.It is like the example mentioned above.

- Does the GPL require that source code of modified versions be posted to the public?
The GPL does not require you to release your modified version. You are free to make modifications and use them privately, without ever releasing them. This applies to organizations (including companies), too; an organization can make a modified version and use it internally without ever releasing it outside the organization.

But if you release the modified version to the public in some way, the GPL requires you to make the modified source code available to the program's users, under the GPL.

Thus, the GPL gives permission to release the modified program in certain ways, and not in other ways; but the decision of whether to release it is up to you.


Is sps and x4m here to stay and how to reduce the risk?

- the team vision of developing x4m is to create Real-time shared web applications. Using extensible gecko-browsers family as base, a lot of other add-ons could be added according to current user demands.
- SPS is an application to tryout and demo the feature of x4m.
- They are constantly upgrading x4m and SPS, such as implementing file transfer capability using Google's libjingle and Gateway interaction between MSN, AIM and Yahoo!
- list of team members, click names for profile.
- SPS and x4m are distributed as .xpi files, which can be easily extracted using any unzip utility. All the implementation codes are in there. (Reducing risk if they decided to stop development)
- very interesting points on Rapid development of rich clients and browser extensions

- PROs:
- we can build TrueTalk on top of SPS as its extensions, or might as well create our own extension for firefox (need the codes to connect to gtalk)
- if we use x4m/sps, no need for intermediary servers, we only need firefox or its siblings.

- CONs:
- Only ran on gecko-based browsers.

TrueTalk Demo

- put chatterbox up. DONE.
- keyboard reference
- fix resize prob. DONE.
- find out why the : is being captured - Nothing being captured anymore.

-Scriptlets are micro-extensions in the form of self-contained JavaScript files, useful for prototyping new features or exchanging cool hacks with your friends. They are an experimental feature of the development branch, and you can access them via the "Actions -> Scriptlets" menu.
- our demo is not a scriptlet yet, coz its not in a single .js file
- it's more like a shared application or extensions of SPS, for now.

- launched SPS and demo in Firefox and Flock:
- Error: Flock sends1 correct msg with 1 blank message in the next line
- Error: Flock doesn't set the focus back to the textbox after pressing ENTER











- Firefox is working fine.

Wednesday, June 6, 2007

TrueTalk on XUL

- why XHTML?
- Easier to code, similar to HTML but stricter.
- Supported in all current browser.
- will be rendered without problems on mobile devices.
- ref

- impressive demo of XUL + XHTML (interface-wise)
- to include HTML elements inside XUL, need to add "xmlns:html="http://www.w3.org/1999/xhtml" in [window] tag
- define html element as , eg
: [html:element][/html:element], eg: [html:div id="xmpp-incoming" style="border: 1px black solid"][/html:div]

- Successful attempts:
- Transform the demo chat app codes from html -> XUL+XHTML - It works!
- I've tried to put in on my server, but apparently my server need some configuration to display .xul files correctly. But you can still get it here, and launch it locally. Let's try it together when we are both online.
- Once launched alongside SPS, both side of the chatroom must 'enable' the XHTML page in the right panel first, then only can start chatting on that page.
- The SPS right panel will then be disabled, meaning every message typed from it will not be sent.
- SPS way of doing things : Load XHTML file inside XUL page. Placement may use 'overlays'.
- Overlay = An overlay is used when it is desirable for a block of content to be shared between several different windows. In addition, it can be used to append or alter content in an existing window. An overlay is defined in a separate XUL file. Overlays are applied while the XUL is being loaded. (Works similar to CSS?)
- A Screeny to top it of.












- Links collection
- XUL Periodic table - http://www.hevanet.com/acorbin/xul/top.xul
- CSS Query @ http://blog.hyperstruct.net/2007/5/16/sameplace-spinoffs-1-css-query
- XHTML Validator @ http://validator.w3.org/

- So next, maybe i'll be focussing on how SPS connect to GTalk, and try to implement the codes inside this demo of mine.

Tuesday, June 5, 2007

XUL + xmpp4moz + SamePlace Suite : Problem encountered

- I have a working html+js codes that can capture xmpp packets when launched together with SamePlace Suite (SPS).
- The plan is to understand the packet structure and internal functions (as shown in previous post) that xmpp4moz used to send xmpp packet. To do that, I try to port the html+js codes, into XUL+js codes.
- Here is a demo chat page I've created using XUL.











- Unfortunately, according to the developement docs [here, and here], SPS uses
tags with id = 'xmpp_incoming' to capture the packet, generated by the xmpp4moz lib internally.
- Since I'm using XUL, I've tried to find an equivalent replacement for
tags in XUL, but to no avail.
- I've already post this problem in their google group. Will search for other solution while waiting for their answer. [ may not be necessary since you can use the ff html/xml renderer to draw the incoming xml packets from xmpp4moz ]
See tutorial on how to add html elements to the XUL UI

XUL : In-Depth Learning

- tutorial reference
- Element reference
- There are several ways that XUL applications are created:
* Firefox extension - an extension adds functionality to the browser itself, often in the form of extra toolbars, context menus, or UI to customize the browser UI. This is done using a feature of XUL called an overlay, which allows the UI provided from one source, in this case, the Firefox browser, to be merged together with the UI from the extension. Extensions may also be applied to other Mozilla based products such as Thunderbird.
* Standalone XULRunner application - XULRunner is a packaged version of the Mozilla platform which allows you to create standalone XUL applications. A browser isn't required to run these applications, as they have their own executable file.
* XUL package - in between the other two are applications which are created in the same way as an extension, but they act like a separate application in a separate window. This is used when you don't want to have the larger size of a complete XULRunner application, but don't mind requiring a Mozilla browser to be installed to be able to run the application.
* Remote XUL application - you can also just place XUL code on a web server and open it in a browser, as you would any other web page. This method is limited however, as there will be security concerns that will limit the kinds of things you will be able to do, such as opening other windows.
- When the user downloads it, it will be installed onto the user's machine. It will hook into the browser using a XUL specific feature called an overlay which allows the XUL from the extension and the XUL in the browser to combine together. To the user, it may seem like the extension has modified the browser, but in reality, the code is all separate, and the extension may be uninstalled easily. Registered packages are not required to use overlays, of course. If they don't, you won't be able to access them via the main browser interface, but you can still access them via the chrome URL, if you know what it is.
- Functions/node used for xmpp4moz and Frefox extensions:
- DOMNodeInserted : This event is sent when a node is added as a child of a element. If you capture this element at the document level, you can be notified of document changes (eg: Triggerred when incoming xmpp packet arrived).
- xmpp4moz:: sample code/API
- caught when a DOMNodeInserted event is triggered.

Oreilly book for firefox programming

Programming Firefox Building Rich Internet Applications with XUL. Will have to see if it has anything over documentation on the web.

Tutorial on programming XUL


Monday, June 4, 2007

SamePlace Suite, an xmpp4moz->Gtalk example

- They've got a gtalk client add-ons for Firefox called SamePlace Suite
- It adds a panel to the left of firefox.
- hide panel by pressing F12.
- They have a Monopoly-like game using xmpp4moz+google map!
- demo video
- I didn't set it as auto-login, therefor every time an instance of Firefox is launching, it prompt me for password. Eg: TAG a url into del.icio.us, when a window popup
- Will keep on active as long as xmpp4moz is enabled.
- Solution: since I need xmpp4moz for development purpose, I must unistall SamePlace for now to avoid annoyance.
- Interesting fact: I failed to load a website, while connected via SamePlace. Reload a few times, still fails. Then I disconnect from SamePlace, then reload, at its OK. Might be some issues here.

About Firefox addons, XUL, XULRunner

- Firefox Add-ons:
- uses XUL (JS+XHTML+CSS)
- reference @ http://www.libsuccess.org/index.php?title=Web_Browser_Extensions#Websites_about_Firefox_Programming
- followed tutorial @ http://www.gmacker.com/web/content/tutorial/firefox/firefoxtutorial.htm
- decompiled SamePlace suite codes and see how xmpp4moz -> gtalk works.
- Add-ons usually uses .js files. The different between this and JSJac is, we dont need to have a server that serve the webpages. But users need to download the Firefox 'plug-ins', which is usually small in size. And the add-ons run through Firefox.
- Possible comm. path: Firefox -> Gtalk -> Bot

- XULRunner
- Run XUL develoment codes without using Firefox
- Similar concept to JVM Appletviewer.
- Tutorial @ http://blogs.acceleration.net/ryan/archive/2005/05/06/1073.aspx


- Browser-based VS Web-based
- Since Firefox has emerged as the most extensible browser ever, the term browser-based and web-based turns to a whole new meaning.
- Browser-based : What you launch inside your browser, not necessarily be connected to the internet. Ex: Firebug for debugging websites
- Web-based : Your website. Obivoiusly need to launch inside a browser with internet connectivity.

xmpp4moz: Getting it to work

- http://dev.hyperstruct.net/xmpp4moz
- found the only "Hello World" xmpp4moz tutorial, with a handful of bugs, which I've successfully repaired@ http://www.pixzone.com/blog/84/embed-jabber-in-firefox-with-xmpp4moz-chat-application-how-to/
- sample of the stanza that xmpp4moz catches:













































- this chat app demonstrate the usage of xmpp4moz.
- to use this, you must login to a jabber account using SamePlace Suite 1st.
- then activate the chat page by clicking a button in the SamePlace side panel.
- for detail explanation, refer to here.

Why need Tomcat to run js2gtalk?

Here's a reply from one of the author of J2S, in their google groups:
Zhou Renjian
From: "Zhou Renjian"
Date: Sat, 2 Jun 2007 11:16:21 +0800
Local: Sat, Jun 2 2007 11:16 am

Subject: Re: J2S Gtalk demo : Why do we need to deploy it on Servlet Container (ie. Tomcat)

Here is how the current Java2Script GTalk works: Java2Script GTalk
(browser side) packs some message into HTTP request, send to Apache
server. And Apache server redirects requests to Tomcat server (Java
Servlet container). Then Java Servlet setups and keeps a XMPP
connection to Google Talk Jabber server using Smack library, and then
sends out request, and responses Jabber server's response, which will
redirected to Apache server. And Apache server then returns responses
through HTTP connection to browser. Java2Script GTalk finally updates
its messages or status.

The reason why there is a Tomcat server is that Apache server is not
designed to execute Java codes while Tomcat is. And in fact, you can
build up Java2Script GTalk without Apache server. Tomcat is already
an HTTP server. And the connection will be simplified to:
Java2Script GTalk <--HTTP--> Tomcat <--XMPP (Jabber) [Smack] --> GTalk Server

BTW: you can run Java2Script GTalk standalone as SWT desktop
application with a Java VM environment.


See the communication path :D

How-To make and test Java2Script working (properly)

Here are the ways you should follow:
1) Refer to http://j2s.sourceforge.net/update/
2) Download and install IDE for Java (Eclipse is recommended by J2S developers)
2) Download the J2S library using Eclipse's Update Manager. Choose the default sourceforge.net server. This is to ensure you'll get the library that is 100% compatible with your IDE.
3) To test your newly setup environment, follow the tutorial @ http://j2s.sourceforge.net/articles/getting-started.html

Friday, June 1, 2007

More info on XIFF and j2sgtalk

Xiff+Flash to Gtalk
- Still none existed (none found even in their developers forum)
- they always persistence in their own MUC client - http://xiffian.sourceforge.net/test/
- There are some cross-domain issues that didn't allow flash clients to connect to other jabber server
- Flash-based apps has advantage both in easy-deployment, as well as rich graphical, vector-based content, proven when the Gtalkr guys are being hired by google. But I didn't found any statement that google will have them use XIFF (Correct me if I'm wrong). There's a possibility that they'll use internal google own library (will continue researching on this)


Why need Tomcat to run js2gtalk?
- It uses Java Backends (Smack) to connect to GTalk server. Only Tomcat can execute those Java codes.
- Tomcat uses the Jasper converter to turn JSPs into servlets for execution.
- "It's wise to keep Java code out of your JSPs as much as possible, and put it in either Java taglibs, or in Java beans of EJBs. Your servlet should act primarily as a "traffic copy", receiving requests from the user and directing those requests to the appropriate methods defined in Java beans or EJBs, and then forwarding the response to the appropriate JSP to render the proper view. This design pattern is called "Model-View-Controller" and was made famous in the book "Design Patterns". I strongly recommend this book to anyone serious about moving beyond "hacking code" and doing serious program architecture and design." - http://forum.java.sun.com/thread.jspa?threadID=531586&messageID=2561649

- Possibility: Chat app need open socket connection for message transfer to work. For non-web-based app (JAVA+Smack), the OS handles this. but for web-based app (AJAX), the server is the one responsible for this. In our case, Tomcat uses servlets that has been "deployed" as part of it engine, to open connection to gtalk server. This relates to how Punjab works, by "deploying" itself using the python engine.


Next, I'll be focusing my reseach on xmpp4moz and creating Firefox add-ons.

Comments are appreciated :D

Java2Script Google Talk: Deploying-Customizing

Here are my findings for today:

get J2S from eclipse update manager
===================================
- used http://j2s.sourceforge.net/update
- tried using mirror from Ishikawa Japan, gave out wrong version
- retry, got latest version from The default site [j2s 1.0.0v5.2.0]. Easiest & u'll get the latest version.


connecting to gtalk using j2s
=============================
- need a servlet container
- apache tomcat engine (http://tomcat.apache.org/index.html)

- Tomcat Engine ver x.x?
- Apache Tomcat caters jsp spec from various version (http://tomcat.apache.org/whichversion.html)


- Tomcat connector?
- it's mod_jk!


- mod_jk?
- mod_jk is a replacement to the elderly mod_jserv. It is a completely new Tomcat-Apache plug-in that handles the communication between Tomcat and Apache. (http://tomcat.apache.org/tomcat-3.2-doc/mod_jk-howto.html)


- installing apache tomcat
- in C:\Program Files\Apache Software Foundation\Tomcat 6.0











- no need to run wamp and tomcat at the same time?
- successfully ran tomcat without wamp (put offline + stop all service)

- configuring apache, tomcat @ http://tomcat.apache.org/tomcat-3.2-doc/mod_jk-howto.html
1) remove mod_jserv if exist, including tomcat-apache.conf or tomcat.conf in httpd.conf
2) ..halt!

- Running J2S gtalk client on localhost succeeded!









- known bug:
- u'll stay online on you buddy's roster's after you logout
- but after 2 minutes, u'll be offline in the chat window, still online on their roster















- recompiling j2sgtalk demo:
- It uses SMACK!
- possible comm. path : Java+Smack+J2S -> Javascript -> Tomcat -> Gtalk -> Conf. Bot
- recompile success, but nothing appear after deploy and launch, the original web.xml are much more complex than what i did.

- running j2sgtalk on plain server
- unsuccessful

- simply copy/paste j2sgtalk folder into Tomcat root dir
- eventhough it shows as a tomcat app in the tomcat manager page, it still wont work.
- possible cause: the web.xml points to classes & libs that need to be loaded inside tomcat, as part of its module


- ajaxrpc?
- is part of junit.framework.TestCase - http://jsourcery.com/api/apache/webservices/axis/1.4/test/jaxrpc/AJAXRPC.html
- IMO: is a testing/debugging library for ajax


- xiff+gtalk?
- as of today...no one has ever done it.
- limitations and possible workarounds - http://www.igniterealtime.org/forum/message.jspa?messageID=103593



- What's up next?
- xmpp4moz - XMPP for Mozilla - http://dev.hyperstruct.net/xmpp4moz
- XMPP Library for firefox - http://www.bolinfest.com/changeblog/2007/03/31/request-for-help-xmpp-library-for-firefox/
- Websites about Firefox Programming - http://www.libsuccess.org/index.php?title=Web_Browser_Extensions#Websites_about_Firefox_Programming
- XMPP library for JAVA - http://www.igniterealtime.org/projects/smack/

Design thoughts

There seems to be a few ways to get a browser app to talk to gtalk.

1. Ajax ------ punjab/tomcat/java servlet ------- Gtalk

The intermediary is because Ajax / Html is stateless and gtalk/jabber requires a statefull system. One success is by using java2script library which Hazrat has shown can connect to gtalk. One issue will be the latency introduced by the middle servlet module in java2script system.

(note the java2script client is on the left)

We will also need to build a conference bot to simulate chat in gtalk and the hops will be:

Ajax ------ tomcat -------- gtalk --------- conference bot

which will add additional latency.


2. Flash ----- Gtalk

Not sure if this needs an intermediary since Flash should be able to maintain state.
Potential libraries are Ignite's XIFF API and jabberflash.
They can talk to jabber servers, but not sure about gtalk yet. Hazrat ?
Since google's gtalk gadget is written in flash, this might be the way to go.

article on XIFF

3. Firefox extension ---- Gtalk

This has potential, though the application development could be tougher because parts of it have to be built in XUL & C (verify ?)
Potential library xmpp4moz.
Verify if it can talk to gtalk. Hazrat ?
Interesting links on programming Firefox

4. Java -- Gtalk
Ignite's Smack API
Interesting Bolinfest article on it.

This would be like the original OnChat and will suffer from the problems
of developing an attractive small java applet for the browser - not so keen on this approach.

Thursday, May 31, 2007

Office Charges / Rents

Even though this is out of the topic :P It's a good fact to know about how office spaces are being charged.

I have the privilege of setting up my own office for my Industrial Training. Now, I don't think there ever a student who need to setup their own office for IT. It is a very good life experience.

According to Mr. Shahril, rents are assigned according to the office logistics. Here's a list:
  • Mersing : RM0.25/sqft
  • TM Tower: RM1.25/sqft
  • KLCC: RM6 - RM8/sqft
  • PJ: TBA :D
Each employee requires about 100-150 sqft of area which includes
bathroom & common areas. So if there is an office of 10 people, you need about 1000 - 1500 sq ft of space.
And the total amount should be Room size x price/sqft.

For the office in PJ, I think the space the provide me is around 8x8 ft, enough for a PC table and a chair. There are 2 more tables and chair set in the other side of the room, I'm not sure whether there are people there.

Java2Script

Its a great tool for Java expert to simply convert their existing java app into web-based app. We can easily use SWT (Standard Windows Toolkit), to create the UI part.

I've tried the J2S with 2 apps. the 1st one is a simple, console-based HELLO WORLD java app and 2nd one is the HELLO WORLD app using SWT. Both can be run successfully using Eclipse.

After that, I tried running both apps as J2S app. The simple (non-SWT) app run OK, but not the one using SWT. I've checked SWT version, the J2S, all docs and tutorial on the net, but to no avail. I even post on their google groups but there are still no response. Here's a screeen shot of the error:



I'm not sure where "Line: 25" refers to, as there are certainly less than 25 lines in my codes. It maybe part of the loader that is trying to load the supposedly created .js file.

I found out that, for the non-SWT app, J2S has converted it's code into a .js file. But there is no .js file for the app with SWT. There maybe clashes between those 2 libraries. Posted this issue in their group too.

I'm sure its an error related to my IDE, but I'm still trying to rectify it.

Wednesday, May 30, 2007

Punjab

I happened to have access to their SVN and using that, I've updated my Punjab to the latest version. When I tried to install punjab, it returns this error :
/python2.3/distutils/dist.py:227: UserWarning: Unknown distribution option: 'package_data'
warnings.warn(msg)

According to plone website, it may because Iwas trying to install it on Python 2.3 (That was the version of Python on our server). Maybe it would be ok if I run it on different version of Python. I have version 2.4 and 2.5, since it also requires modification on the server, I'll put it on hold for a while.

Globsy

The main purpose for this framework is to setup a BOT that represents you on your gtalk account, sort of automatic response unit of some sort. Since it is a BOT for gtalk users, there's a slight possibility that we can manipulate it to be the liaison to the gtalk server.

I've tried it also for a few hours. It has many dependencies that need to be installed. Luckily I have installed it all except a C library called cURL. The documentation for it is very limited. At the end of the day, I email the author of Globsy asking for help and he replied with a couple of advices.

Since it does require major modification to the server, I put it on hold too, so that i could lay my hands on Punjab once more.

JabberHTTPBind

Tried JHB for a few hours. It can't work properly because I have not install any servlet container (ie: Tomcat). I will try to install Tomcat for Apache later, but for now, i'll try to figure out the simplest way to setup a connection between our server and GTalk, that didn't require major server modification.

The author has setup a website combining JWChat with JHB here. If you use the default server, then it'll work out OK. But when I try to connect to GTalk, multiple times with various settings, it won't work. I've post some question on the development blog here, and still waiting for the response.

Tools of Trade

Here are the tools that may help us:

Punjab :
- is a HTTP jabber client interface. It is a SOAP, XMLRPC, JEP-0025 or JEP-0124 server that allows persistent client connections to a jabber server. It can be used for many things, but its main purpose is to allow for stateless applications (ie web) a stateful connection to jabber. LINK
jwchat & Punjab

jabberHTTPBind (JHB) :
- is a java servlet implementing JEP-0124 (HTTP Binding) thus enabling you to connect to any Jabber™ server by way of HTTP Binding. LINK


Globsy :
- Globsy is a PHP bot framework for the Google Talk network that can be executed from a regular browser on a PHP enabled server, connect to the Google Talk network and continue running in the background, without the browser needing to remain open. LINK


Java2Script :
- java2Script (J2S) Pacemaker provides an Eclipse Java to JavaScript compiler plugin and an implementation of JavaScript version of Eclipse Standard Widget Toolkit (SWT) with other common utilities, such as java.lang.* and java.util.*. You can convert your SWT-base Rich Client Platform (RCP) into Rich Internet Application (RIA) by Java2Script Pacemaker. LINK