1. Testing the Firefox browser on mobile websites: Are you game?

    Friends and hackers, we have a challenge

    Are you a developer who’s passionate about Mozilla’s mission on the open Web? We need your help: We’re looking for someone to build a game to help keep the Web open as it goes mobile. There’s a Firefox mobile website testing app which we think would make a nice little HTML5 game — with scoring, achievement, levels, leaderboards — and we think you have the chops to make it fun. We’ve had some success making a game of the activity within our team, but we think you could do it better.

    Here’s some context. We need lots of people looking at lots of frequently visited websites to see if they look good and work well on mobile. And if they don’t, we need to figure out how to make them better: by finding the bugs and fixing our browser or by working with the developer who built the site to make it work on the open Web. Testing Fennec matters for the future of the open Web:

    Fennec, Mozilla’s mobile browser, just landed in Google Play (you may remember it as the Android Marketplace). Firefox Beta for Android is better than ever! You can download it now, use it on your Android phone or tablet and share your feedback. If you get hooked on testing, you’ll want to create a bugzilla account (if you don’t have one) and start filing bugs. By

    If you’d like to do a little more directed testing, check out Aaron Train’s most excellent testing app, which sends you to some of the world’s leading websites to share your feedback. This is the app we’d like to gamify, to motivate more people in the Mozilla community to help us keep improving the Firefox mobile web experience for everyone.

    What matters is mobile

    It’s an interesting exercise to start viewing and interacting with the world’s most frequently used websites in a mobile browser. Any mobile browser. You realize the mobile Web has a ways to go. But there’s more to it than that. David Slater, who leads Product Marketing at Mozilla put it so well that I’m just going to share a note that he sent out internally earlier this week:

    The mobile Web is under threat. For 8 years Mozilla has fought to make the Web open on desktop – and won. On mobile, it’s different – the battle is underway. In order to win, we will have to make the Web on mobile devices as compelling for developers and users as native mobile apps are today. Marketplace is about doing that. Boot-to-Gecko, ultimately, is about doing that. But first, we have to break open the mobile web and expose the issues.

    Today, Apple and Google – and therefore browsers based on Webkit – are dominating the mobile Web, and as a result developers are coding for a single rendering engine. Like we did with desktop, we have to ensure developers have access to truly open standards. And that means that we need to do whatever it takes to establish Gecko‘s presence on mobile – and specifically, on the Android platform which is widely forecast to grow more than any other in the next 5 years.

    There are many ways you can join us in this battle, but if you’ve been wanting to test your skills by building a Web game, there’s never been a better time to try, and never for a better cause. And if you need a little help, there are many places you can ask, like our IRC channel, #devrel, the engagement-developers mailing list, or simply @mozhacks on Twitter. And, of course, if you do, we’ll make you MDN-famous, and treat you like a hero. Thank you.

    Heroes Wanted

  2. Mozilla supports the Liberated Pixel Cup for open games

    We’re excited to announce that Mozilla is supporting the Liberated Pixel Cup, a fantastic competition aiming to spark the creation of artwork and code for games that are free and available for others to use.

    The Liberated Pixel Cup is the brainchild of OpenGameArt, a long-standing community of artists that provide graphics and sound effects for others to use in their games. Joining us in supporting the competition are the Creative Commons, Free Software Foundation, as well as the hundreds of everyday supporters who donated to the prize fund.

    Getting involved with the Liberated Pixel Cup was an obvious choice for us. Over the past year we’ve vastly improved our performance for games in Firefox, we’ve added new features for games, we’ve hosted a work week to discuss the future of games, we’ve attended and represented the open Web at important game-related events like GDC, as well as much, much more. To put it simply, we think games are pretty darn important to the future of the Web!

    As part of our involvement, we’ll be:

    • Supporting the HTML5 category of the competition
    • Using our various spaces around the world to host Liberated Pixel Cup events
    • Donating funds to support the running of the competition

    The art side of the competition starts in June, with the code side starting in July; so mark those dates in your diary and get ready to create some game-related goodness!

    Check out the Liberated Pixel Cup website for more information.

  3. The Web Developer Toolbox: Raphaël

    This is the first of a series of articles dedicated to the useful libraries that all web developers should have in their toolbox. My intent is to show you what those libraries can do and help you to use them at their best. This first article is dedicated to the Raphaël library.

    Introduction

    Raphaël is a library originally written by Dmitry Baranovskiy and is now part of Sencha Labs.

    The goal of this library is to simplify work with vector graphics on the Web. Raphaël relies on the SVG W3C Recommendation (which is well supported in all modern browsers) and falls back to the Micrsoft VML language in order to address legacy versions of Internet Explorer. It also tries to harmonize some working issues across SVG implementations such as the SVG Animations. As a consequence, Raphaël is a very nice wrapper to produce consistent kick-ass graphics all over the Web.

    Basic usage

    The library has very good documentation with many examples. Do not hesitate to use it extensively.

    The following example will draw a simple red circle inside an HTML element with the id “myPaper”.

    // the following example creates a drawing zone
    // that is 100px wide by 100px high.
    // This drawing zone is created at the top left corner
    // of the #myPaper element (or its top right corner in
    // dir="rtl" elements)
    var paper = Raphael("myPaper", 100, 100); 
     
    // The circle will have a radius of 40
    // and its center will be at coordinate 50,50
    var c = paper.circle(50, 50, 40); 
     
    // The circle will be filled with red
    // Note that the name of each element property
    // follow the SVG recommendation
    c.attr({
        fill: "#900"
    });

    Advanced usage

    Despite the fact that Raphaël reduces the possibilities offered by SVG (mainly because of the VML fallback) it allows one to perform very advanced stuff:

    • Advance Matrix transformation
    • Advance event handler
    • Cross browser animations
    • Easy drag system
    • Path intersection detection

    Raphaël is also extensible through an extension system that allows you to build custom functions.

    For example, here’s an extension to draw pie charts:

    /**
     * Pie method
     *
     * cx: x position of the rotating center of the pie
     * cy: y position of the rotating center of the pie
     * r : radius of the pie 
     * a1: angle expressed in degrees where the pie start
     * a2: angle expressed in degrees where the pie end
     */
    Raphael.fn.pie = function (cx, cy, r, a1, a2) {
        var d,
            flag = (a2 - a1) > 180; 
     
        a1 = (a1 % 360) * Math.PI / 180;
        a2 = (a2 % 360) * Math.PI / 180; 
     
        d = [
            // Setting the rotating axe of the pie
            "M", cx, cy,
     
            // Go to the start of the curve
            "l", r * Math.cos(a1), r * Math.sin(a1),
     
            // Drawing the curve to its end
            "A", r, r, "0", +flag, "1",
            cx + r * Math.cos(a2), cy + r * Math.sin(a2),
     
            // Closing the path
            "z"
        ]; 
     
        return this.path(d.join(' '));
    };

    Note: In the example above, you have to be familiar with the SVG path syntax (Raphaël will convert it to the VML syntax under the hood), but once it’s done you can reuse it as any other Raphaël primitive. Look at this extension working to draw a color wheel on jsFiddle.

    Limits and precaution

    If you are not familiar with SVG and/or want to support legacy MS Internet Explorer browsers, this tool is made for you. However, it’s a JavaScript library, which means that you have to know JavaScript to use it. You cannot use SVG and ask Raphaël to parse it and interpret it (to do that, it exists other libraries).

    In terms of browser support, Raphaël gives you a large base. Raphaël currently supports Firefox 3.0+, Safari 3.0+, Chrome 5.0+, Opera 9.5+ and Internet Explorer 6.0+.

    In fact, the only browser that can not take advantage of Raphaël is the native browser for Android 1.x and 2.x (and obviously many feature phone browsers). This is due to the fact that those browsers do not support any vector language. Android starts (partially) supporting SVG with Android 3.0 so take care if you want to work with all mobile devices.

    Conclusion

    Raphaël was the first library to allow web designers and web developers to use SVG in the wild. If you want to write some nice applications without the need of the full SVG DOM API or if you have to support legacy browsers, this library will give you some power.

    In conclusion, here are some cool usages of Raphaël:

  4. Desktop Apps with HTML5 and the Mozilla Web Runtime

    Desktop Apps with HTML5

    One of the best things about HTML is that it’s never “done”.  HTML has been with us longer than most of the development technologies that we consider commonplace. (.NET, ASP, Java, PHP, etc.)

    The latest incarnation of HTML, HTML5 has been the source of a great deal of buzz in the software and information industries. When we say “HTML5″, we’re implicitly referring to the “stack” of  HTML/CSS/JavaScript.

    At Mozilla we often refer to this collectively as the “Web Run-Time” or WebRT for short. Mozilla’s apps initiative, including the Web Runtime is documented here.

    Skeptics like to say “HTML5 is not ready”. This week I saw an article declaring HTML5 won’t be “ready” for another 10 years. To which I ask “ready for what?” Of course there are many APIs that are still under development, but for many scenarios HTML5 is ready now. For many other scenarios its ready for development now and will be ready for general public use in the near future.

    Recently the Mozilla Apps Native Install Experience was introduced to the Firefox Nightly Channel. (Read here for more information about the Firefox release channels.)

    This functionality lets us install an HTML5 application with a native launching experience on Windows or Mac (Linux and Android coming).

    One great way to do this is to simply list your app in the Mozilla Marketplace. The Marketplace will be open to the general public soon and developers can submit their app now at the Marketplace Ecosystem Portal. All you need besides an app to submit is a set of BrowserID credentials.

    An HTML5 App that targets the Mozilla Web Runtime includes a manifest file.

    The manifest is simply a JSON file that declares certain data about the application.

    Here is the manifest file from a sample app. You can read more about the Mozilla App Manifest here.

        {  
          "version": "1.0",  
          "name": "KO Round Timer",  
          "description": "A Workout Timer for Fighting Athletes!",  
          "icons": {   
            "128": "/images/icon-128.png"  
          },    
          "developer": {  
            "name": "Joe Stagner",  
            "url": "http://koscience.com"  
          },  
          "installs_allowed_from": [  
            "http://timer.koscience.com", 
    	"https://marketplace.mozilla.org"   
          ],    
          "default_locale": "en"  
        }

    JSON does not need to be formatted with CRLFs. The above JSON is only formatted to simplify display.

    Note line #12 above which specifies where the app can be installed from.

    The Mozilla Web Runtime includes an apps object (winbow.navigator.mozApps) The mozApps object (currently implemented in Firefox Nightly on Windows and Mac) has a method to install an application. We’ll look at code that uses that API in a minute.

    If you want your app to install from the Mozilla Marketplace you don’t need to write any install code. When you list your app in the marketplace, the marketplace creates a listing page for your app and that page includes an install button.

    Mozilla Marketplace App Listing Page

    The generated code that is invoked when the Install button is clicked tells the Runtime to install the app. The Runtime then fetches the manifest for the app and, among other things, checks to see it the app allows installation from whatever domain is requesting the install.

    As you can see in the manifest listing above, line 14 specifies that the app may be installed from “https://marketplace.mozilla.org”.

    But you might want to let users install your application from other domains, for example your own web site.

    You can see line 13 in our sample manifest, listed above, that “http://timer.koscience.com” is also specified as a valid “install from” location. I can specify as many domains as I like to be authorized to install the application from and wildcards are supported.

    If we want to install the app from our own web site however, we need to implement the install logic ourselves.

    We could create a page similar to the app listing page on the Mozilla Marketplace, or could make the app “self installing” meaning that we could implement installation logic in the app itself.

    Take, for example, the Workout Timer app shown below.

    K.O. Timer Screen Shot

    Notice the row of navigation buttons at the bottom of the timer.

    The last one to the right says “Install Me”.

    The install button should only appear if the app is running in an environment that supports the mozApps runtime. Since this app (K.O. Timer) is an HTML5 app it can run in any HTML5 compliant browser but will only be “installable” if it is running in a browser / runtime with mozApps support.

    We also don’t want the install button to appear if the app is already installed.

    Here is a JavaScript method to test both runtime support and install state.

    If runtime support is present and the app is not install then an install button is displayed.

    In some scenarios you might choose to forgo the display of an optional install button and simply start the installer when the app is not already installed.

    (This code is using jQuery)

    function TestAppInstalled() {
        if ((!navigator.mozApps) || (!navigator.mozApps.getSelf)) {
            /*-----------------------------------------------------------+
            || Test to see if the Mozilla Apps Web Runtime is supported
            || HACK: Testing for either mozApps OR mozApps.getSelf is a 
            || hack. 
            || This is needed because some pre-beta versions of Firefox 
            || have the object present but nit fully implemented.
            || TODO: Update when Firefox Desktop & Mobile are complete.
            ------------------------------------------------------------*/
            return;
        }
     
        var MyAppSelf = navigator.mozApps.getSelf();
        MyAppSelf.onsuccess = function() {
            if (! this.result) {
                // Application is not "installed"
                $('#InstallButton').show();
            }
            else {
                 // This "MozApp" is already installed.
            }
            return;
        }
        MyAppSelf.onerror = function() {
            alert('Error checking installation status: ' + 
                   this.error.message);
            return;
        }
    }

    When the user clicks on the install button the following code is called.

    $('#InstallButton').click(function() {
        var installation = navigator.mozApps.install(
                    "http://timer.koscience.com/kotimer.webapp");
        installation.onsuccess = function() {
            $('#InstallButton').hide();
            alert("K.O. Timer has been successfully installed.....");
        }
        installation.onerror = function() {
            alert("APP: The installation FAILED : " + this.error.name);
        }
    });

    So when the user navigates to the K.O. Timer app (timer.koscience.com) in a browser that supports mozApps (currently Firefox Nightly) and the user clicks on the “Install Me” button the mozApps runtime starts the installer.

    KOTimer at Install Click

    KOTimer at Install Click Closeup

    After the user clicks “install” button in the dialog pictured above, the installer is called and, when completed, the user has a native launching experience.

    On Windows you get a desktop shortcut.

    Native Shortcut for HTML5 App

    As well as a Start Menu item.

    HTML5 app in the Windows Start Menu

    And, of course the app is now in the user’s Mozilla MyApps collection.

    Mozilla MyApps Collection

    It’s important to remember that, while these launchers have been created on the user’s system the application itself still exists in the cloud. A developer can choose to add “off line” functionality to their application by other HTML5 features like AppCache, LocalStorage or IndexedDB.

    The ability to provide native launchers for HTML5 apps, coupled with the huge HTML5 apps distribution mechanism that will be available when the Mozilla Marketplace become available to the general public (in the near future), creates great opportunity for developers building standards based apps.

  5. MDN hack day tomorrow in the #mozldn space in London, England

    We cleared the aftermath of yesterday’s epic Geek Quiz (photo proof here) but there is no rest for the wicked in the London Mozilla Space. Tomorrow (yes, that day after this one) we’ll run an MDN hack day here in 101 St. Martin’s Lane, London (5 minute footwalk from Leicester Square or 10 from Charing Cross).

    If you have no idea what hack day in MDN means, check out Tristan Nitot’s introductory post.

    MDN hack day

    There are still tickets available, so go to http://mdn-hackday-london.eventbrite.com/ and sign up if you haven’t yet.

    There’ll be food (well, Pizza, we thought Fondue would be too much of a mess) and drink (the non-fermented and fermented kind, we don’t discriminate), lots of experts from Mozilla to pester about your wishes for our products and to learn all about what we are doing in London, a few Boot to Gecko phones to play with and quite a few talks to give you inspiration to hack:

    Schedule (subject to change slightly but you get the idea of who is speaking):

    8:30 Registration & Light Breakfast
    9:00 Welcome Remarks Christian Heilmann
    9:15 Christian Heilmann – The New Web Challenge
    9:45 Rob Hawkes – B2G
    10:15 Chloe Varelidi – Catch Them Young – Meet the Web Arcade
    10:45 Brad Lassey – Fennec Goes Native
    11:15 Break
    11:30 Heather Arthur – Firefox DevTools
    12:00 Jean Yves Perrier – BrowserID
    12:30 Rob Hawkes – Games
    1:00 Paul Lewis – WebGL Live Demos
    1:30 Lunch (Lightening Talk/Discussion Group Sign Up)
    2:30 Hacking
    5:15 Presentations and Lightning Talks
    5:30 Refreshments

    The hashtag to use is #mdnhackday, the wireless is open, the Fox is out there, let’s do this!

  6. Getting snappy – performance optimizations in Firefox 13

    Back in the fall of 2011, we took a targeted look at Firefox responsiveness issues. We identified a number of short term projects that together could achieve significant responsiveness improvements in day-to-day Firefox usage. Project Snappy kicked off at the end of the year with the goal of improving Firefox responsiveness.

    Although Snappy first contributed fixes to Firefox 11, Snappy’s most noticeable contributions to date are landing with Firefox 13. Currently in beta, this release includes a number of responsiveness related fixes, most notably tabs-on-demand, cycle collector improvements, and start-up optimization.

    Tabs -on-Demand

    Tabs-on-demand is a feature that reduces start-up time for Firefox windows with many tabs. In Firefox 12, all tabs are loaded on start-up. For windows with many tabs this may cause a delay before you can interact with Firefox as each tab must load its content. In Firefox 13, only the active tab will load. Loading of background tabs is deferred until a tab is selected. This results in Firefox starting faster as tabs-on-demand reduces processing requirements, network usage, and memory consumption.

    Cycle Collector

    As you interact with the browser and Web content, memory is allocated as needed. The Firefox cycle collector works to automatically free some of this memory when it is no longer needed. This action reduces Firefox’s memory usage. In Firefox 13, the cycle collector is more efficient, spending less time examining memory that is still in use, which results in less pauses as you use Firefox.

    Start-up

    Firefox start-up time is visible to all users. Our investigation into start-up has identified a number of unoptimized routines in the code that executes before what we call “first paint”. “First paint” signifies when the Firefox user interface is first visible on your screen. In Firefox 13 we have optimized file calls, audio sessions, drag and drop, and overall IO, just to name a few. We are continuing to profile the Firefox start-up sequence to identify further optimizations that can be made in future releases.

    There are numerous other Snappy fixes in Firefox 13 including significant improvements to IO contention, font enumeration, and livemark overhead. All of these fixes contribute to a more responsive experience. We are already working on further responsiveness fixes for future Firefox releases. You can expect to see Snappy improvements in upcoming releases in areas such as memory usage, shutdown time, network cache and connections, menus, and graphics.

  7. DOM MutationObserver – reacting to DOM changes without killing browser performance.

    DOM Mutation Events seemed like a great idea at the time – as web developers create a more dynamic web it seems natural that we would welcome the ability to listen for changes in the DOM and react to them. In practice however DOM Mutation Events were a major performance and stability issue and have been deprecated for over a year.

    The original idea behind DOM Mutation Events is still appealing, however, and so in September 2011 a group of Google and Mozilla engineers announced a new proposal that would offer similar functionality with improved performance: DOM MutationObserver. This new DOM Api is available in Firefox and Webkit nightly builds, as well as Chrome 18.

    At it’s simplest, a MutationObserver implementation looks like this:

    // select the target node
    var target = document.querySelector('#some-id');
     
    // create an observer instance
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            console.log(mutation.type);
        });    
    });
     
    // configuration of the observer:
    var config = { attributes: true, childList: true, characterData: 	true }
     
    // pass in the target node, as well as the observer options
    observer.observe(target, config);
     
    // later, you can stop observing
    observer.disconnect();

    The key advantage to this new specification over the deprecated DOM Mutation Events spec is one of efficiency. If you are observing a node for changes, your callback will not be fired until the DOM has finished changing. When the callback is triggered, it is supplied a list of the changes to the DOM, which you can then loop through and choose to react to.

    This also means that any code you write will need to process the observer results in order to react to the changes you are looking for. Here is a compact example of an observer that listens for changes in an editable ordered list:

    <!DOCTYPE html>
    <ol contenteditable oninput="">
      <li>Press enter</li>
    </ol>
    <script>
      var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
      var list = document.querySelector('ol');
     
      var observer = new MutationObserver(function(mutations) {  
        mutations.forEach(function(mutation) {
          if (mutation.type === 'childList') {
            var list_values = [].slice.call(list.children)
                .map( function(node) { return node.innerHTML; })
                .filter( function(s) {
                  if (s === '<br>') {
                    return false;
                  }
                  else {
                    return true;
                  }
            });
            console.log(list_values);
          }
        });
      });
     
      observer.observe(list, {
      	attributes: true, 
      	childList: true, 
      	characterData: true
      });
    </script>

    If you want to see this code running, I’ve put it up on jsbin here:

    http://jsbin.com/ivamoh/53/edit

    If you play with the live example, you’ll notice some quirks in behaviour, in particular that the callback is triggered when you press enter in each li, in particular when the user action results in a node being added or removed from the DOM. This is an important distinction to be made from other techniques such as binding events to key presses or more common events like ‘click’. MutationObservers work differently from these techniques because they are triggered by changes in the DOM itself, not by events generated either via JS or user interaction.

    So what are these good for?

    I don’t expect most JS hackers are going to run out right now and start adding mutation observers to their code. Probably the biggest audience for this new api are the people that write JS frameworks, mainly to solve problems and create interactions they could not have done previously, or at least not with reasonable performance. Another use case would be situations where you are using frameworks that manipulate the DOM and need to react to these modifications efficiently ( and without setTimeout hacks! ).

    Another common use of the Dom Mutation Events api is in browser extensions, and in the next week or so I’m going to publish a follow-up post on how MutationObservers are particularly useful when interacting with web content in a Firefox Add-on.

    Resources

  8. State of the Docs, May 9th, 2012

    By rights, today’s edition of “State of the Docs” should be a little light, since it has been only a week and a half since a very productive documentation sprint. But our amazing documentation contributors collectively do not rest, and so there is still lots to mention.

    Outside the usual categories of docs, Tom Lowenthal created a page of privacy policy guidelines, with help from Jishnu Menon, along with a privacy policy template that you can fork on Github. If you missed the earlier Hacks post about privacy guidelines, check it out.

    Help needed

    Fbender added a note to the Talk page for JavaScript Functions and function scope that “conditionally defining a function throws an error in at least ES5 strict, possibly non-strict (at least soon), too, see Bug 609832 and Bug 585536. The section Conditionally defining a function should be updated to reflect those changes.” Want to make that change? Go for it!

    Web standards docs

    Mozilla technology docs