Saltar al contenido principal

Julio 2016: Nuevas Apps y Encuentros

· 2 lectura mínima

We're starting a monthly roundup to highlight activity in the Electron community. Each roundup will feature things like new apps, upcoming meetups, tools, videos, etc.


This site is updated with new apps and meetups through pull requests from the community. Puede ver el repositorio para recibir notificaciones de cosas nuevas o si no está interesado en todos los cambios del sitio suscríbete al feed RSS del blog.

Si has hecho una aplicación Electron u organizar una reunión, haz un pull request para añadirlo al sitio y hará el siguiente resumen.

Nuevas aplicaciones

DemioA Webinar platform built for inbound sales and marketing
ElectorrentA remote client app for uTorrent server
PhoneGapThe open source framework that gets you building amazing mobile apps using web technology
WordMarkA lightweight blog publishing editor for Markdown writers
UbAuthApp to help developers create access tokens for Uber applications with OAuth 2.0
HyperTermHTML/JS/CSS terminal
MarpMarkdown presentation writer
Glyphr StudioA free, web based font designer, focusing on font design for hobbyists
BitCryptA simple file encryption application for Windows Encrypt your bits
TrymBeautiful small app for macOS to help you view, optimize and convert SVG icons
BookerText editor with the power of Markdown
PhonePresenterThe smartest presentation clicker
YoutThe new way to watch your playlists from YouTube on desktop

New Meetups

Electron Open Source Desktop FrameworkLondon, UK

Electron Internals: Integración de bucle de mensaje

· 3 lectura mínima

This is the first post of a series that explains the internals of Electron. This post introduces how Node's event loop is integrated with Chromium in Electron.


Ha habido muchos intentos de usar Node para programación GUI, como node-gui para enlaces GTK+ y node-qt para enlaces QT. But none of them work in production because GUI toolkits have their own message loops while Node uses libuv for its own event loop, and the main thread can only run one loop at the same time. So the common trick to run GUI message loop in Node is to pump the message loop in a timer with very small interval, which makes GUI interface response slow and occupies lots of CPU resources.

During the development of Electron we met the same problem, though in a reversed way: we had to integrate Node's event loop into Chromium's message loop.

The main process and renderer process

Before we dive into the details of message loop integration, I'll first explain the multi-process architecture of Chromium.

En Electron hay dos tipos de procesos: el proceso principal y el proceso de renderizador (esto en realidad es extremadamente simplificado, para una vista completa por favor vea Archivación multiproceso). The main process is responsible for GUI work like creating windows, while the renderer process only deals with running and rendering web pages.

Electron allows using JavaScript to control both the main process and renderer process, which means we have to integrate Node into both processes.

Replacing Chromium's message loop with libuv

My first try was reimplementing Chromium's message loop with libuv.

It was easy for the renderer process, since its message loop only listened to file descriptors and timers, and I only needed to implement the interface with libuv.

However it was significantly more difficult for the main process. Each platform has its own kind of GUI message loops. macOS Chromium uses NSRunLoop, whereas Linux uses glib. I tried lots of hacks to extract the underlying file descriptors out of the native GUI message loops, and then fed them to libuv for iteration, but I still met edge cases that did not work.

So finally I added a timer to poll the GUI message loop in a small interval. As a result the process took a constant CPU usage, and certain operations had long delays.

Polling Node's event loop in a separate thread

As libuv matured, it was then possible to take another approach.

The concept of backend fd was introduced into libuv, which is a file descriptor (or handle) that libuv polls for its event loop. So by polling the backend fd it is possible to get notified when there is a new event in libuv.

So in Electron I created a separate thread to poll the backend fd, and since I was using the system calls for polling instead of libuv APIs, it was thread safe. And whenever there was a new event in libuv's event loop, a message would be posted to Chromium's message loop, and the events of libuv would then be processed in the main thread.

In this way I avoided patching Chromium and Node, and the same code was used in both the main and renderer processes.

The code

You can find the implemention of the message loop integration in the node_bindings files under electron/atom/common/. It can be easily reused for projects that want to integrate Node.

Actualización: Implementación movida a electron/shell/common/node_bindings.cc.

Podcasts de Electron

· Lectura de un minuto

¿Buscas comenzar en el mundo de Electron? Se han publicado dos nuevos podcasts que ofrecen un gran vistazo a qué es, por qué se construyó y cómo se está utilizando.


Ya disponible:

Hanselminutes: Creando aplicaciones multiplataforma de Electron

¿Es Electron "sólo Chrome en una ventana" o es mucho más? Jessica pone a Scott en el camino correcto y explica exactamente donde encaja la plataforma de Electron en su mundo como desarrollador.


JavaScript Air: Electron Apps

Electron is becoming more and more of a relevant and popular way of building multi-platform desktop apps with web technologies. Let's get a dive into this awesome tech and see how we can use it to enhance our own experience and our user's experience on the desktop.


If you're looking for an introduction to Electron, give the first a listen. The second goes into more detail about building apps with great tips from Nylas's Evan Morikawa.

We are currently working on two more podcasts that should come out next month, keep an eye on the @ElectronJS Twitter account for updates.

Electron 1.0

· 4 lectura mínima

Durante los últimos dos años, Electron ha ayudado a los desarrolladores a construir aplicaciones multiplataforma de escritorio usando HTML, CSS y JavaScript. Ahora estamos encantados de compartir un hito importante para nuestro framework y para la comunidad que lo creó. La versión de Electron 1.0 ya está disponible en electronjs.org.


Electron 1.0

Electron 1.0 representa un hito importante en la estabilidad y madurez de la API. Esta versión te permite construir aplicaciones que actúen y se sientan verdaderamente nativas en Windows, Mac y Linux. Construir aplicaciones de Electron es más fácil que nunca con nueva documentación, nuevas herramientas y una nueva aplicación para guiarlo a través de las API de Electron.

Si estás listo para construir tu primera aplicación Electron , aquí tienes una guía de inicio rápido para ayudarte a empezar.

Estaremos encantados de ver tus creaciones con Electron.

Trayectoria de Electron

Lanzamos Electron cuando lanzamos Atom hace poco más de dos años. Electron, entonces conocido como Atom Shell, era el framework sobre el que habíamos construido Atom. En esos días, Atom fue la fuerza motriz detrás de las características y funcionalidades que Electron proporcionaba, bajo la presión de lograr el lanzamiento inicial de Atom.

Ahora conducir Electron es una creciente comunidad de desarrolladores y empresas que construyen todo desde correo electrónico, chat, y aplicaciones Git a herramientas de análisis SQL, clientes torrent, y robots.

En estos últimos dos años hemos visto tanto empresas como proyectos de código abierto elegir Electron como la base de sus aplicaciones. Justamente el año pasado, Electron ha sido descargado por más de 1.2 millones de veces. Da una visita a algunas de las increíbles aplicaciones de Electron y añade la tuya si no está ahí.

Descarga Electron

Demos de la API de Electron

Junto con el lanzamiento de la versión 1.0, estamos lanzando una nueva aplicación para ayudarte a explorar las API de Electron y aprender más sobre cómo hacer que tu aplicación de Electron se sienta nativa. La aplicación Electron API Demos contiene fragmentos de código para ayudar a comenzar su aplicación y consejos sobre el uso efectivo de las API de Electron.

Demos de la API de Electron

Devtron

También hemos añadido una nueva extensión para ayudarte a depurar tus aplicaciones de Electron. Devtron es una extensión de código abierto a las Herramientas para desarrolladores de Chrome diseñadas para ayudarte a inspeccionar, debug, y solucione problemas a su aplicación Electron.

Devtron

Características

  • Require graph que te ayuda a visualizar las dependencias internas y externas de las bibliotecas de tu aplicación tanto en los procesos principales como en los procesos de renderizado
  • IPC monitor que rastrea y muestra los mensajes enviados y recibidos entre los procesos de tu aplicación
  • Event inspector que muestra los eventos y los escuchadores que están registrados en tu aplicación en las API principales de Electron, como la ventana, la aplicación y los procesos
  • App Linter que verifica tus aplicaciones en busca de errores comunes y funcionalidades faltantes

Spectron

Finalmente, lanzamos una nueva versión de Spectron, el framework de pruebas de integración para aplicaciones Electron.

Spectron

Spectron 3.0 cuenta con un soporte completo para toda la API de Electron, lo que te permite escribir pruebas más rápidamente para verificar el comportamiento de tu aplicación en diferentes escenarios y entornos. Spectron se basa en ChromeDriver y WebDriverIO por lo que también tiene APIs completas para la navegación de la página, entrada y ejecución de JavaScript.

Comunidad

Electron 1.0 es el resultado de un esfuerzo de la comunidad realizado por cientos de desarrolladores. Además de la estructura principal, se han lanzado cientos de bibliotecas y herramientas para facilitar la construcción, empaquetado y despliegue de aplicaciones de Electron.

Ahora hay una nueva página de comunidad que muestra muchas de las increíbles herramientas de Electron , aplicaciones, bibliotecas y frameworks en desarrollo. También puede revisar Electron y Electron Userland organizaciones para ver algunos de estos fantásticos proyectos.

¿Eres nuevo en Electron? Mira el video de introducción de Electron 1.0:

Novedades en Electron 0.37

· 5 lectura mínima

Electron 0.37 fue publicado recientemente e incluye una gran actualización de Chrome 47 a Chrome 49, además de algunas nuevas APIs principales. Este último lanzamiento proporciona todas las nuevas características incluidas en Chrome 48 y Chrome 49. Esto incluye las propiedades personalizadas de CSS, soporte incrementado de ES6, mejoras en KeyboardEvent, mejoras en Promise y otras nuevas características disponibles en tu aplicación de Electron.


What's New

Propiedades personalizadas de CSS

Si anteriormente has utilizado lenguajes procesados previamente como Sass y Less, es probablemente que estés familiarizado con las variables, que te permiten definir valores reutilizables en cosas como esquemas de color y diseños. Las variables ayudan a mantener las hojas de estilo SECAS y más fáciles de mantener.

Las propiedades personalizadas de CSS son similares a las variables previamente procesadas en el sentido de que son reutilizables, pero también tienen una cualidad única que las hace más poderosas y flexibles: estas pueden ser manipuladas con JavaScript. Esta sutil pero poderosa característica permite realizar cambios dinámicos a las interfaces visuales, mientras estas se benefician de la aceleración por hardware de CSS y la reducción de código duplicado entre el código de la interfaz y las hojas de estilo.

Para más información sobre las propiedades personalizadas de CSS, lea el artículo de MDN y la demostración de Google Chrome.

Variables de CSS en acción

Veamos un ejemplo de variable simple que puede modificarse sobre la marcha en tu app.

:root {
--awesome-color: #a5ecfa;
}

body {
background-color: var(--awesome-color);
}

El valor de la variable puede ser recuperado y modificado directamente en JavaScript:

// Obtener el valor de la variable ' #A5ECFA'
let color = window
.getComputedStyle(document.body)
.getPropertyValue('--awesome-color');

// Establece el valor de la variable a 'orange'
document.body.style.setProperty('--awesome-color', 'orange');

Los valores de las variables también pueden ser editadas desde la sección de Estilos en las herramientas de desarrollo para una retroalimentación y cambios rápidos:

CSS properties in Styles tab

KeyboardEvent.code Property

Chrome 48 added the new code property available on KeyboardEvent events that will be the physical key pressed independent of the operating system keyboard layout.

This should make implementing custom keyboard shortcuts in your Electron app more accurate and consistent across machines and configurations.

window.addEventListener('keydown', function (event) {
console.log(`${event.code} was pressed.`);
});

Check out this example to see it in action.

Promise Rejection Events

Chrome 49 added two new window events that allow you to be notified when an rejected Promise goes unhandled.

window.addEventListener('unhandledrejection', function (event) {
console.log('A rejected promise was unhandled', event.promise, event.reason);
});

window.addEventListener('rejectionhandled', function (event) {
console.log('A rejected promise was handled', event.promise, event.reason);
});

Check out this example to see it in action.

ES2015 Updates in V8

The version of V8 now in Electron incorporates 91% of ES2015. Here are a few interesting additions you can use out of the box—without flags or pre-compilers:

Default parameters

function multiply(x, y = 1) {
return x * y;
}

multiply(5); // 5

Asignación de desestructuración

Chrome 49 added destructuring assignment to make assigning variables and function parameters much easier.

This makes Electron requires cleaner and more compact to assign now:

Browser Process Requires
const { app, BrowserWindow, Menu } = require('electron');
Renderer Process Requires
const { dialog, Tray } = require('electron').remote;
Other Examples
// Destructuring an array and skipping the second element
const [first, , last] = findAll();

// Destructuring function parameters
function whois({ displayName: displayName, fullName: { firstName: name } }) {
console.log(`${displayName} is ${name}`);
}

let user = {
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe',
},
};
whois(user); // "jdoe is John"

// Destructuring an object
let { name, avatar } = getUser();

New Electron APIs

A few of the new Electron APIs are below, you can see each new API in the release notes for Electron releases.

show and hide events on BrowserWindow

These events are emitted when the window is either shown or hidden.

const { BrowserWindow } = require('electron');

let window = new BrowserWindow({ width: 500, height: 500 });
window.on('show', function () {
console.log('Window was shown');
});
window.on('hide', function () {
console.log('Window was hidden');
});

platform-theme-changed on app for OS X

This event is emitted when the system’s Dark Mode theme is toggled.

const { app } = require('electron');

app.on('platform-theme-changed', function () {
console.log(`Platform theme changed. In dark mode? ${app.isDarkMode()}`);
});

app.isDarkMode() for OS X

This method returns true if the system is in Dark Mode, and false otherwise.

scroll-touch-begin and scroll-touch-end events to BrowserWindow for OS X

These events are emitted when the scroll wheel event phase has begun or has ended.

const { BrowserWindow } = require('electron');

let window = new BrowserWindow({ width: 500, height: 500 });
window.on('scroll-touch-begin', function () {
console.log('Scroll touch started');
});
window.on('scroll-touch-end', function () {
console.log('Scroll touch ended');
});

Use V8 and Chromium Features in Electron

· 2 lectura mínima

Building an Electron application means you only need to create one codebase and design for one browser, which is pretty handy. But because Electron stays up to date with Node.js and Chromium as they release, you also get to make use of the great features they ship with. In some cases this eliminates dependencies you might have previously needed to include in a web app.


There are many features and we'll cover some here as examples, but if you're interested in learning about all features you can keep an eye on the Google Chromium blog and Node.js changelogs. You can see what versions of Node.js, Chromium and V8 Electron is using at electronjs.org/#electron-versions.

ES6 Support through V8

Electron combines Chromium's rendering library with Node.js. The two share the same JavaScript engine, V8. Many ECMAScript 2015 (ES6) features are already built into V8 which means you can use them in your Electron application without any compilers.

Below are a few examples but you can also get classes (in strict mode), block scoping, promises, typed arrays and more. Check out this list for more information on ES6 features in V8.

Arrow Functions

findTime () => {
console.log(new Date())
}

String Interpolation

var octocat = 'Mona Lisa';
console.log(`The octocat's name is ${octocat}`);

New Target

Octocat() => {
if (!new.target) throw "Not new";
console.log("New Octocat");
}

// Throws
Octocat();
// Logs
new Octocat();

Array Includes

// Returns true
[1, 2].includes(2);

Rest Parameters

// Represent indefinite number of arguments as an array
(o, c, ...args) => {
console.log(args.length);
};

Chromium Features

Thanks to all the hard work Google and contributors put into Chromium, when you build Electron apps you can also use cool things like (but not limited to):

Follow along with the Google Chromium blog to learn about features as new versions ship and again, you can check the version of Chromium that Electron uses here.

What are you excited about?

Tweet to us @ElectronJS with your favorite features built into V8 or Chromium.

API Changes Coming in Electron 1.0

· 4 lectura mínima

Since the beginning of Electron, starting way back when it used to be called Atom-Shell, we have been experimenting with providing a nice cross-platform JavaScript API for Chromium's content module and native GUI components. The APIs started very organically, and over time we have made several changes to improve the initial designs.


Now with Electron gearing up for a 1.0 release, we'd like to take the opportunity for change by addressing the last niggling API details. The changes described below are included in 0.35.x, with the old APIs reporting deprecation warnings so you can get up to date for the future 1.0 release. An Electron 1.0 won't be out for a few months so you have some time before these changes become breaking.

Deprecation warnings

By default, warnings will show if you are using deprecated APIs. To turn them off you can set process.noDeprecation to true. To track the sources of deprecated API usages, you can set process.throwDeprecation to true to throw exceptions instead of printing warnings, or set process.traceDeprecation to true to print the traces of the deprecations.

New way of using built-in modules

Los módulos integrados ahora se agrupan en un solo módulo, en lugar de separarse en módulos independientes, así que puedes usarlos sin conflictos con otros módulos:

var app = require('electron').app;
var BrowserWindow = require('electron').BrowserWindow;

The old way of require('app') is still supported for backward compatibility, but you can also turn if off:

require('electron').hideInternalModules();
require('app'); // throws error.

An easier way to use the remote module

Because of the way using built-in modules has changed, we have made it easier to use main-process-side modules in renderer process. You can now just access remote's attributes to use them:

// New way.
var app = require('electron').remote.app;
var BrowserWindow = require('electron').remote.BrowserWindow;

Instead of using a long require chain:

// Old way.
var app = require('electron').remote.require('app');
var BrowserWindow = require('electron').remote.require('BrowserWindow');

Splitting the ipc module

The ipc module existed on both the main process and renderer process and the API was different on each side, which is quite confusing for new users. We have renamed the module to ipcMain in the main process, and ipcRenderer in the renderer process to avoid confusion:

// In main process.
var ipcMain = require('electron').ipcMain;
// In renderer process.
var ipcRenderer = require('electron').ipcRenderer;

And for the ipcRenderer module, an extra event object has been added when receiving messages, to match how messages are handled in ipcMain modules:

ipcRenderer.on('message', function (event) {
console.log(event);
});

Standardizing BrowserWindow options

The BrowserWindow options had different styles based on the options of other APIs, and were a bit hard to use in JavaScript because of the - in the names. They are now standardized to the traditional JavaScript names:

new BrowserWindow({ minWidth: 800, minHeight: 600 });

Following DOM's conventions for API names

The API names in Electron used to prefer camelCase for all API names, like Url to URL, but the DOM has its own conventions, and they prefer URL to Url, while using Id instead of ID. We have done the following API renames to match the DOM's styles:

  • Url is renamed to URL
  • Csp is renamed to CSP

You will notice lots of deprecations when using Electron v0.35.0 for your app because of these changes. An easy way to fix them is to replace all instances of Url with URL.

Changes to Tray's event names

The style of Tray event names was a bit different from other modules so a rename has been done to make it match the others.

  • clicked is renamed to click
  • double-clicked is renamed to double-click
  • right-clicked is renamed to right-click

Mac App Store and Windows Auto Updater on Electron

· 2 lectura mínima

Recently Electron added two exciting features: a Mac App Store compatible build and a built-in Windows auto updater.


Mac App Store Support

As of v0.34.0 each Electron release includes a build compatible with the Mac App Store. Previously an application built on Electron would not comply with Apple's requirements for the Mac App Store. Most of these requirements are related to the use of private APIs. In order to sandbox Electron in such a way that it complies with the requirements two modules needed to be removed:

  • crash-reporter
  • auto-updater

Additionally some behaviors have changed with respect to detecting DNS changes, video capture and accessibility features. You can read more about the changes and submitting your app to the Mac App store in the documentation. The distributions can be found on the Electron releases page, prefixed with mas-.

Related Pull Requests: electron/electron#3108, electron/electron#2920

Windows Auto Updater

In Electron v0.34.1 the auto-updater module was improved in order to work with Squirrel.Windows. This means that Electron ships with easy ways for auto updating your app on both OS X and Windows. You can read more on setting up your app for auto updating on Windows in the documentation.

Related Pull Request: electron/electron#1984

Novedades en Electrón

· 2 lectura mínima

Ha habido algunas actualizaciones interesantes y charlas dadas recientemente en Electron, aquí hay un resumen.


Origen

Electron está actualizado con Chrome 45 a partir v0.32.0. Otras actualizaciones incluyen...

Mejor Documentación

nuevos documentos

Hemos reestructurado y estandarizado la documentación para que luzca y se lea mejor. Además hay traducciones de la documentación aportadas por la comunidad, como el japonés y el coreano.

Pull requests relacionados: electron/electron#2028, electron/electron#2533, electron/electron#2557, electron/electron#2709, electron/electron#2725, electron/electron#2698, electron/electron#2649.

Node.js 4.1.0

Desde v0.33.0 Electron viene con Node.js 4.1.0.

Pull request relacionado: electron/electron#2817.

node-pre-gyp

Los módulos que dependen de node-pre-gyp ahora pueden ser compilados contra Electron cuando se construye desde la fuente.

Pull request relacionado: mapbox/node-pre-gyp#175.

Soporte ARM

Ahora Electron proporciona compilaciones para Linux en ARMv7. Se ejecuta en plataformas populares como Chromebook y Raspberry Pi 2.

Temas relacionados: atom/libchromiumcontent#138, electron/electron#2094, electron/electron#366.

Ventana sin marco al estilo Yosemite

ventana sin borde

Se ha integrado un parche de @jaanus que, al igual que otras aplicaciones integradas de OS X, permite crear ventanas sin marcos con luces de tráfico del sistema integradas en OS X Yosemite y posteriores.

Pull request relacionado: electron/electron#2776.

Soporte para impresión de Google Summer of Code

Después del Google Summer of Code hemos incorporado parches de @hokein para mejorar el soporte de impresión y agregar la habilidad de imprimir la página en archivos PDF.

Temas relacionados: electron/electron#2677, electron/electron#1935, electron/electron#1532, electron/electron#805, electron/electron#1669, electron/electron#1835.

Atom

Atom se ha actualizado ahora a Electron v0.30.6 ejecutando Chrome 44. Una actualización a v0.33.0 está en progreso en atom/atom#8779.

Talks

GitHubber Amy Palamountain dio una gran introducción a Electron en una charla en Nordic.js. Además creó la libreria electron-accelerator.

Construir aplicaciones nativas con Electron por Amy Palomountain

Ben Ogle, también en el equipo de Atom, dio una charla de Electron en YAPC Asia:

Crear Aplicaciones de Escritorio con Tecnologías Web por Ben Ogle

El miembro del equipo Atom Kevin Sawicki y otros dieron una charla sobre Electron en la reunión Bay Are Electron User Group recientemente. Los videos han sido publicados, aquí hay un par:

La historia de Electron por Kevin Sawicki

Hacer que una aplicación web parezca nativa por Ben Gotow

Reunión de Electron en las oficinas centrales de GitHub

· Lectura de un minuto

Únete a nosotros el 29 de setiembre en las oficinas centrales de GitHub para una reunión de Electron organizada por los miembros del equipo de Atom @jlord y @kevinsawicki. There will be talks, food to snack on, and time to hangout and meet others doing cool things with Electron. We'll also have a bit of time to do lightning talks for those interested. Hope to see you there!


Talks

  • Jonathan Ross and Francois Laberge from Jibo will share how they use Electron to animate a robot.
  • Jessica Lord will talk about building a teaching tool, Git-it, on Electron.
  • Tom Moor will talk about the pros and cons of building video and screen sharing on Electron with speak.io.
  • Ben Gotow will preview N1: The Nylas Mail Client and talk about developing it on Electron.

Detalles

electron-meetup-office-2