Introducing AutoBlog

One of the first things I want to do always I publish some new project on GitHub is to provide a development diary / (b)log with the latest updates or feature additions but I have not found the proper tool yet. I’ve been told about Jekyll but it requires more effort than I’m willing to do (although it require very low effort). I want something quick and easy: with the minimum server or client support. Something to do with a simple text editor.

So I created AutoBlog. And I have all the documentation, setup, and feature list in an AutoBlog supported static site you can check for inspiration and example. Of course, this is only a beta and more features are coming but you know, step by step.

Seguir leyendo «Introducing AutoBlog»

Firefox OS: applications 101

Hi again!

The other day in TID I was told there is not much information about how to start a HTML5 application for Firefox OS and deploy it into the device. There is. Seriously. But I have to admit there is not a straight way to the topic and you could get lost in the middle of all the available information. So this is a try to provide a quick and basic Firefox OS application tutorial.

Step 0: set-up the environment

Firefox Nightly

Nightly is the latest version of Firefox. Always. Built every night from the source-code. You can download it from the Nightly’s official site.

Before open it, it is very important you close all sessions of Firefox.

Firefox OS Simulator

This is an extension to Firefox; grab it by clicking on «+ Add to Firefox» from the Firefox OS Simulator add-on page.

The device and drivers

If you are fortunate enough then you have a Firefox OS device. If not, you can purchase one from Geekphone’s store. You need its drivers as well and they depend on the device you have and the operating system of your PC.

Finally, in the device go to Settings > Information > More information > Developer and enable «Remote debugging».

Now you are ready to start  developing Firefox OS applications!

Step 1: the first app

Before starting, create a new folder. Name it as you want (i.e. myapp) and enter the folder. All your application files will go here.

Open your favorite text editor and create a new document named «index.html». Now enter the following HTML5 code and save it inside the folder you created before.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="pragma" content="no-cache" />
  </head>
  <body>
    <p>This is my first Firefox OS application.</p>
  </body>
</html>

If you are not used with HTML5, let’s take a quick review to the code:

  • Line 1 indicates the navigator we are using HTML5.
  • Line 2 is the beginning of the HTML5 document.
  • Line 3 indicates the beginning of the head section where metadata goes.
  • Line 4 is metadata saying the document is encoded in «UTF-8».
  • Line 5 is more metadata saying you don’t want Firefox OS to cache the content. This is very convenient while developing.
  • Line 6 indicates the end of the head section.
  • Line 7 indicates the beginning of the body section where content goes.
  • Line 8 is a paragraph with some text.
  • Line 9 indicates the end of the body section.
  • And line 10 indicates the end of the HTML5 document.

Step 2: the manifest

The index.html is one of the two things you need to make a Firefox OS application. Again, use your favorite text editor an create another file named «manifest.webapp», Put this text inside:

{
"name": "MyApp",
"description": "My first Firefox OS application",
"launch_path": "index.html"
}

This is a JSON file. Again, if you never read about this format before let’s review what is it saying:

  • Line 1 indicates the beginning of a JSON object. A JSON object is a list of pairs «key»: «value».
  • Line 2 is the key «name» which indicates the name of the application.
  • Line 3 contains the key «description» with the description of the application.
  • Line 4 has the key «launch_path» which says Firefox OS what file must be opened when launching the application.
  • Line 5 ends the JSON object.

Step 3: test your application!

Yes, you’ve read well, it’s time to test your application. Nothing more is needed. Now open Nightly and click on Tools menu, then go to Web Developer > Firefox OS Simulator.

Firefox OS Simulator dashboard
Firefox OS Simulator dashboard.

This will open the dashboard. Click on «Add directory» button and navigate to the folder you created in step 1. Select the manifest file and accept. This will launch the Firefox OS simulator allowing you to see your application as if it were running in a real device.

MyApp application in the dashboard.
MyApp application in the dashboard.

If you modify the application while the application is still running, go to «App» menu, then «Refresh» to reload the app.

Application running in the Simulator.
Application running in the Simulator.

Step 4: testing on the device!

If you have a device, connect it to your PC. If the drivers are installed properly you should see the phrase «Device connected» below the «Simulator» switch. Furthermore, your application entry will display a «Push» button.

Device has been recognized by the Firefox OS Simulator.
Device has been recognized by the Firefox OS Simulator.

Press the «Push» button and your application will be uploaded to your phone. The first time you upload an application, a prompt will be displayed on it. If you accept, the application will be installed and a status message will appear when finished.

Then you can go to your home screen and search for your application. Open it and see the results.

Note there is no such thing as Refresh in your real device. If you change the source files in your PC, you need to push your application again. Furthermore, you must close the application and reopen to see the changes.

Congratulations. You have written and run your first Firefox OS application.

Seguir leyendo «Firefox OS: applications 101»

μTask

Bea's kanban in English
Bea’s kanban in English

Os presento μTask, una pequeña aplicación para gestionar tareas usando un panel kanban en fase alpha. Últimamente me ronda mucho por la cabeza las aplicaciones con modelos representables en texto plano. Como todo.txt, por ejemplo.

μTask es un pequeño parser de una notación de mi invención para gestionar tareas, pensada para interacturar con los comandos estándar cortar y pegar.

Tenéis un ejemplo de una tarea aquí mismo:

To do:
  Task 153: LMDL fixes

Y una escueta lista de características:

  • Tareas con identificador, descripción y detalles
  • Dos espacios para definir tareas: uno para reflejar el estado del kanban y otro para clasificar y detallar las tareas
  • Clasificaciones por temas y colores
  • Expresa el progreso de una tarea y su fecha límite

Podéis encontrar más información así como un lugar donde dejar vuestros comentarios en la página del proyecto:

http://unoyunodiez.com/proyectos/mtask/

El tutorial en GitHub:

https://github.com/lodr/mtask/#%CE%BCtask

Respeta la especificación

Todo el mundo sabe que en general, los navegadores son muy tolerantes a errores en el marcado y por eso muchos programadores / diseñadores no prestan una adecuada atención a las estructuras HTML que producen. Os voy a poner un caso que me ha ocurrido hoy para no olvidar que aunque se toleren los fallos, siempre es mejor no cometerlos:

Teníamos esta estructura:

<button>
<span> Test </span>
</button>

En un momento dado, la expandíamos añadiendo cierto marcado al interior del botón:

<button>
<span>
<button><span>Test 1</span></button>
<button><span>Test 2</span></button>
<button><span>Test 3</span></button>
</span>
</button>

Pues bien, en Firefox, los botones internos jamás recibían ningún evento. ¿Por qué? Pues porque la especificación dice del contenido de un elemento button, lo siguiente:

Content model:
Phrasing content, but there must be no interactive content descendant.

Modelo del contenido:
Contenido en forma de sentencia, mas no debe haber ningún descendiente con contenido interactivo.

¿Quiere esto explícitamente decir que los eventos que reciba el primer button no se propagarán hacia los botones contenidos en él? No, o la menos yo no he encontrado esa negación explícita. Se trata sencillamente de un comportamiento indefinido y no se puede confiar en los comportamientos indefinidos. No hay duda de que son útiles para la optimización y en este caso, Firefox no propaga eventos de interacción dentro de un elemento que no debería tener contenido interactivo.

BOM o cómo arruinar el DOM

Esta tarde he pasado por una de las etapas de frustración más alarmantes de mi vida como diseñador web en mis ratos libres.

El problema es sencillo de explicar: resulta que yo disponía de este sencillo código:

<!DOCTYPE html >
<html>
    <head>
        <title>Title of the document</title>
        <style type="text/css">
        * { margin:0; padding:0; }
        </style>
    </head>

    <body>
        <p>The content of the document......</p>
    </body>
</html>

Este código HTML es un ejemplo de documento HTML5 válido. La sección estilo elimina todos los márgenes y rellenos de forma que el contenido debería aparecer pegado a la esquina superior izquierda de la página y de hecho, cuando probaba la página en mi ordenador de sobremesa, con Windows 7, así era; sin embargo, al usarlo en el servidor de pruebas con Linux, editando con vim, el párrafo de prueba aparecía desplazado una línea hacia abajo.

Este inexplicable comportamiento está relacionado con el modelo de objetos del documento (DOM). El DOM es una interfaz que presenta un documento HTML o XML como un árbol de objetos anidados. Herramientas como Firebug o Chrome permiten inspeccionar el DOM de la página web. Por alguna extraña razón (que he tardado una hora en descubrir), el DOM de la versión en Windows era correcta mientras que la versión en el servidor Linux no lo era: todo el contenido de la cabecera web (etiqueta <head>) aparecía insertado dentro del cuerpo (etiqueta <body>).

Al usar la  herramienta de validación HTML de la W3 con el documento del servidor, recibía la siguiente advertencia:

Byte-Order Mark found in UTF-8 File.

The Unicode Byte-Order Mark (BOM) in UTF-8 encoded files is known to cause problems for some text editors and older browsers. You may want to consider avoiding its use until it is better supported.

Que viene a indicar que el documento cargado incluye la marca de orden de bytes o BOM y que esta podría causar problemas con algunos editores de texto o navegadores viejos. Bien, tengo Firefox 4. No pensé en él como en un navegador viejo. Además también probé con Chrome y obtenía los mismos resultados. El BOM es una marca que indica cuáles son los bytes más significativos de un carácter codificado en UTF-8.

¿Qué quiere decir esto? Pues que, por ejemplo, la «ñ» tiene el símbolo UTF (en hexadecimal) ‘F1′ pero como UTF puede codificarse en 8, 16 o 32bits, podríamos encontrarlo también como ’00 F1′ (16bits) o ’00 00 00 F1’ (32bits). Y lo que es peor, podemos encontrarnos estas dos últimas codificaciones al revés: ‘F1 00’ y ‘F1 00 00 00’. Para evitar confusiones existe el BOM que indica si debemos leer los caracteres de izquierda a derecha o de derecha a izquierda.

En el caso del BOM para UTF de 8 bits, la existencia de la marca o su contenido debería ser irrelevante (sólo es 1byte, no importa el orden) pero no es así. Y este era el problema: la existencia del BOM confundía a Firefox y a Chrome (aun presiento que a quien confundía realmente era al servidor Apache pero no estoy seguro), lo que llevaba a malinterpretar los símbolos del documento, errar las etiquetas y corromper el DOM lo que a su vez arruinaba el aspecto de la página.

En fin, un brainfuck considerable. Así que ya sabéis:

contenido para web en UTF-8, sin BOM

Desde vim, podeis deshabilitar el BOM introduciendo los comandos:

:set nobomb
:w

Fácil cuando lo sabes, xP.

EDIT: He encontrado informaicón muy útil y en Español en la W3 acerca de la marca de BOM