Notas de un Peregrino Articulos varios sobre la web, mozilla y firebug

3Dec/10Off

Grooveshark Remote Control

Update: Now the extension is listed and approved in AMO!

Maybe not all of you noticed, but today Grooveshark changed it's UI from the regrettable Flash to a shiny and great HTML interface! YAY!!

Well, being myself a prototyping addict, the first thing I thought was:

"HTML UI + Javascript == Hackability!"

And started coding right from within Firebug the basis of what I wanted to build: A remote controller for Grooveshark!

Before, with the Flash UI, the only way to control Grooveshark was from the page itself. No Javascript APIs were enabled on the player object, so the only way to operate it was the user going there directly. But nowdays, we all browse the web with at least 5 tabs open, and switching to Grooveshark (even for looking at the name of the song being played!) is tiring.

So, enter Jetpack, HTML and Javascript. I was really wanting this feature for a loooooong time, so I took the first chance I had to code it! After some hours inspecting Grooveshark and guessing the API, I ended up with a prototype extension working decently good in Firefox. And is a surprisingly short extension, 85 lines aprox, but with a tremendous UX enhancement for Grooveshark :)

Now, the links and warnings:

WARNING:
As I said before, this is a working prototype. It can screw your tabs. It can do weird things with your Firefox. It can even not work. So you're warned, try this on a new profile or take your chances. Be brave.

Known Issues:

  • Grooveshark now has HTML UI, but in the end is a Flash player. So if you have a flashblocker, add an exception to grooveshark or disable it for testing this addon.
  • It might reload ALL your tabs. This happened randomly, but in different computers. As I used a mixture of unstable software to code this (unstable firefox, unstable jetpack, and 1st day released grooveshark UI) and was coded in like 4hs I still don't know what's the cause.
  • You may have some issues regarding weird combinations of play/pause.
  • I didn't test it on FF3.6, but an alpha tester just told me that deactivating compatibility check in 3.6 it was working.

Functionality:

  • The UI is only shown when a grooveshark tab is open. If you close grooveshark, the remote control goes away until you open the tab again.
  • Once grooveshark is loaded, fill the queue with songs (radio, custom playlist, whatever)
  • Then control the reproduction with the (<<), (>), (||) and (>>) buttons.

Requirements:

Installation:

Is a Restartless addon (as it's coded entirely in Jetpack), so you won't need to restart your browser to test it :)

Further Improvement:

There's loads of things to improve with this addon! I'm planning on maintaining this, so send your comments/complains/etc. to hernan@bipgeeks.com or leave a message in here! Also, a Chromium and maybe Safari and Opera versions are comming too :) .

If you want to help with this, and specially if you're a Designer, I encourage you to contact me in any of the aforementioned ways!

11Aug/10Off

Jetpack and Code Portability

Yesterday I was tinkering with my Multitouch Simulator Jetpack wondering if I could take the code out of it and make it a standalone library. I expected some pain extracting the code and making it work on a webpage as it's a somewhat different environment... I couldn't be more wrong.

From the beginning I wanted to code the extension's modules in a way that would allow me to take them away from the Jetpack extension. But that was it, just a wish, I didn't write each single line thinking on portability. Hopefully things ended up better than I expected.
When it was time to take the code out, I just copied the events dispatcher and files parser modules, performed 2 or 3 global replaces because of conflicting names and... job done! You can see the results in here with Firefox Minefield.

I think this is a great feature, not only meaning that you can take your code out from a Jetpack extension, but also the possibility of putting in a Jetpack previously coded "for the web" JavaScript libraries!

If you know me a little,  you would guess that I couldn't leave that possibility without a try... And you would be quite right :D So I took some little bit of code that Marcio Galli showed me on twitter, a QR-Code maker done entirely in Canvas+Javascript (see here), and decided to stuff it in a Jetpack.
Again, a very effort-less thing with great results. I ported that code to Jetpack in a blink, and created a qr-code library for jetpack, and in 5 more minutes, I had this Selection-To-QRcode extension running.

So, in brief, these are some exciting new possibilities to expand and remix the web and your experience with it!

Filed under: English, Jetpack No Comments
6Aug/10Off

New recording features for the MT-Simulator

The end of the Google Summer of Code is approaching and the Simulator have reached the Feature Completion stage. From now on, only minor bugfixes will be made untill the end of the project (August 16) when I have to submit the final code. From that on coding won't stop, is just that the GSoC ends. Probably the way things are done will be different and more feedback will be seek, but this project will surely continue.
And now the news about this release...

Notice
If you don't want to read the whole stuff and go right to the testing and trying fun stuff, just jump to the "Links! Links! Links!" section on the bottom

The new Recording features

Something that was very very needed was a more natural way to record the input files. Doing so programatically tends to be more dificoult and troublesome than moving your mouse around, so something had to be done. After some thinking and discussion with Felipe, I came up with a more comfortable way to record the files. I'll describe it briefly here, but you can alsgo skip it and see a demo after the break :) .

Basically the UI consists of a representation of the fingers on the screen. Moving them with the mouse represents the movement of the fingers on the multitouch surface.

First you click the Start Recording Button and choose where to save the final file. Once the file is specified, the number of fingers that will be on-screen has to be chosen. Pushing the Finger Button will add a finger to the screen, but beware because there's no way to remove a finger for now.

Doing the recording is pretty straight forward. All fingers are recorded in cycles, one at a time starting from the first one added and then going sequentially with the rest. The cycle starts again when the last finger is done.
Before starting to record the actual moves, you have to set the starting position of each finger. Doing so is pretty easy, drag the black-bordered (active) finger and then click on the Accept Button, then the next finger will be activated and so on. Once all the fingers are set, the recordings can start.

You will notice when the fingers are being recorded because a trace of the finger movement will appear on screen. If a mistake happens, the finger movement can be undone, and this can go as far as the first finger of the cycle. The recording cycles can be repeated until you decide to hit the save button.

When the cycle is finished (last finger moved) it can be played back, triggering the multitouch events on the page, with the Play button. This is in case some actions are needed in order to continue recording. Keep in mind that this is a replay of just the previous recorded cycle: you cannot do it twice and cycles don't accumulate.

When you decide the recording is done and click on the save button, the file will be closed and saved. Also, every element added for the recording will be removed from the screen.

Multitouch Landed on trunk!

For those who are wondering what does this means: Multitouch support is now on Minefield and will be included on the Firefox 4 Beta 3 that is going to be released soon. This also means that the custom build I had to upload on my previous post is no longer needed to try the extension :)

Links! Links! Links!

You can download the multitouch simulator 0.4 from AMO here. Remember to download the xpi and drag n' drop it on firefox, that will do for installation. In Firefox 3.6 you'll have to restart to see the efects, but in Firefox 4 betas the extension will load without restart :D If you find the bottom bar annoying, it can be hidden pressing Ctrl+Shift+U (or in OSX Cmnd+Shif+U).

If you just want to see this in action on a live demo, you can see the JavaScript library version here with the Firefox 4 beta 3 or greater. You don't need to install any addon, is a stand-alone version of the code running on a demo page :)

Also, here you have a list of available demos to try the multitouch support coded by Felipe Gomes:

  • Image Crop
    Draw a rectangle to potentially "crop" an image with a pinch gesture
  • Image Resize
    Shrink and Enlarge images with pinch gestures. With two simultaneous pinches you can resize two different images
  • Touch Canvas
    Simple canvas that tracks your fingers
  • Tracking Divs
    Two divs keep tracking of the fingers you have on the screen
  • Fluids
    Fluid simulation following your fingers!
Filed under: English, GSoC, Jetpack No Comments
22Jul/10Off

First stop on the road to completion

Some time has passed from the first post I made, and the extension now is more "usable". We showcased both the Firefox Multitouch and the Simulator project in the Mozilla 2010 Summit's Science Fair with my mentor, Felipe Gomes, and the people who passed by our booth were very interested in both projects! The input and the comments from the assistants were great!

Protocol optimized

After some tinkering with the old protocol, Felipe and I thought it was over sized and a little repetitive to work with, so we put it on a diet. Now it's more compact and kind of easier to work with, I'll show you/

This would be a sample file written with the new version:

{
  "frames":[
     {
       "positions":[
            {"id":"1","x":300,"y":300}
        ],
       "events":[
           {"id":"1","type":"MozTouchDown"}
       ]
     },
     {
       "active_duration": 5
     },
     {
       "positions":[
           {"id":"1","x":400,"y":400}
       ],
       "events":[
          {"id":"1","type":"MozTouchRelease"}
       ]
     }
  ],
  "fps": 10
}

The new rules are even simpler:

  • frames
    A collection of Frame-Objects
  • Frame-Object
    An object that has two properties to define the status of each frame:

    • positions
      A collection of objects containing the finger ID that the position belongs and x and y position: {ID, X_POS, Y_POS}
    • events
      Collection of objects containing finger ID and Event Type. Event Types are to be designed, but inital ones are the same as the implementation:

      • MozTouchDown
      • MozTouchUp
      • MozTouchRelease
      • MozTouchMove
  • Frame-Object Types
    There are three Frame-Object types now:

    • Snapshot
      This is the type in where you define positions and events
    • Spacer Active
      A Frame-Object is of this kind when it's only property is "active-duration". This indicates that between two snapshots objects an animation should be done, and the duration is the value of "activ-duration"
    • Spacer Inactive
      This has the same structure as the active one, but instead the property is "idle-duration". This indicates that no transition should be calculated between two snapshots, it's a waiting time.
  • fps
    The framerate that will be used to play the file

Changes:

  • Frame-objects no longer have a fingers collection. This is now deduced from the positions IDs
  • Events now are the same as the ones implemented in firefox. This is to simplify naming, and probably they'll soon change to something more "human" and less "techy".
  • The Frame-Objects have 3 subtypes now: Snapshot, Spacer Active, Spacer Idle.

Demo Available

As I promised last time, the code is ready for some demoing!

As the multitouch part is not yet available on firefox latest builds you'll have to use a special build of firefox to try this stuff. Here you'll find a compiled version for your system:

  • Mac OSX (tested on 10.6, should also work on 10.5)
  • Windows
  • Linux (not here yet, still have to compile this)

Now that you have the correct build to test the extension is time to install it. I would strongly recommend you to create a new profile, it's a good practice when you're trying new stuff that may explode ;) .

You can grab here the extension compiled as an XPI, and here some good sutff: you won't need to restart firefox to try it out! As a side-effect of coding the extension with Jetpack, and having to use the latest firefox build for the multitouch part, we end up having the best setup ever: restartless addons enabled! To install the addon, just download it and drag-n-drop it on firefox.

But we need some demos to try the addon, so here you have a list of available demos to try multitouch coded by Felipe Gomes:

  • Image Crop
    Draw a rectangle to potentially "crop" an image with a pinch gesture
  • Image Resize
    Shrink and Enlarge images with pinch gestures. With two simultaneous pinches you can resize two different images
  • Marcio Drawing
    A demo that lets you draw with your fingers. Touching a color in the pallete, changes the drawing color.
  • Pong (not much usefull in for this addon)
    A simple implementation of the classic Pong game.
  • Touch Canvas
    Simple canvas that tracks your fingers
  • Tracking Divs
    Two divs keep tracking of the fingers you have on the screen
  • Fluids
    Fluid simulation following your fingers!

And here are some sample input files:

  • Sample 1: A simple pinch gesture.
  • Sample 2: Two simultaneous simple pinch gestures.
  • Sample 3: Cross-drawing (this is designed for the Marcio Drawing Demo)

Using the simulator is pretty simple, it just has three buttons:

The first one lets you load an input file (as the samples I'm providing) to be processed. The second one opens a kind of "console" so you can write a input file on the fly and then run it with the third button, as you can see here:

Where to go now

The next steps I think will be the harder ones. What is pending to be added is a way to simulate multitouch input with just one pointer. That means, how to make the extension itself write the input files instead of doing it by hand. I still have to come up with a UI for that, and any suggestion/idea is welcome. If you think you can collaborate on that stuff, don't hesitate to contact me on twitter or leaving a comment.

Feedback

I would really appreciate if some (or all!) of you try this extension and reports issues/enhancements (you can do it here), that would be priceless. Of course any thing you want to ask you can reach me in #jetpack on irc.mozilla.org,  I go by the name of "peregrino", or by leaving a comment here.

Filed under: English, GSoC, Jetpack No Comments
4Mar/10Off

Lima, Mozilla y Add-ons

Todavía recuerdo aquella tarde de octubre en Santiago cuando nos preguntábamos cuáles eran nuestros objetivos para el año que se venía. Mi objetivo ya lo tenía preparado desde hacía tiempo: Eventos para Desarrolladores.

Tenía muchas ganas de poder tener en Latinoamérica algún evento como los que tienen en Europa, o Estados Unidos, en donde el centro de la cuestión sea el código fuente. Un evento en el cual poder hablar en nuestra lengua natal, el querido Español, sobre temas en los que casi siempre hay que conversar en Inglés. Un evento en el cual conocer gente con intereses similares y hacer nuevas amistades. Un evento para desarrolladores.MAOW

Esa meta parecía tan distante... Hasta que a principio de este año, una tarde reviso el correo y veo una noticia que me alegró el resto del día. Una propuesta para realizar el primer mozilla addons workshop en Latinoamérica. Realmente no lo podía creer, era como un sueño hecho realidad. Y así comenzó la aventura, el sueño se había cumplido, ahora había que vivirlo!

Prácticamente ya tenía las valijas listas para salir hacia mi entrenamiento como Jetpack Ambassador en las oficinas de Mozilla en Mountain View (sobre lo que ya escribiré!), y ahora tenía una invitación para mi primer evento como Jetpack Ambassador. La emoción era enorme... y también lo era la responsabilidad. Está claro que la responsabilidad de asistir a un workshop no es ni remotamente parecida a la de dar el workshop, pero a veces hay que hacer pequeños sacrificios para lograr lo que se quiere. Como decía mi abuela: el que quiere celeste, que le cueste.

Así que luego de concluido mi entrenamiento en Mozilla, empecé a darle forma a las secciones que me correspondían en el MAOW de Lima. Decidí que lo mejor era primero dar una introducción a Jetpack, dado que probablemente nadie supiera siquiera de la existencia del mismo. Luego presentaría un taller, con cosas simples para que la audiencia no se perdiera tanto. Y por suerte resultó, y a los asistentes les entusiasmó.

La experiencia del taller fue magnífica, y como las sesiones de Jetpack vinieron después de las extensiones normales, los resultados fueron muy gratificantes. Ver cómo la gente se sorprendía con la simplicidad de Jetpack, y que pensaran que con algo así sí podrían crear una extensión, me pareció un gran éxito para la plataforma. Los asistentes por lo general habían tenido alguna experiencia programando páginas web, pero no todos eran gurús del cyberespacio. Justamente el publico al que Jetpack apunta!

Antes de finalizar el MOAW, hicimos una pequeña competencia a ver quién lograba modificar una extensión base para agregarle un poco de comportamiento, y así regalábamos algunos premios :) . De nuevo fue sorprendente que las primeras personas en lograrlo lo hayan hecho en menos de 10 minutos. ¡Entendían lo que estaban haciendo pese a que nunca habían programado una extensión! Eso es en mi opinión una excelente primera impresión.

Las personas que se acreditaron premios fueron las siguientes, en orden de llegada:

  1. Davis (@davis_laban)
  2. Cristian (@criso)

  3. Ulises (@ulisescab)

  4. Yannick (@ywarnier)

Estoy muy agradecido de todos los asistentes al taller, de sus críticas y comentarios que nos vienen súper útiles para los próximos MAOWs que seguramente realizaremos ;) . Ya he visto por ahí en Twitter que algunos están probando Jetpack, creo que no puedo estar más satisfecho y espero que algún día logren superar al maestro!

Antes de despedirme quiero agradecer a Percy Cabello, Daniel Yucra y Mozilla Perú por haber hecho realidad este evento. También a mi compañero Jorge Villalobos, que me acompañó en el taller dando la parte de Extensiones Tradicionales. Y a todos los demás encargados de que el taller saliera a la perfección y casi sin contratiempos!

Fotos tomadas por Percy Cabello, disponibles aquí
12Dec/09Off

Firebug y Jetpack, juntos otra vez

Ultimamente estuve jugando bastante con un nuevo proyecto de Mozilla Labs: Jetpack. Lo voy a describir brevemente para aquellos que no saben de qué se trata este maravillos nuevo proyecto, pero deberías revisar el sitio de Jetpack si querés aprender más acerca del mismo.

Si alguna vez te preguntaste cómo están hechos todos esos complementos de Firefox, probablemente hayas descubierto (quizás con alguna decepción) que no son tan fáciles de programar. Tenés que aprender un lenguaje llamado XUL para la UI, asimilar un montón de nuevos términos como Overlays, XPI, XPCom... Pero che, no estoy diciendo que todo esto es imposible de aprender (de hecho hay un montón de documentación y tutoriales disponibles), sino que simplemente hay que aprender algo nuevo.

Así que Mozilla pensó sobre esto por un tiempo, y salieron con una idea bastante piola: lo más probable es que vos ya conozcas JavaScript, CSS y HTML. Por qué deberías tener que aprender algo nuevo? Y así nació Jetpack, una nueva forma de programar complementos, en tan sólo un archivo y completamente programados en JavaScript, CSS y HTML.

Firebug y Jetpack

Y qué relación tiene Jetpack con Firebug? Bueno, bastante. Como dicen en el sitio de Jetpack, "para no reinventar la rueda" usaron Firebug para depurar y loguear. Hasta ahora todo perfecto: una manera simple para desarrollar complementos, un lindo depurador... qué más se podría pedir?
Quizás que ambos funcionen juntos ni bien los instalamos?

Como algunos se han dado cuenta, las últimas versiones de Firebug y de Jetpack no funcionan bien juntas de entrada. Esto es porque la versión actual de Jetpack (0.6.2) usa una vieja llamada a la API para comunicarse con Firebug, que cambió en la versión 1.4.3. Al parecer desarrollaron toda la interacción con Firebug usando Firebug 1.4.2, con lo cual nunca se enteraron del cambio en la API de Firebug. Pero a no desesperar! Hay una solución para esto, y es tan simple como cambiar una sóla palabra en una sóla linea de código.

Haciendo que ambos vuelvan a llevarse bien

Nota importante:
Al momento de escribir este artículo el bug abierto para este problema ya está en "Verified and Fixed", lo cual siginifica que el arreglo estará disponible en la próxima versión de Jetpack. Mientras tanto, vas a tener que hacer la siguiente modificación a mano para poder usar Jetpack con un Firebug 1.4.3 o posterior.

Primero que nada, vas a tener que ubicar tu perfil de Firefox. Esto depende de tu sistema, pero acá están algunas de las ubicaciones más comunes:

  • Linux:
    ~/.mozilla/firefox/<profile folder>
  • Mac OS X:
    ~/Library/Mozilla/Firefox/Profiles/<profile folder>
    Ó
    ~/Library/Application Support/Firefox/Profiles/<profile folder>
  • Windows XP:
    C:\Documents and Settings\<Windows login/user name>\Application Data\Mozilla\Firefox\Profiles\<profile folder>
  • Windows 7:
    C:\Users\<Windows login/user name>\AppData\Roaming\Mozilla\Firefox\Profiles\<profile folder>

Si estás usando Firefox 3.6, podés ir a la URL "about:support" y ahí hay un botón que te lleva a la carpeta con tu perfil.

Una vez encontrada la carpeta de tu perfil, vas a tener que ir a esta carpeta que se encuentra dentro del mismo:

extensions/jetpack@labs.mozilla.com/content/js/xul

y editar el siguiente archivo:

firebug-extension.js

Cambiando la línea 19 de:

Firebug.URLSelector.watchBrowser(browser);

A:

Firebug.Activation.watchBrowser(browser);

Guarda el archivo, reinicia Firefox, y voilà, ahora Firebug y Jetpack deberían estar trabajando juntos!

Probando si Firebug está funcionando

Si querés saber si Firebug está funcionando como lo esperado, copiá el siguiente código en la parte de "Develop" en Jetpack:

jetpack.future.import("menu");
jetpack.menu.context.page.add({
    label: "LoguearEsto!",
    command: function(){
        console.log("Firebug está Andando OK");
    }
});

Ahora apretá el botón "Try out this code", habilitá Firebug y actualizá la página. Si todo salio bien, ahora debería haber una nueva entrada en el menú de contexto de la página, llamada "LoguearEsto!". Si hacés click en la misma, y en la consola aparece el texto "Firebug está andando OK", entonces Firebug está andando correctamente.

11Dec/09Off

Firebug & Jetpack, make them work together

UPDATE: This article is outdated! This talks about the Jetpack Prototype, a project that has been phased out in favor of the Add-On SDK.

Lately I've been playing a lot with a new project from Mozilla Labs: Jetpack. I'll describe it briefly for those who don't know what this wonderful new project is, but you should check Jetpack's Site if you want to learn more about it. If you ever wondered how all those Firefox extensions are made, you probably discovered (maybe with some disappointment) that they're not that easy to code. You have to learn a language called XUL for the UI, assimilate a lot of new terms like Overlays, XPI, XPcom... But hey, I'm not telling this stuff is impossible to grasp (in fact, there's a lot of documentation and tutorials available), just that you have to learn something new. So Mozilla thought about that for a while, and came up with a pretty cool idea: you are most likely to allready know JavaScript, CSS and HTML. Why you should have to learn something new? And thus born Jetpack, a new way to code Add-Ons in just a single file and entirely coded in JavaScript, CSS and HTML.

Firebug and Jetpack

And what has Jetpack to do with Firebug? Well, pretty much. As stated on Jetpack's site, "not wanting to reinvent the wheel" they used Firebug for debugging and logging purposes. So for now everything's great: a simple way to develop add-ons, and a nice debugger... what else could I ask for? Maybe for them to work together out of the box? As some people has noticed, the latest versions of Firebug and Jetpack won't work together right after installing them. This is because the current version of Jetpack (0.6.2) uses an old API call to communicate with Firebug that changed in version 1.4.3. It seems that all the Firebug interaction was developed using Firebug 1.4.2, so they never noticed the change in the API. But don't panic! There is a way to fix this, and is as simple as changing a single word on a single file.

Making them play nice together again

Important Notice: As I write this article the bug opened for this issue is already Verified and Fixed, so that means that the fix will be on the next Jetpack release. Meanwhile, you'll have to do the following patch by hand to use Jetpack with Firebug 1.4.3 or later.

First of all, you have to locate your Firefox profile. This depends on your system, but this are some of the most common locations:

  • Linux: ~/.mozilla/firefox/<profile folder>
  • Mac OS X: ~/Library/Mozilla/Firefox/Profiles/<profile folder> OR ~/Library/Application Support/Firefox/Profiles/<profile folder>
  • Windows XP: C:\Documents and Settings\<Windows login/user name>\Application Data\Mozilla\Firefox\Profiles\<profile folder>
  • Windows 7: C:\Users\<Windows login/user name>\AppData\Roaming\Mozilla\Firefox\Profiles\<profile folder>

If you are using firefox 3.6, you can go to the address "about:support" and there's a link to your profile folder. After finding your profile folder, you'll have to go to the following folder inside it.

extensions/jetpack@labs.mozilla.com/content/js/xul

and edit this file:

firebug-extension.js

Changing the line 19 from:

Firebug.URLSelector.watchBrowser(browser);

To:

Firebug.Activation.watchBrowser(browser);

Save that file, restart Firefox, and voilà, Firebug and Jetpack are working together now!

Testing if Firebug is now working

If you want to test if Firebug is working as expected, then paste the following into the develop area of Jetpack:

jetpack.future.import("menu");
jetpack.menu.context.page.add({
    label: "LogThis!",
    command: function(){
        console.log("Firebug is Working OK");
    }
});

Now hit the "Try out this code" button, enable Firebug and refresh the page. If everything went right, you should have a new entry on the context menu of the webpage, called "LogThis!". If you click on that entry and the text "Firebug is Working OK" appears on the console, you have it working.

C:\Documents and Settings\<Windows login/user name>\Application Data\Mozilla\Firefox\Profiles\<profile folder>