mozilla

Revisão 302099 de Arquitetura do Firefox OS

  • Slug da revisão: Mozilla/Firefox_OS/Architecture
  • Título da revisão: Firefox OS architecture
  • ID da revisão: 302099
  • Criado:
  • Criador: TelaSocial
  • É a revisão atual? Não
  • Comentar

Conteúdo da revisão

{{draft()}}

Este artigo traz uma visão geral da arquitetura da plataforma Firefox OS, introduzindo conceitos chaves e explicações básicas de como os componentes se interagem. Para explicações mais avançadas veja a seção {{anch("See also")}}.

Nota: Lembre-se que o Firefox OS ainda é um produto tipo pre-release, ou seja, a arquitetura não é final e está sujeita a mudanças. 

Terminologia

Existem alguns termos que você precisa saber para entender melhor o Firefox OS. 

B2G
Versão curta do Boot to Gecko.
Boot to Gecko
codename ou apelido do projeto Firefox OS que era o termo anteriormente utilizado antes do nome oficial, Firefox OS, ser lançado. É comum ver o termo B2G ser utilizado em casos que não são específicos ao Firefox OS, por exemplo quando desenvolvedores estão interessados na infra estrutura geral e usos que não estão atrelados com a agenda ou prioridades do Firefox OS. 
Gaia
É a interface visual do Firefox OS, que apresenta a experiência do sistema ao usuário. A camada Gaia contém várias aplicações padrão como lock screen, home screen, e várias aplicações que são esperadas de um celular tipo smartphone. O Gaia é completamente implementado com padrões web como HTML, CSS, JavaScript, dentre outros. As interfaces entre a camada web e os recursos do sistema operacional são feitas via APIs web — algumas abertas e outras que estão em desenvolvimento na camada Gecko. O Gaia oferece maneiras para a instalação de aplicações de terceiros. 
Gecko
Este é o runtime web específico para as aplicações do Firefox OS. O Gecko oferece uma infra estrutura de padrões web como HTML5, CSS, SVG, WebGL, JavaScript, dentre outros. Ele também oferece recursos do sistema como device API assim permitindo que aplicações web possam acessar serviços do disposivo móvel, como por exemplo o GPS e câmera. O Gecko também carrega várias funcionalidades básicas que são importantes para que aplicações web possam rodar corretamente, como a camada de rede e segurança, a camada de gráficos, o motor máquina virtual JavaScript, o engine de layout, dentre outros. 
Gonk
O Gonk é a camada mais baixa do sistema operacional e consiste em um kernel Linux e o HAL (hardware abstraction layer). O kernel e várias das bibliotecas são ligados a projetos de código aberto conhecidos: Linux, libusb, bluez, dentre outros. Algumas outras partes do HAL são compartilhadas com o projeto Android: GPS, camera, dentre outros. Pode-se dizer que o Gonk é uma distribuição Linux simplificada. O Gonk é uma plataforma alvo (porting target) do Gecko, ou seja, existe o target Gonk assim como existem plataformas de saída para Mac OS X, Windows, e Android. Uma vez que o projeto do Firefox OS tem controle sobre o Gonk, é possível que interfaces baixo nível sejam expostas ao Gecko, por exemplo, o acesso direto para a pilha de serviços de telefonia e também o acesso direto ao frame buffer gráfico. Estas características são novas e não ocorrem no caso de outros sistemas operacionais. 

O processo de inicialização bootstrapping

Quando um dispositivo com o Firefox OS é ligado, a execução dá inicio no bootloader primário. A partir deste ponto é carregado o sistema operacional da forma tradicional. From there, the process of loading the main operating system proceeds in the typical way; a succession of increasingly higher-level bootloaders bootstrap the next loader in the chain. At the end of the process, execution is handed off to the Linux kernel.

There are a few points worth noting about the boot process:

  • The bootloaders usually display the first splash screen seen by the user during device startup; this is typically a vendor logo.
  • The bootloaders implement flashing an image to the device. Different devices use different protocols; most phones use the fastboot protocol, but the Samsung Galaxy S II uses the odin protocol.
  • By the end of the bootstrapping process, the modem image is usually loaded and running on the modem processor. How this happens is highly device-specific and may be proprietary.

The Linux kernel

The Linux kernel(s) used by Gonk is very similar to the upstream Linux from which it's derived. There are a few changes made by the Android Open Source Project that have not yet been upstreamed. In addition, vendors sometimes modify the kernel and upstream those changes on their own schedule. In general, though, the Linux kernel is close to stock.

The startup process for Linux is well-documented elsewhere on the Internet, so this article won't cover that. At the end of the process, a userspace init process is launched, as it is in most UNIX-like operating systems. At this point in execution, the only mounted "disk" is a RAM disk. The RAM disk is built during the Firefox OS build process, and contains critical utilities, such as init, as well as other startup scripts and loadable kernel modules.

Once the init process is launched, the Linux kernel handles system calls from userspace, and interrupts and the like from hardware devices. Many hardware features are exposed to userspace through sysfs. For example, here's a code snippet that reads the battery state in Gecko:

FILE *capacityFile = fopen("/sys/class/power_supply/battery/capacity", "r");
double capacity = dom::battery::kDefaultLevel * 100;
if (capacityFile) {
  fscanf(capacityFile, "%lf", &capacity);
  fclose(capacityFile);
}

The init process

The init process in Gonk handles mounting the required file systems and spawns system services. After that, it stays around to serve as a process manager. This is quite similar to init on other UNIX-like operating systems. It interprets scripts (that is, the init*.rc files) that consist of commands describing what should be done to start various services. The Firefox OS init.rc is typically the stock Android init.rc for that device patched to include the things required to kick-start Firefox OS, and varies from device to device.

One key task the init process handles is starting up the b2g process; this is the core of the Firefox OS operating system.

The code in init.rc that starts this up looks like this:

service b2g /system/bin/b2g.sh
    class main
    onrestart restart media

You can also take a look at the file init.b2g.rc, which is the code appended to the Android init.rc to start up the b2g process.

Note: Exactly how much init.rc differs from the Android version varies from device to device; sometimes, init.b2g.rc is simply appended, and sometimes the patches are more significant.

The userspace process architecture

Now it's useful to take a high-level look at how the various components of Firefox OS fit together and interact with one another. This diagram shows the primary userspace processes in Firefox OS.

Userspace diagram

Note: Keep in mind that since Firefox OS is under active development, this diagram is subject to change, and may not be entirely accurate.

The b2g process is the primary system process. It runs with high privileges; it has access to most hardware devices. b2g communicates with the modem, draws to the display framebuffer, and talks to GPS, cameras, and other hardware features. Internally, b2g runs the Gecko layer (implemented by libxul.so). See {{anch("Gecko")}} for details on how the Gecko layer works, and how b2g communicates with it.

b2g

The b2g process may, in turn, spawn a number of low-rights content processes. These processes are where web applications and other web content are loaded. These processes communicate with the main Gecko server process through IPDL, a message-passing system.

rild

The rild process is the interface to the modem processor. rild is the daemon that implements the Radio Interface Layer (RIL). It's a proprietary piece of code that's implemented by the hardware vendor to talk to their modem hardware. rild makes it possible for client code to connect to a UNIX-domain socket to which it binds. It's started up by code like this in the init script:

service ril-daemon /system/bin/rild
    socket rild stream 660 root radio

rilproxy

In Firefox OS, the rild client is the rilproxy process. This acts as a dumb forwarding proxy between rild and b2g. This proxy is needed is an implementation detail; suffice it to say, it is indeed necessary. The rilproxy code can be found on GitHub.

mediaserver

The mediaserver process controls audio and video playback. Gecko talks to it through an Android Remote Procedure Call (RPC) mechanism. Some of the media that Gecko can play (OGG Vorbis audio, OGG Theora video, and WebM video) are decoded by Gecko and sent directly to the mediaserver process. Other media files are decoded by libstagefright, which is capable of accessing proprietary codecs and hardware encoders.

Note: The mediaserver process is a "temporary" component of Firefox OS; it's there to aid in our initial development work, but is expected to go away eventually. This will most likely not happen until Firefox OS 2.0 at the earliest, however.

netd

The netd process is used to configure network interfaces.

wpa_supplicant

The wpa_supplicant process is the standard UNIX-style daemon that handles connectivity with WiFi access points.

dbus-daemon

The dbus-daemon implements D-Bus, a message bus system that Firefox OS uses for Bluetooth communication.

Gecko

Gecko, as previously mentioned, is the implementation of web standards (HTML, CSS, and JavaScript) that is used to implement everything the user sees on Firefox OS.

Processing input events

Most action inside Gecko is triggered by user actions. These actions are represented by input events (such as button presses, touches to a touch screen device, and so forth). These events enter Gecko through the {{source("widget/gonk/nsAppShell.cpp", "Gonk implementation")}} of {{interface("nsIAppShell")}}, a Gecko interface that is used to represent the primary entrance points for a Gecko application; that is, the input device driver calls methods on the nsAppShell object that represents the Gecko subsystem in order to send events to the user interface.

For example:

void GeckoInputDispatcher::notifyKey(nsecs_t eventTime,
                                     int32_t deviceId,
                                     int32_t source,
                                     uint32_t policyFlags,
                                     int32_t action,
                                     int32_t flags,
                                     int32_t keyCode,
                                     int32_t scanCode,
                                     int32_t metaState,
                                     nsecs_t downTime) {
  UserInputData data;
  data.timeMs = nanosecsToMillisecs(eventTime);
  data.type = UserInputData::KEY_DATA;
  data.action = action;
  data.flags = flags;
  data.metaState = metaState;
  data.key.keyCode = keyCode;
  data.key.scanCode = scanCode;
  {
    MutexAutoLock lock(mQueueLock);
    mEventQueue.push(data);
  }
  gAppShell->NotifyNativeEvent();
}

These events come from the standard Linux input_event system. Firefox OS uses a {{source("widget/gonk/libui/InputReader.cpp", "light abstraction layer")}} over that; this provides some nice features like event filtering. You can see the code that creates input events in the EventHub::getEvents() method in {{source("widget/gonk/libui/EventHub.cpp", "EventHub.cpp")}}.

Once the events are received by Gecko, they're dispatched into the DOM by {{source("widget/gonk/nsAppShell.cpp", "nsAppShell")}}:

static nsEventStatus sendKeyEventWithMsg(uint32_t keyCode,
                                         uint32_t msg,
                                         uint64_t timeMs,
                                         uint32_t flags) {
    nsKeyEvent event(true, msg, NULL);
    event.keyCode = keyCode;
    event.location = nsIDOMKeyEvent::DOM_KEY_LOCATION_MOBILE;
    event.time = timeMs;
    event.flags |= flags;
    return nsWindow::DispatchInputEvent(event);
}

After that, the events are either consumed by Gecko itself or are dispatched to Web applications as DOM events for further processing.

Graphics

At the very lowest level, Gecko uses OpenGL ES 2.0 to draw to an GL context that wraps the hardware frame buffers. This is done in the Gonk implementation of {{source("widget/gonk/nsWindow.cpp", "nsWindow")}}.

Fonte da revisão

<p>{{draft()}}</p>
<p>Este artigo traz uma visão geral da arquitetura da plataforma Firefox OS, introduzindo conceitos chaves e explicações básicas de como os componentes se interagem. Para explicações mais avançadas veja a seção {{anch("See also")}}.</p>
<div class="note">
  <p><strong>Nota:</strong>&nbsp;Lembre-se que o Firefox OS ainda é um produto tipo <em>pre-release</em>, ou seja, a arquitetura não é final e está sujeita a mudanças.&nbsp;</p>
</div>
<h2 id="Terminologia">Terminologia</h2>
<p>Existem alguns termos que você precisa saber para entender melhor o Firefox OS.&nbsp;</p>
<dl>
  <dt>
    B2G</dt>
  <dd>
    Versão curta do <em>Boot to Gecko</em>.</dd>
  <dt>
    Boot to Gecko</dt>
  <dd>
    O&nbsp;<em>codename</em> ou apelido do projeto Firefox OS que era o termo anteriormente utilizado antes do nome oficial, Firefox OS, ser lançado. É comum ver o termo B2G ser utilizado em casos que não são específicos ao Firefox OS, por exemplo quando desenvolvedores estão interessados na infra estrutura geral e usos que não estão atrelados com a agenda ou prioridades do Firefox OS.&nbsp;</dd>
  <dt>
    <a href="/en-US/docs/Mozilla/Firefox_OS/Gaia" title="/en-US/docs/Mozilla/Firefox_OS/Gaia">Gaia</a></dt>
  <dd>
    É a interface visual do Firefox OS, que apresenta a experiência do sistema ao usuário. A camada Gaia contém várias aplicações padrão como <em>lock screen</em>, <em>home screen</em>, e várias aplicações que são esperadas de um celular tipo <em>smartphone</em>. O&nbsp;Gaia é completamente implementado com padrões web como HTML, CSS, JavaScript, dentre outros. As interfaces entre a camada web e os recursos do sistema operacional são feitas via APIs web — algumas abertas e outras que estão em desenvolvimento na camada Gecko. O Gaia oferece maneiras para a instalação de aplicações de terceiros.&nbsp;</dd>
  <dt>
    <a href="/en-US/docs/Gecko" title="/en-US/docs/Accessibility/AT-APIs/Gecko">Gecko</a></dt>
  <dd>
    Este é o <em>runtime</em> web específico para as aplicações do Firefox OS. O Gecko oferece uma infra estrutura de padrões web como HTML5, CSS, SVG, WebGL, JavaScript, dentre outros. Ele também oferece recursos do sistema como <em>device API&nbsp;</em>assim permitindo que aplicações web possam acessar serviços do disposivo móvel, como por exemplo o GPS e câmera. O Gecko também carrega várias funcionalidades básicas que são importantes para que aplicações web possam rodar corretamente, como a camada de rede e segurança, a camada de gráficos, o motor máquina virtual JavaScript, o <em>engine&nbsp;</em>de layout, dentre outros.&nbsp;</dd>
  <dt>
    <a href="/en-US/docs/Mozilla/Firefox_OS/Gonk" title="/en-US/docs/Mozilla/Firefox_OS/Gonk">Gonk</a></dt>
  <dd>
    O Gonk é a camada mais baixa do sistema operacional e consiste em um kernel Linux e o HAL (<em>hardware abstraction layer). </em>O kernel e várias das bibliotecas são ligados a projetos de código aberto conhecidos:&nbsp;Linux, libusb, bluez, dentre outros. Algumas outras partes do HAL são compartilhadas com o projeto Android: GPS, camera, dentre outros. Pode-se dizer que o Gonk é uma distribuição Linux simplificada. O Gonk é uma plataforma alvo (<em><strong>porting target</strong></em>)&nbsp;do Gecko, ou seja, existe o <em>target&nbsp;</em>Gonk assim como existem plataformas de saída para Mac OS X, Windows, e Android. Uma vez que o projeto do Firefox OS tem controle sobre o Gonk, é possível que interfaces baixo nível sejam expostas ao Gecko, por exemplo, o acesso direto para a pilha de serviços de telefonia e também o acesso direto ao <em>frame buffer&nbsp;</em>gráfico. Estas características são novas e não ocorrem no caso de outros sistemas operacionais.&nbsp;</dd>
</dl>
<h2 id="The_bootstrapping_process">O processo de inicialização <em>bootstrapping</em></h2>
<p>Quando um dispositivo com o Firefox OS é ligado, a execução dá inicio no <em>bootloader</em> primário. A partir deste ponto é carregado o sistema operacional da forma tradicional. From there, the process of loading the main operating system proceeds in the typical way; a succession of increasingly higher-level bootloaders bootstrap the next loader in the chain. At the end of the process, execution is handed off to the Linux kernel.</p>
<p>There are a few points worth noting about the boot process:</p>
<ul>
  <li>The bootloaders usually display the first splash screen seen by the user during device startup; this is typically a vendor logo.</li>
  <li>The bootloaders implement flashing an image to the device. Different devices use different protocols; most phones use the <a href="http://android-dls.com/wiki/index.php?title=Fastboot" title="http://android-dls.com/wiki/index.php?title=Fastboot">fastboot protocol</a>, but the Samsung Galaxy S II uses the odin protocol.</li>
  <li>By the end of the bootstrapping process, the modem image is usually loaded and running on the modem processor. How this happens is highly device-specific and may be proprietary.</li>
</ul>
<h2 id="The_Linux_kernel">The Linux kernel</h2>
<p>The Linux kernel(s) used by Gonk is very similar to the upstream Linux from which it's derived. There are a few changes made by the <a href="http://source.android.com/" title="http://source.android.com/">Android Open Source Project</a> that have not yet been upstreamed. In addition, vendors sometimes modify the kernel and upstream those changes on their own schedule. In general, though, the Linux kernel is close to stock.</p>
<p>The <a href="http://en.wikipedia.org/wiki/Linux_startup_process" title="http://en.wikipedia.org/wiki/Linux_startup_process">startup process for Linux</a> is well-documented elsewhere on the Internet, so this article won't cover that. At the end of the process, a userspace <code>init</code> process is launched, as it is in most UNIX-like operating systems. At this point in execution, the only mounted "disk" is a RAM disk. The RAM disk is built during the Firefox OS build process, and contains critical utilities, such as <code>init</code>, as well as other startup scripts and loadable kernel modules.</p>
<p>Once the <code>init</code> process is launched, the Linux kernel handles system calls from userspace, and interrupts and the like from hardware devices. Many hardware features are exposed to userspace through <a href="http://en.wikipedia.org/wiki/Sysfs" title="http://en.wikipedia.org/wiki/Sysfs"><code>sysfs</code></a>. For example, here's a <a href="https://github.com/cgjones/mozilla-central/blob/master/hal/gonk/GonkHal.cpp#L277" title="https://github.com/cgjones/mozilla-central/blob/master/hal/gonk/GonkHal.cpp#L277">code snippet</a> that reads the battery state in Gecko:</p>
<pre>
FILE *capacityFile = fopen("/sys/class/power_supply/battery/capacity", "r");
double capacity = dom::battery::kDefaultLevel * 100;
if (capacityFile) {
  fscanf(capacityFile, "%lf", &amp;capacity);
  fclose(capacityFile);
}</pre>
<h2 id="The_init_process">The init process</h2>
<p>The <code>init</code> process in Gonk handles mounting the required file systems and spawns system services. After that, it stays around to serve as a process manager. This is quite similar to init on other UNIX-like operating systems. It interprets scripts (that is, the <code>init*.rc</code> files) that consist of commands describing what should be done to start various services. The Firefox OS <code>init.rc</code> is typically the stock Android <code>init.rc</code> for that device patched to include the things required to kick-start Firefox OS, and varies from device to device.</p>
<p>One key task the <code>init</code> process handles is starting up the <code>b2g</code> process; this is the core of the Firefox OS operating system.</p>
<p>The code in <code>init.rc</code> that starts this up looks like this:</p>
<pre>
service b2g /system/bin/b2g.sh
&nbsp;&nbsp;&nbsp; class main
&nbsp;&nbsp;&nbsp; onrestart restart media</pre>
<p>You can also take a look at the file <a href="https://github.com/mozilla-b2g/gonk-misc/blob/master/init.b2g.rc" title="https://github.com/mozilla-b2g/gonk-misc/blob/master/init.b2g.rc"><code>init.b2g.rc</code></a>, which is the code appended to the Android init.rc to start up the b2g process.</p>
<div class="note">
  <p><strong>Note:</strong> Exactly how much <code>init.rc</code> differs from the Android version varies from device to device; sometimes, <code>init.b2g.rc</code> is simply appended, and sometimes the patches are more significant.</p>
</div>
<h2 id="The_userspace_process_architecture">The userspace process architecture</h2>
<p>Now it's useful to take a high-level look at how the various components of Firefox OS fit together and interact with one another. This diagram shows the primary userspace processes in Firefox OS.</p>
<p><a href="/files/3849/B2G userspace architecture.svg"><img alt="Userspace diagram" src="/files/3849/B2G%20userspace%20architecture.svg" style="width: 520px; height: 491px; float: right; position: relative; z-index: 12; " /></a></p>
<div class="note">
  <p><strong>Note:</strong> Keep in mind that since Firefox OS is under active development, this diagram is subject to change, and may not be entirely accurate.</p>
</div>
<p>The <code>b2g</code> process is the primary system process. It runs with high privileges; it has access to most hardware devices. <code>b2g</code> communicates with the modem, draws to the display framebuffer, and talks to GPS, cameras, and other hardware features. Internally, <code>b2g</code> runs the Gecko layer (implemented by <code>libxul.so</code>). See {{anch("Gecko")}} for details on how the Gecko layer works, and how <code>b2g</code> communicates with it.</p>
<h3 id="b2g">b2g</h3>
<p>The <code>b2g</code> process may, in turn, spawn a number of low-rights <strong>content processes</strong>. These processes are where web applications and other web content are loaded. These processes communicate with the main Gecko server process through <a href="/en-US/docs/IPDL" title="/en-US/docs/IPDL">IPDL</a>, a message-passing system.</p>
<h3 id="rild">rild</h3>
<p>The <code>rild</code> process is the interface to the modem processor. <code>rild</code> is the daemon that implements the <strong>Radio Interface Layer</strong> (RIL). It's a proprietary piece of code that's implemented by the hardware vendor to talk to their modem hardware. <code>rild</code> makes it possible for client code to connect to a UNIX-domain socket to which it binds. It's started up by code like this in the <code>init</code> script:</p>
<pre>
service ril-daemon /system/bin/rild
&nbsp;&nbsp;&nbsp; socket rild stream 660 root radio</pre>
<h3 id="rilproxy">rilproxy</h3>
<p>In Firefox OS, the <code>rild</code> client is the <code>rilproxy</code> process. This acts as a dumb forwarding proxy between <code>rild</code> and <code>b2g</code>. This proxy is needed is an implementation detail; suffice it to say, it is indeed necessary. The <a href="https://github.com/mozilla-b2g/rilproxy" title="https://github.com/mozilla-b2g/rilproxy"><code>rilproxy</code> code can be found on GitHub</a>.</p>
<h3 id="mediaserver">mediaserver</h3>
<p>The <a href="https://github.com/android/platform_frameworks_base/tree/ics-mr0-release/media/libmediaplayerservice" title="https://github.com/android/platform_frameworks_base/tree/ics-mr0-release/media/libmediaplayerservice"><code>mediaserver</code> process</a> controls audio and video playback. Gecko talks to it through an Android Remote Procedure Call (RPC) mechanism. Some of the media that Gecko can play (OGG Vorbis audio, OGG Theora video, and <a href="http://www.webmproject.org/about/" title="http://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;ved=0CDUQFjAA&amp;url=http%3A%2F%2Fwww.webmproject.org%2F&amp;ei=8Q84UOnoMoHH6wHZ44DwBA&amp;usg=AFQjCNHK9j6wyhUful5RmKCpU6b8GDfpYQ&amp;sig2=tCl8VxL3mCvrH86EyOwO_A">WebM</a> video) are decoded by Gecko and sent directly to the <code>mediaserver</code> process. Other media files are decoded by <code>libstagefright</code>, which is capable of accessing proprietary codecs and hardware encoders.</p>
<div class="note">
  <p><strong>Note:</strong> The <code>mediaserver</code> process is a "temporary" component of Firefox OS; it's there to aid in our initial development work, but is expected to go away eventually. This will most likely not happen until Firefox OS 2.0 at the earliest, however.</p>
</div>
<h3 id="netd">netd</h3>
<p>The <code>netd</code> process is used to configure network interfaces.</p>
<h3 id="wpa_supplicant">wpa_supplicant</h3>
<p>The <code>wpa_supplicant</code> process is the standard UNIX-style daemon that handles connectivity with WiFi access points.</p>
<h3 id="dbus-daemon">dbus-daemon</h3>
<p>The dbus-daemon implements <a href="http://www.freedesktop.org/wiki/Software/dbus" title="http://www.freedesktop.org/wiki/Software/dbus">D-Bus</a>, a message bus system that Firefox OS uses for Bluetooth communication.</p>
<h2 id="Gecko">Gecko</h2>
<p><a href="/en-US/docs/Gecko" title="/en-US/docs/Gecko">Gecko</a>, as previously mentioned, is the implementation of web standards (<a href="/en-US/docs/HTML" title="/en-US/docs/HTML">HTML</a>, <a href="/en-US/docs/CSS" title="/en-US/docs/CSS">CSS</a>, and <a href="/en-US/docs/JavaScript" title="/en-US/docs/JavaScript">JavaScript</a>) that is used to implement everything the user sees on Firefox OS.</p>
<h3 id="Processing_input_events">Processing input events</h3>
<p>Most action inside Gecko is triggered by user actions. These actions are represented by input events (such as button presses, touches to a touch screen device, and so forth). These events enter Gecko through the {{source("widget/gonk/nsAppShell.cpp", "Gonk implementation")}} of {{interface("nsIAppShell")}}, a Gecko interface that is used to represent the primary entrance points for a Gecko application; that is, the input device driver calls methods on the <code>nsAppShell</code> object that represents the Gecko subsystem in order to send events to the user interface.</p>
<p>For example:</p>
<pre>
void GeckoInputDispatcher::notifyKey(nsecs_t eventTime,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int32_t deviceId,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int32_t source,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; uint32_t policyFlags,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int32_t action,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int32_t flags,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int32_t keyCode,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int32_t scanCode,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int32_t metaState,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; nsecs_t downTime) {
&nbsp; UserInputData data;
&nbsp; data.timeMs = nanosecsToMillisecs(eventTime);
&nbsp; data.type = UserInputData::KEY_DATA;
&nbsp; data.action = action;
&nbsp; data.flags = flags;
&nbsp; data.metaState = metaState;
&nbsp; data.key.keyCode = keyCode;
&nbsp; data.key.scanCode = scanCode;
&nbsp; {
&nbsp;&nbsp;&nbsp; MutexAutoLock lock(mQueueLock);
&nbsp;&nbsp;&nbsp; mEventQueue.push(data);
&nbsp; }
&nbsp; gAppShell-&gt;NotifyNativeEvent();
}</pre>
<p>These events come from the standard Linux <code>input_event</code> system. Firefox OS uses a {{source("widget/gonk/libui/InputReader.cpp", "light abstraction layer")}} over that; this provides some nice features like event filtering. You can see the code that creates input events in the <code>EventHub::getEvents()</code> method in <code>{{source("widget/gonk/libui/EventHub.cpp", "EventHub.cpp")}}</code>.</p>
<p>Once the events are received by Gecko, they're dispatched into the DOM by <code>{{source("widget/gonk/nsAppShell.cpp", "nsAppShell")}}</code>:</p>
<pre>
static nsEventStatus sendKeyEventWithMsg(uint32_t keyCode,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; uint32_t msg,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; uint64_t timeMs,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; uint32_t flags) {
&nbsp;&nbsp;&nbsp; nsKeyEvent event(true, msg, NULL);
&nbsp;&nbsp;&nbsp; event.keyCode = keyCode;
&nbsp;&nbsp;&nbsp; event.location = nsIDOMKeyEvent::DOM_KEY_LOCATION_MOBILE;
&nbsp;&nbsp;&nbsp; event.time = timeMs;
&nbsp;&nbsp;&nbsp; event.flags |= flags;
&nbsp;&nbsp;&nbsp; return nsWindow::DispatchInputEvent(event);
}
</pre>
<p>After that, the events are either consumed by Gecko itself or are dispatched to Web applications as <a href="/en-US/docs/DOM_Client_Object_Cross-Reference/DOM_Events" title="/en-US/docs/DOM_Client_Object_Cross-Reference/DOM_Events">DOM events</a> for further processing.</p>
<h3 id="Graphics">Graphics</h3>
<p>At the very lowest level, Gecko uses <a href="http://www.khronos.org/opengles/2_X/" title="http://www.khronos.org/opengles/2_X/">OpenGL ES 2.0</a> to draw to an GL context that wraps the hardware frame buffers. This is done in the Gonk implementation of {{source("widget/gonk/nsWindow.cpp", "nsWindow")}}.</p>
Reverter para esta revisão