Saltar al contenido principal

Project of the Week: Ghost

· 5 lectura mínima

This week we chatted with Felix Rieseberg, desktop engineer at Slack and maintainer of Ghost Desktop, an Electron client for the Ghost publishing platform.


Ghost Desktop Screenshot

What is Ghost?

Ghost is a fully open source, hackable platform for building and running a modern online publication. We power blogs, magazines and journalists from Zappos to Sky News.

What makes it different from other publishing platforms?

Ghost was founded in April 2013, after a very successful Kickstarter campaign to create a new platform focused solely on professional publishing. Our mission is to create the best open source tools for independent journalists and writers across the world, and have a real impact on the future of online media. Ofrece una experiencia más simple y enfocada, ya que nuestro editor está diseñado exclusivamente para ofrecer la mejor herramienta de escritura posible.

Compared to the all-time classic WordPress, it offers a simpler, more streamlined experience - it is easier to setup and maintain, comes with all important features out-of-the-box, and is dramatically faster. Compared to other online platforms, Ghost gives writers full ownership and control over their content, allows full customization, and enables authors to build a business around their publication.

Is Ghost a for-profit company?

This one is important to us: Ghost is an independent non-profit organisation. We build publishing tools for modern journalism & blogging because we believe freedom of speech is important. Our software is released under a free open source license, our business model is completely transparent, and our legal structure means that 100% of the money we make is reinvested into making Ghost better.

What is Ghost Desktop?

Ghost Desktop allows writers to manage multiple blogs at once - and to focus on their writing. Las cosas simples como los accesos directos de escritura comunes no se pueden realizar en un navegador, pero están disponibles en nuestra aplicación de escritorio. Permite a otras aplicaciones comunicarse directamente con el blog a través de enlaces profundos.

What is Ghost for Journalism?

This year we're very excited to be dedicating our entire 10 person full-time Ghost team to helping grow three independent publications, along with $45,000 in resources toward their efforts. We're calling it Ghost for Journalism.

We've been building Ghost as the web's next great platform for independent publishers for about three and half years now, and we've now reached a really interesting inflection point. We started this journey to create a simple, well designed blogging platform which could be used by just about anyone. That was always going to be step one.

Long term, we want Ghost to be an incredible platform for the world's best journalism, and that means we need to build features to attract exactly those people. This year we're making a very conscious decision to focus on just that.

Why did you choose to build Ghost Desktop on Electron?

Ghost uses JavaScript and Node.js on both the backend and frontend, so being able to utilize the same technology and skillset enables our team to move faster, build more, and ultimately deliver a better experience. In addition, being able to share more than 95% of code between the macOS, Windows, and Linux version of the app allows us to focus on building a great core user experience, without having to maintain one code base for each platform.

What are some challenges you've faced while building Ghost Desktop?

Spellchecking is likely still one of the most difficult services offered - we could easily utilize one of the many online services, but correctly spellchecking text in multiple languages while guarding the privacy and autonomy of our users is not an easy task.

¿En qué áreas debe mejorarse Electron?

We would love to see Electron bring the operating system's native spellchecking capabilities to their apps. We're dreaming about a world in which an <input> field receives the same services as a NSTextView, but we are also intimately aware how difficult that is.

¿Qué es lo que más le gusta de Electron?

JavaScript is famous for being a vast ecosystem, involving countless tools and frameworks - but the convenience it affords us is hard to overstate. Building an app with Electron is only slightly harder than building a web app, which is an amazing feat.

Is Ghost done? If not, what's coming next?

Ghost Desktop is also an ongoing project - we're pretty far from being done. We have been talking for a while about bringing a full offline mode to our users, and we're getting fairly close. Other notable work areas are the extension and integration with other text editing apps (like Word or Atom), ultimately allowing people to write posts using their favorite tools. In general, once we've shipped the offline mode feature, we're looking for deeper integration with the operating system. If that sounds interesting to you, join us!

What are some of your favorite Electron apps?

I'm a big fan of Kap, Felony, and Visual Studio Code.

👻

Proyecto de la Semana: Navegador Beaker

· 4 lectura mínima

Esta semana hemos centrado nuestra atención en Paul Frazee, creador de Beaker Browser. Beaker es un navegador web de igual a igual (peer-to-peer) experimental que utiliza el protocolo Dat para alojar sitios desde los dispositivos de los usuarios.


¿Qué es Beaker y por qué lo creaste?

Beaker es un navegador participativo. Es un navegador para hackers independientes.

La web es de código cerrado. Si quieres influir en cómo funcionan las redes sociales, tienes que trabajar en Facebook o Twitter. Para búsqueda, Google. El control está en manos de las empresas, y no de los propios usuarios.

Con Beaker, tenemos un nuevo protocolo Web: el Transporte de archivos descentralizados (Decentralized Archive Transport). "Dato". Crea sitios bajo demanda, de forma gratuita, y luego los comparte desde el dispositivo. No se requieren servidores. Esa es nuestra innovación.

Protocols de Beakers

Cuando visitas un sitio de Dat en Beaker, descargas los archivos. El sitio es tuyo, para siempre. Puedes guardarlo, bifurcarlo, modificarlo y compartir gratis tu nueva versión. Todo es de código abierto.

De eso se trata: Estamos creando un navegador para sitios web de código abierto. Queremos que sea un conjunto de herramientas para el hacking social.

¿Quién debería usar Beaker?

Hackers. Modders. Tipos creativos. A la gente a la que le gusta jugar.

¿Cómo puedo crear un nuevo proyecto que utilice Dat?

Tenemos una herramienta de línea de comandos llamada bkr que es como git + npm. Creando el sitio:

$ bifurcación bkr dat://0ff7d4c7644d0aa19914247dc5dbf502d6a02ea89a5145e7b178d57db00504cd/ ~/my-fork
$ cd ~/my-fork
$ echo "Mi bifurcación no tiene en cuenta el índice anterior. tml!" > index.html
$ bkr publicar

Haciendo fork del sitio:

$ bkr fork dat://0ff7d4c7644d0aa19914247dc5dbf502d6a02ea89a5145e7b178d57db00504cd/ ~/my-fork
$ cd ~/my-fork
$ echo "Mi bifurcación no tiene en cuenta el anterior index.html!" tml!" > index.html
$ bkr publicar

Estos sitios son alojados fuera de su navegador. Es un poco como BitTorrent; usted comparte los sitios en una malla P2P.

Si quieres una interfaz de usuario tenemos algunas herramientas básicas incorporadas en el navegador pero estamos trabajando para incorporarlas en userland. Todo va a ser aplicaciones de usuario modulables.

¿Por qué elegiste construir Beaker en Electron?

Era evidente para este proyecto. Si yo mismo bifurcara Chrome, ¡estaría escribiendo C++ ahora mismo! Nadie quiere hacerlo. Conozco la pila web, y puedo trabajar rápidamente con ella. Es obvio.

La verdad es que no estoy seguro de que hubiera podido hacer nada de esto sin Electron. Es una gran software.

¿Cuáles son algunos de los desafíos a los que se enfrenta mientras construye Beaker?

La mitad es hurgar en las herramientas y averiguar cuánto puedo conseguir.

Hacer el navegador en sí mismo fue bastante fácil. Electron es prácticamente un conjunto de herramientas para hacer navegadores. ...Excepto por las pestañas del navegador; eso me llevó bastante hacerlo bien. Finalmente me derrumbé y aprendí a hacer SVG. Se ve mucho mejor, pero me costó 3 o 4 veces antes de hacerlo bien.

¿En qué áreas debe mejorarse Electron?

Sería realmente genial si pudiera acoplar las herramientas de desarrollo dentro de una vista web.

¿Qué es lo siguiente en Beaker?

Nombres DNS seguros para sitios Dat. Un esquema de URL socialmente configurable, llamado el "esquema de aplicación". Más API Dat.

¿Para la gente que puede estar interesada en contribuir al proyecto, en qué áreas necesita ayuda Beaker?

Tenemos muchas cuestiones abiertas. No tengas miedo de hacerme un ping. #beakerbrowser en freenode. Mantenemos una página para los colaboradores y te agregaremos a ella. Y si visitas Austin, te invitaré a una cerveza.

¿Algún consejo sobre Electron que pueda ser útil para otros desarrolladores?

  1. Utilice las herramientas de compilación disponibles. No quieres luchar con tus propias soluciones, créeme. Usar electron-builder. Utilice un repositorio repetitivo.
  2. Si necesita abrir un problema en el repositorio de Electron, haga un esfuerzo adicional para que sea fácil de reproducir. Recibirás una respuesta mucho más rápida, y el equipo lo apreciará. Aún mejor, intente arreglarlo usted mismo. En realidad, es bastante interesante ver las entrañas.
  3. Lee todas las guías y documentos avanzados al menos una vez.
  4. No construya un navegador, es un mercado saturado.

Proyecto de la semana: Kap

· 7 lectura mínima

The Electron community is growing quickly, and people are creating powerful new apps and tools at an astounding rate. To celebrate this creative momentum and keep the community informed of some of these new projects, we've decided to start a weekly blog series featuring noteworthy Electron-related projects.


This post is the first in the series, and features Kap, an open-source screen recording app built by Wulkano, a geodistributed team of freelance designers and developers.

Kap Screencast

What is Kap?

Kap is an open-source screen recorder built primarily for designers and developers to easily capture their work. People use it to share animated prototypes, document bugs, create silly GIFs and everything in-between.

Hemos visto a gente de todas las edades y fondos usarlo en entornos educativos, screencasts, tutoriales... la lista continúa. Even to create production assets! We're completely blown away by how well received our little side project has been.

Why did you build it?

That's a very good question, it's not like there's a lack of screen recorders out there! We felt the alternatives were either too complex, too expensive or too limited. Nothing felt just right for our everyday needs. We also think it's great when the tools we use to do our work are open-source, that way everyone can help shape them. Building Kap ended up being just as much about what we didn't do. It's all in the details, an accumulation of small improvements that became the outline of a tool we wanted to use.

However, and maybe most importantly, Kap has become a place for us to leave our worries at the door and just have fun building something for ourselves and people like us. It's so important to create an environment where you get to just vent, try new thins and enjoy your craft. No requirements, no pressure, no expectations. Should designers and developers side project? Why, yes. Yes, they should.

Why did you choose to build Kap on Electron?

There were a number of reasons:

  • Web tech
  • Most of the team are web developers
  • We're invested in JavaScript
  • It opens the door for more people to contribute
  • Electron itself is open-source
  • The power and easily maintainable modularity of node_modules
  • Cross-platform possibilities

We think the future of apps are in the browser, but we're not quite there yet. Electron is an important step in the journey towards that future. It not only makes the apps themselves more accessible, but also the code they're built with. An interesting thought is imagining a future where the OS is a browser, and the tabs are essentially Electron apps.

Additionally, being primarily web developers, we're big fans of the isomorphic nature of JavaScript, in that you can run JS on the client, server, and now the desktop. With web tech (HTML, CSS and JS), many things are much simpler than native: Faster prototyping, less code, flexbox > auto-layout (macOS/iOS).

What are some challenges you've faced while building Kap?

Using the resources Electron has available to record the screen was the biggest challenge. They simply weren't performant enough to meet our requirements and would render the project a failure in our eyes. Though at no fault of Electron itself, there's still a gap between native development and building desktop apps with web tech.

We spent a lot of time trying to work around the poor performance of the getUserMedia API, an issue originating in Chromium. One of our main goals when we set out to make Kap was to build the entire app with web tech. After trying everything we could to get it working (the minimum requirement being 30 FPS on a Retina screen), we eventually had to find another solution.

I see some Swift code in the repo. What's that about?

Being forced to look for alternatives to getUserMedia, we started experimenting with ffmpeg. Besides being one of the best tools for audio and video conversion it has the functionality of recording the screen in almost any OS, and we were able to record crispy video meeting our minimum requirement of 30 FPS on a Retina screen. Problema? The performance was "😩", the CPU usage was going haywire. So we went back to the drawing board, discussed our options and realised that we had to make a compromise. That resulted in Aperture, our own screen recording library for macOS written in Swift.

¿En qué áreas debe mejorarse Electron?

We all know that Electron apps can have a thing for using RAM, but again, that's really a Chromium thing. It's part of how it works and it really depends on what you're running, for example Kap and Hyper typically use less than 100MB of memory.

One of the biggest areas of improvement that we see is payload, particularly how Electron distributes Chromium. One idea would be to have a shared Electron core and make app installers check if it's already present on the system.

Creating cross-platform Electron apps could be a better experience. Right now there are too many inconsistencies, platform-specific APIs, and missing features between platforms, making your codebase littered with if-else statements. For example, vibrancy is only supported on macOS, the auto-updater works differently on macOS and Windows, and is not even supported on Linux. Transparency is a hit or miss on Linux, usually miss.

It should also be easier to call native system APIs. Electron comes with a very good set of APIs, but sometimes you need functionality it doesn't provide. Creating a native Node.js addon is an option, but it's painful to work with. Ideally Electron would ship with a good FFI API, like fastcall. This would have enabled us to write the Swift part in JavaScript instead.

¿Qué es lo que más le gusta de Electron?

Our favorite thing is easily the fact that anyone with knowledge of creating for the web can build and contribute to multi-platform native experiences. Not to mention the ease and joy of developing on it, the excellent documentation and the thriving ecosystem.

From a front-end perspective, building Kap felt no different than building a simple website using browser APIs. Electron does a really great job of making app development similar (basically identical) to web development. So simple in fact that there was no need for frameworks or similar to help us, just clean and modular JS and CSS.

We are also huge fans of the team building it, their dedication and support, and the active and friendly community they maintain. Hugs to all of you!

What's coming next in Kap?

The next step for us is to review the app in preparation for our 2.0.0 milestone, which includes a React re-write in addition to support for plugins, allowing developers to extend the functionality of Kap! We invite everyone to follow to project and contribute on our GitHub repository. We're listening and want to hear from as many of you as possible, let us know how we can make Kap the best possible tool it can be for you!

What is Wulkano?

Wulkano is a design studio and digital collective, a team of remote technologists who love working together on both client gigs and our own projects. We're a distributed but tight knit group of people from different places and backgrounds, sharing knowledge, ideas, experiences, but most importantly silly GIFs and memes, in our virtual office (which happens to be the Electron based Slack!).

¿Algún consejo sobre Electron que pueda ser útil para otros desarrolladores?

Take advantage of and get involved in the fantastic community, check out Awesome Electron, look at examples and make use of the great docs!

Electron Simple Samples

· 2 lectura mínima

We recently hosted an Electron hackathon at GitHub HQ for members of Hackbright Academy, a coding school for women founded in San Francisco. To help attendees get a head start on their projects, our own Kevin Sawicki created a few sample Electron applications.


If you're new to Electron development or haven't yet tried it out, these sample applications are a great place to start. They are small, easy to read, and the code is heavily commented to explain how everything works.

To get started, clone this repository:

git clone https://github.com/electron/simple-samples

To run any of the apps below, change into the app's directory, install dependencies, then start:

cd activity-monitor
npm install
npm start

Activity Monitor

Shows a doughnut chart of the CPU system, user, and idle activity time.

Captura de pantalla

Hash

Shows the hash values of entered text using different algorithms.

captura de pantalla

Espejo

Plays a video of the computer's camera at a maximized size like looking into a mirror. Includes an optional rainbow filter effect that uses CSS animations.

Prices

Shows the current price of oil, gold, and silver using the Yahoo Finance API.

captura de pantalla

URL

Loads a URL passed on the command line in a window.

Other Resources

We hope these apps help you get started using Electron. Here are a handful other resources for learning more:

Electron Userland

· 3 lectura mínima

We've added a new userland section to the Electron website to help users discover the people, packages, and apps that make up our flourishing open-source ecosystem.


github-contributors

Origins of Userland

Userland is where people in software communities come together to share tools and ideas. The term originated in the Unix community, where it referred to any program that ran outside of the kernel, but today it means something more. When people in today's Javascript community refer to userland, they're usually talking about the npm package registry. This is where the majority of experimentation and innovation happens, while Node and the JavaScript language (like the Unix kernel) retain a relatively small and stable set of core features.

Node and Electron

Like Node, Electron has a small set of core APIs. These provide the basic features needed for developing multi-platform desktop applications. Esta filosofía de diseño permite Electron a seguir siendo una herramienta flexible sin ser excesivamente prescriptivas sobre cómo deben utilizarse.

Userland is the counterpart to "core", enabling users to create and share tools that extend Electron's functionality.

Collecting data

To better understand the trends in our ecosystem, we analyzed metadata from 15,000 public GitHub repositories that depend on electron or electron-prebuilt

We used the GitHub API, the libraries.io API, and the npm registry to gather info about dependencies, development dependencies, dependents, package authors, repo contributors, download counts, fork counts, stargazer counts, etc.

We then used this data to generate the following reports:

Filtering Results

Reports like app dependencies and starred apps which list packages, apps, and repos have a text input that can be used to filter the results.

As you type into this input, the URL of the page is updated dynamically. This allows you to copy a URL representing a particular slice of userland data, then share it with others.

babel

More to come

This first set of reports is just the beginning. We will continue to collect data about how the community is building Electron, and will be adding new reports to the website.

All of the tools used to collect and display this data are open-source:

If you have ideas about how to improve these reports, please let us know opening an issue on the website repository or any of the above-mentioned repos.

Thanks to you, the Electron community, for making userland what it is today!

Corrección de transparencia del certificado

· 3 lectura mínima

Electron 1.4. 2 contiene un parche importante que soluciona un problema de Chrome en el que algunos Symantec, GeoTrust, y los certificados Thawte SSL/TLS son rechazados incorrectamente 10 semanas desde el tiempo de compilación de libchromiumcontent, La biblioteca Chrome de Electron subyacente. No hay problemas con los certificados utilizados en los sitios afectados y la sustitución de estos certificados no ayudará.


En Electron 1.4.0 — 1.4.11 las solicitudes HTTPS a los sitios que utilicen estos certificados afectados fallarán con errores de red después de una fecha determinada. Esto afecta las solicitudes HTTPS realizadas con las API de red subyacentes de Chrome. como window.fetch,Solicitudes de Ajax, Electron's net API, BrowserWindow.loadURL, webContents.loadURL, el atributo src en una etiqueta <webview> y otros.

Actualizando sus aplicaciones a 1.4.12 evitará que se produzcan estos errores de solicitud.

Nota: Este problema se introdujo en Chrome 53, por lo que las versiones anteriores a Electron 1.4.0 no se ven afectadas.

Fechas de impacto

A continuación se muestra una tabla de cada versión de Electron 1.4 y la fecha en que las solicitudes a los sitios que utilizan estos certificados afectados comenzarán a fallar.

Versión de ElectronFecha de Impacto
1.3.xInafectada
1.4.0Ya está fallando
1.4.1Ya está fallando
1.4.2Ya está fallando
1.4.310 de diciembre de 2016 9:00 PM PST
1.4.410 de diciembre de 2016 9:00 PM PST
1.4.510 de diciembre de 2016 9:00 PM PST
1.4.614 de enero de 2017 9:00 PM PST
1.4.714 de enero de 2017 9:00 PM PST
1.4.814 de enero de 2017 9:00 PM PST
1.4.914 de enero de 2017 9:00 PM PST
1.4.1014 de enero de 2017 9:00 PM PST
1.4.1111 de febrero de 2017 9:00 PM PST
1.4.12Inafectada

Puedes verificar la fecha de impacto de tu aplicación adelantando el reloj de tu ordenador y luego comprobar si https://symbeta. ymantec.com/welcome/ carga con éxito.

Más información

Puede leer más sobre este tema, el problema original y la corrección en los siguientes lugares:

Septiembre 2016: Nuevas Apps

· 3 lectura mínima

Here are the new Electron apps and talks that were added to the site in September.


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.

New Talks

In September, GitHub held its GitHub Universe conference billed as the event for people building the future of software. There were a couple of interesting Electron talks at the event.

Also, if you happen to be in Paris on December 5, Zeke will be giving an Electron talk at dotJS 2016.

Nuevas aplicaciones

PexelsSearch for completely free photos and copy them into your clipboard
Marca de tiempoA better macOS menu bar clock with a customizable date/time display and a calendar
HarmonyMusic player compatible with Spotify, Soundcloud, Play Music and your local files
uPhoneWebRTC Desktop Phone
SealTalkInstant-messaging App powered by RongCloud IM Cloud Service and IM SDK
InfinityAn easy way to make presentation
Cycligent Git ToolStraightforward, graphic GUI for your Git projects
FocoStay focused and boost productivity with Foco
StrawberryWin Diners for Life Know and serve them better with the all-in-one restaurant software suite.
MixmaxSee every action on your emails in real-time Compose anywhere.
Firebase AdminA Firebase data management tool
ANoteA Simple Friendly Markdown Note
TempsA simple but smart menubar weather app
AmiumA work collaboration product that brings conversation to your files
SoubeReproductor sencillo de música
(Un)coloredNext generation desktop rich content editor that saves documents with themes HTML & Markdown compatible. For Windows, OS X & Linux.
quickcalcMenubar Calculator
Forestpin AnalyticsFinancial data analytics tool for businesses
LingREST Client
ShortextsShortcuts for texts you copy frequently, folders and emojis
Front-End BoxSet of front-end-code generators

Documentos de la API de Electron como Datos Estructurados

· 4 lectura mínima

Hoy presentamos algunas mejoras en la documentación de Electron. Cada nuevo lanzamiento ahora incluye un archivo JSON que describe todas las APIs públicas de Electron en detalle. Hemos creado este archivo para facilitar a los desarrolladores usar la documentación de la API de Electron de maneras nuevas e interesantes.


Resumen del esquema

Cada API es un objeto con propiedades como nombre, descripción, tipo, etc. Las clases como BrowserWindow y Menu tienen propiedades adicionales que describen sus métodos de instancia, propiedades de instancia, eventos de instancia, etc.

Aquí hay un fragmento del esquema que describe la clase BrowserWindow:

{
name: 'BrowserWindow',
description: 'Crear y controlar ventanas del navegador. ,
process: {
main: true,
renderer: false
},
type: 'Class',
instanceName: 'win',
slug: 'browser-window',
websiteUrl: 'https://electronjs. rg/docs/api/browser-window',
repoUrl: 'https://github.com/electron/electron/blob/v1.4.0/docs/api/browser-window. d',
staticMethods: [...],
instanceMethods: [...],
instanceProperties: [...],
instanceEvents: [...]
}
}

Y aquí hay un ejemplo de la descripción de un método, en este caso el método de instancia apis.BrowserWindow.instanceMethods.setMaximumSize:

{
name: 'setMaximumSize',
signature: '(width, height)',
description: 'Establece el tamaño máximo de la ventana a anchura y altura. ,
parameters: [{
name: 'width',
type: 'Integer'
}, {
name: 'height',
type: 'Integer'
}]
}

Usando los nuevos datos

Para facilitar a los desarrolladores el uso de estos datos estructurados en sus proyectos, hemos creado electron-docs-api, un pequeño paquete npm que se publica automáticamente cada vez que hay una nueva versión de Electron.

npm install electron-api-docs --save

Para una gratificación instantánea, pruebe el módulo en su REPL de Node.js:

npm i -g trymodule && trymodule electron-api-docs=apis

Qué datos se recopilan

La documentación de la API de Electron se adhiere al Estilo de codificación de Electrón y al Estilo de Electrón, para que su contenido pueda ser analizado programáticamente.

El repositorio electron-docs-linter es una nueva dependencia de desarrollo del repositorio electron/electron. Es una herramienta de línea de comandos que muestra todos los archivos de markdown e impone la reglas del styleguide. Si se encuentran errores, se listan y el proceso de liberación se detiene. Si los documentos de la API son válidos, el archivo electron-json.api se crea y se sube a GitHub como parte de la versión de Electron.

Javascript estándar y Markdown estándar

A principios de este año, el código base de Electron fue actualizado para usar el linter standard para todos los JavaScript. El README de standard resume el razonamiento detrás de esta elección:

Adoptar el estilo standard significa clasificar la importancia de la claridad del código y las convenciones comunitarias por encima del estilo personal. Esto podría no tener sentido para el 100% de los proyectos y las culturas de desarrollo, sin embargo el código abierto puede ser un lugar hostil para los novatos. Establecer expectativas claras y automatizadas de los colaboradores hace que un proyecto sea más saludable.

También recientemente creamos standard markdown para verificar que todos los fragmentos de código JavaScript en nuestra documentación son válidos y consistentes con el estilo en la base de código.

Juntas, estas herramientas nos ayudan a utilizar la integración continua (IC) para encontrar automáticamente errores en las solicitudes PR para añadir actualizaciones al repositorio (Pull Requests). Esto reduce la carga impuesta a los humanos haciendo revisión del código, y nos da más confianza sobre la precisión de nuestra documentación.

Un esfuerzo de la comunidad

La documentación de Electron está mejorando constantemente, y tenemos a nuestra increíble comunidad de código abierto a la que darle las gracias por ello. Cerca de 300 personas han contribuido a la documentación, que incluye este texto.

Estamos encantados de ver qué hacen las personas con estos nuevos datos estructurados. Las usos posibles incluyen:

Electron Internals: Referencias débiles

· 6 lectura mínima

As a language with garbage collection, JavaScript frees users from managing resources manually. But because Electron hosts this environment, it has to be very careful avoiding both memory and resources leaks.

This post introduces the concept of weak references and how they are used to manage resources in Electron.


Weak references

In JavaScript, whenever you assign an object to a variable, you are adding a reference to the object. As long as there is a reference to the object, it will always be kept in memory. Once all references to the object are gone, i.e. there are no longer variables storing the object, the JavaScript engine will recoup the memory on next garbage collection.

A weak reference is a reference to an object that allows you to get the object without effecting whether it will be garbage collected or not. You will also get notified when the object is garbage collected. It then becomes possible to manage resources with JavaScript.

Using the NativeImage class in Electron as an example, every time you call the nativeImage.create() API, a NativeImage instance is returned and it is storing the image data in C++. Once you are done with the instance and the JavaScript engine (V8) has garbage collected the object, code in C++ will be called to free the image data in memory, so there is no need for users manage this manually.

Otro ejemplo es el problema desaparecido de la ventana, cuál muestra vistivamente cómo se recolecta la basura cuando todas las referencias a ella se han ido.

Testing weak references in Electron

There is no way to directly test weak references in raw JavaScript since the language doesn't have a way to assign weak references. The only API in JavaScript related to weak references is WeakMap, but since it only creates weak-reference keys, it is impossible to know when an object has been garbage collected.

In versions of Electron prior to v0.37.8, you can use the internal v8Util.setDestructor API to test weak references, which adds a weak reference to the passed object and calls the callback when the object is garbage collected:

// El código a continuación solo puede ejecutarse en Electron < v0.37.8.
var v8Util = process.atomBinding('v8_util');

var object = {};
v8Util.setDestructor(object, function () {
console.log('The object is garbage collected');
});

// Remove all references to the object.
object = undefined;
// Manually starts a GC.
gc();
// Console prints "The object is garbage collected".

Note that you have to start Electron with the --js-flags="--expose_gc" command switch to expose the internal gc function.

The API was removed in later versions because V8 actually does not allow running JavaScript code in the destructor and in later versions doing so would cause random crashes.

Weak references in the remote module

Apart from managing native resources with C++, Electron also needs weak references to manage JavaScript resources. Un ejemplo es el módulo remotode Electron, que es un módulo Llamada de Procedimiento Remoto (RPC) que permite usar objetos en el proceso principal de procesos de renderizado.

One key challenge with the remote module is to avoid memory leaks. When users acquire a remote object in the renderer process, the remote module must guarantee the object continues to live in the main process until the references in the renderer process are gone. Additionally, it also has to make sure the object can be garbage collected when there are no longer any reference to it in renderer processes.

For example, without proper implementation, following code would cause memory leaks quickly:

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

for (let i = 0; i < 10000; ++i) {
remote.nativeImage.createEmpty();
}

The resource management in the remote module is simple. Cada vez que un objeto es solicitado, un mensaje es enviado al main process y Electron guardara el objeto en un mapa y le asignara un ID, luego envia de vuelta el ID al renderer process. In the renderer process, the remote module will receive the ID and wrap it with a proxy object and when the proxy object is garbage collected, a message will be sent to the main process to free the object.

Using remote.require API as an example, a simplified implementation looks like this:

remote.require = function (name) {
// Tell the main process to return the metadata of the module.
const meta = ipcRenderer.sendSync('REQUIRE', name);
// Create a proxy object.
const object = metaToValue(meta);
// Tell the main process to free the object when the proxy object is garbage
// collected.
v8Util.setDestructor(object, function () {
ipcRenderer.send('FREE', meta.id);
});
return object;
};

In the main process:

const map = {};
const id = 0;

ipcMain.on('REQUIRE', function (event, name) {
const object = require(name);
// Add a reference to the object.
map[++id] = object;
// Convert the object to metadata.
event.returnValue = valueToMeta(id, object);
});

ipcMain.on('FREE', function (event, id) {
delete map[id];
});

Maps with weak values

With the previous simple implementation, every call in the remote module will return a new remote object from the main process, and each remote object represents a reference to the object in the main process.

The design itself is fine, but the problem is when there are multiple calls to receive the same object, multiple proxy objects will be created and for complicated objects this can add huge pressure on memory usage and garbage collection.

For example, the following code:

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

for (let i = 0; i < 10000; ++i) {
remote.getCurrentWindow();
}

It first uses a lot of memory creating proxy objects and then occupies the CPU (Central Processing Unit) for garbage collecting them and sending IPC messages.

An obvious optimization is to cache the remote objects: when there is already a remote object with the same ID, the previous remote object will be returned instead of creating a new one.

This is not possible with the API in JavaScript core. Using the normal map to cache objects will prevent V8 from garbage collecting the objects, while the WeakMap class can only use objects as weak keys.

To solve this, a map type with values as weak references is added, which is perfect for caching objects with IDs. Now the remote.require looks like this:

const remoteObjectCache = v8Util.createIDWeakMap()

remote.require = function (name) {
// Tell the main process to return the meta data of the module.
...
if (remoteObjectCache.has(meta.id))
return remoteObjectCache.get(meta.id)
// Create a proxy object.
...
remoteObjectCache.set(meta.id, object)
return object
}

Note that the remoteObjectCache stores objects as weak references, so there is no need to delete the key when the object is garbage collected.

Native code

For people interested in the C++ code of weak references in Electron, it can be found in following files:

The setDestructor API:

The createIDWeakMap API:

Agosto 2016: Nuevas Apps

· 3 lectura mínima

Aquí están las nuevas aplicaciones de Electron que fueron añadidas al sitio en agosto.


El sitio se actualiza con nuevas aplicaciones y reuniones a través de pull requests de la comunidad. 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

Código RPGifyAplicación de codificación de estilo RPG
PamFaxUna aplicación multiplataforma para enviar y recibir faxes
BlankUpEditor Markdown con claridad +1
RamboxAplicación libre y de código abierto, que combina las aplicaciones web más comunes de mensajería y correo electrónico
GordieLa mejor aplicación para tus colecciones de tarjetas
Ionic CreatorConstruye increíbles aplicaciones móviles, más rápido
TwitchAlertsMantén a tus espectadores contentos con hermosas alertas y notificaciones
MuseeksUn reproductor de música simple, limpio y multiplataforma
SeaPigUn convertidor de markdown a html
GrupMeAplicación no oficial de GroupMe
MoeditorTu editor de markdown para todos los fines
SoundnodeSoundnode App es la nube de Soundcloud para escritorio
QMUI WebQMUI Web Desktop es una aplicación para administrar proyectos basados en QMUI Web Framework
SvgsusOrganiza, limpia y transforma tus SVGs
RammeApp de escritorio de Instagrama no oficial
InsomniaCliente API REST
CorreoUna aplicación Gmail para Windows, macOS y Linux de barra de menús
KongDashCliente de escritorio para API de admin de Kong
Translation EditorEditor de archivos de traducción para mensajes INTL ICU (ver formatjsio)
5EClient5EPlay CSGO Client
Theme JuiceDesarrollo local de WordPress facilitado