Aller au contenu principal

Project of the Week: Ghost

· 5 mins de lecture

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. It offers a simpler, more focussed experience: Our editor is designed solely around providing the best possible writing experience.

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. Des choses simples comme des raccourcis d'écriture courants ne peuvent pas être réalisées dans un navigateur, mais sont disponibles dans notre application de bureau. Il permet à d'autres applications de communiquer directement avec le blog via deeplinks.

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.

Dans quels domaines faut-il améliorer 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.

Quelles sont vos choses préférées à propos d'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.

👻

Project of the Week: Beaker Browser

· 4 mins de lecture

This week we caught up with Paul Frazee, creator of Beaker Browser. Beaker is an experimental peer-to-peer web browser that uses the Dat protocol to host sites from users’ devices.


What is Beaker and why did you create it?

Beaker is a participatory browser. It's a browser for indie hackers.

The Web is closed source. If you want to influence how social media works, you have to work at Facebook or Twitter. For search, Google. Control is in the hands of companies, rather than the users themselves.

With Beaker, we have a new Web protocol: the Decentralized Archive Transport. "Dat". Il crée des sites à la demande, gratuitement, et ensuite les partage à partir de l'appareil. No servers required. That's our innovation.

Beakers Protocols

When you visit a Dat site in Beaker, you download the files. The site is yours, forever. You can save it, fork it, modify it, and share your new version for free. It's all open-source.

So that's what it's about: We're making a browser for open-source Websites. We want it to be a toolkit for social hacking.

Who should be using Beaker?

Hackers. Modders. Creative types. People who like to tinker.

How do I create a new project that uses Dat?

We've got a command-line tool called bkr that's kind of like git + npm. Here's creating a site:

$ cd ~/mon-site
$ bkr init
$ echo "Bonjour, monde!" > index.html
$ bkr publish

And here's forking a site:

$ bkr fork dat://0ff7d4c7644d0aa19914247dc5dbf502d6a02ea89a5145e7b178d57db00504cd/ ~/my-fork
$ cd ~/my-fork
$ echo "Mon fork n'a aucune considération pour l'index précédent. > index.html
$ bkr publish

Those sites then get hosted out of your browser. It's a little like BitTorrent; you share the sites in a P2P mesh.

If you want a GUI, we have some basic tools built into the browser, but we're pushing those tools into userland. It's all going to be moddable user apps.

Why did you choose to build Beaker on Electron?

It was obvious for this project. If I forked Chrome myself, I'd be writing C++ right now! Nobody wants to do that. I know the Web stack, and I can work quickly with it. It's a no-brainer.

The truth is, I'm not sure I could do any of this without Electron. It's a great piece of software.

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

Half of it is poking at the tools and figuring out how much I can get away with.

Making the browser itself was pretty easy. Electron is practically a toolkit for making browsers. ...Except for the browser tabs; that took me forever to get right. I finally broke down and learned how to do SVGs. It's much better looking, but it took 3 or 4 iterations before I got that right.

Dans quels domaines faut-il améliorer Electron ?

It'd be really great if I could dock the devtools inside a webview.

What's coming next in Beaker?

Secure DNS names for Dat sites. A socially configurable URL scheme, called the "app scheme." More Dat APIs.

For folks who may be interested in contributing to the project, in what areas does Beaker need help?

We have lots of open issues. Don't be afraid to ping me. #beakerbrowser on freenode. We keep a page for contributors and we'll add you to it. And if you visit Austin, I'll buy you a beer.

Des conseils d'Electron qui pourraient être utiles aux autres développeurs ?

  1. Use the build tooling that's out there. You don't want to wrestle with your own solutions, trust me. Use electron-builder. Use a boilerplate repo.
  2. If you need to open an issue in the Electron repo, go the extra mile to make it easy to reproduce. You'll get a response much more quickly, and the team will appreciate it. Even better, try fixing it yourself. It's actually pretty interesting to see the innards.
  3. Read through all the guides and advanced docs at least once.
  4. Don't build a browser, it's a saturated market.

Project of the Week: Kap

· 7 mins de lecture

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.

Nous avons vu des gens de tous âges et de tous horizons l'utiliser dans des environnements éducatifs, screencasts, tutoriels... la liste continue. 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. Problem? 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.

Dans quels domaines faut-il améliorer 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.

Quelles sont vos choses préférées à propos d'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!).

Des conseils d'Electron qui pourraient être utiles aux autres développeurs ?

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

Exemples simples d'Electron

· 2 mins de lecture

Nous avons récemment organisé un hackathon Electron au siège de GitHub pour les membres de la Hackbright Academy, une école de codage pour femmes fondée à San Francisco. Pour aider les participants à prendre un bon départ dans leurs projets, notre propre Kevin Sawicki a créé quelques exemples d'applications Electron.


Si vous êtes nouveau dans le développement avec Electron ou si vous ne l'avez pas encore essayé, ces exemples d'applications sont un bon point de départ. Ils sont petits, faciles à lire et le code est fortement commenté pour expliquer comment tout fonctionne.

Pour commencer, clonez ce dépôt :

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

Pour exécuter l'une des applications ci-dessous, allez dans le répertoire de l'application, installez les dépendances, puis démarrez :

cd activity-monitor
npm install
npm start

Moniteur d'activité

Affiche un diagramme en beignet du temps d'activité du CPU, de l'utilisateur et d'inactivité.

Capture d'écran

Hachage

Affiche les valeurs de hachage du texte saisi en utilisant différents algorithmes.

capture d'écran

Miroir

Lit une vidéo de la caméra de l'ordinateur à une taille maximale, comme si vous regardiez dans un miroir. Inclut un effet de filtre arc-en-ciel optionnel qui utilise des animations CSS.

Prix

Affiche le prix actuel du pétrole, de l'or et de l'argent à l'aide de l'API Yahoo Finance.

capture d'écran

URL

Charge une URL passée à la ligne de commande dans une fenêtre.

Autres ressources

Nous espérons que ces applications vous aideront à démarrer avec Electron. Nous vous proposons également ces quelques autres ressources pour en apprendre plus :

Electron Userland

· 4 mins de lecture

Nous avons ajouté une nouvelle section userland au site Web d'Electron pour aider les utilisateurs à découvrir les gens, les packages et les applications qui composent notre écosystème open-source florissant.


contributeurs de GitHub

Origines du Userland

Userland est l'endroit où les gens dans les communautés de logiciels se réunissent pour partager des outils et des idées. Le terme est originaire de la communauté Unix, où il fait référence à tout programme qui s'est exécuté en dehors du noyau, mais aujourd'hui, cela signifie quelque chose de plus. Lorsque les membres de la communauté Javascript d’aujourd’hui se réfèrent à userland, ils parlent généralement du registre des paquets npm. C'est là que la majorité des expériences et l'innovation se produisent, alors que Node et le langage JavaScript (comme le noyau Unix) conservent un ensemble relativement petit et stable de fonctionnalités de base.

Node et Electron

Comme Node, Electron a un petit ensemble d’API de base. Celui ci fournit les fonctionnalités de base nécessaires au développement d'applications de bureau multi-plates-formes. Cette philosophie de conception permet à Electron de rester un outil flexible sans être trop normatif sur la manière dont il devrait être utilisé.

Userland est le pendant du « core », permettant aux utilisateurs de créer et de partager des outils qui étendent les fonctionnalités d’Electron.

Collecte des données d’utilisation

Pour mieux comprendre les tendances de notre écosystème, nous avons analysé les métadonnées de 15 000 dépôts GitHub publics qui dépendent de electron ou electron-prebuilt

Nous avons utilisé les bibliothèques GitHub API, libraries.io API, et le registre npm pour récupérer des informations sur les dépendances, dépendances de développement, dépendants, auteurs de package, contributeurs de dépôts, compteurs de téléchargement, compteurs de fork, compteurs de stargazer etc.

Nous avons ensuite utilisé ces données pour générer les rapports suivants :

Filtrage des résultats

Des rapports tels que les dépendances d’applications et les applications étoilées qui répertorient les packages, les applications et les repos ont une entrée de texte qui peut être utilisée pour filtrer les résultats.

Lorsque vous tapez dans cette entrée, l'URL de la page est mise à jour dynamiquement. Ceci permet de copier une URL représentant une tranche particulière de données de l'espace utilisateur, puis de la partager avec d'autres.

babel

Plus d'infos à venir

Ce premier ensemble de rapports n'est que le début. Nous continuerons à collecter des données sur la façon dont la communauté construit Electron, et nous ajouterons de nouveaux rapports au site web.

Tous les outils utilisés pour collecter et afficher ces données sont open-source:

Si vous avez des idées sur la façon d'améliorer ces rapports, veuillez nous faire savoir en déclarant un problème sur le dépôt du site web ou l'un des dépôts susmentionnés.

Merci à vous, la communauté Electron, d’avoir fait de userland ce qu’il est aujourd’hui !

Certificate Transparency Fix

· 2 mins de lecture

Electron 1.4. 2 contient une mise à jour importante qui corrige un problème de Chrome amont où certains Symantec, GeoTrust, et les certificats Thawte SSL/TLS sont incorrectement rejetés 10 semaines à partir de la date de construction de libchromiumcontent, la bibliothèque Chrome sous-jacente d'Electron. There are no issues with the certificates used on the affected sites and replacing these certificates will not help.


In Electron 1.4.0 — 1.4.11 HTTPS requests to sites using these affected certificates will fail with network errors after a certain date. This affects HTTPS requests made using Chrome's underlying networking APIs such as window.fetch, Ajax requests, Electron's net API, BrowserWindow.loadURL, webContents.loadURL, the src attribute on a <webview> tag, and others.

Upgrading your applications to 1.4.12 will prevent these request failures from occurring.

Note: This issue was introduced in Chrome 53 so Electron versions earlier than 1.4.0 are not affected.

Impact Dates

Below is a table of each Electron 1.4 version and the date when requests to sites using these affected certificates will start to fail.

Electron VersionImpact Date
1.3.xUnaffected
1.4.0Already failing
1.4.1Already failing
1.4.2Already failing
1.4.3December 10th, 2016 9:00 PM PST
1.4.4December 10th, 2016 9:00 PM PST
1.4.5December 10th, 2016 9:00 PM PST
1.4.6January 14th, 2017 9:00 PM PST
1.4.7January 14th, 2017 9:00 PM PST
1.4.8January 14th, 2017 9:00 PM PST
1.4.9January 14th, 2017 9:00 PM PST
1.4.10January 14th, 2017 9:00 PM PST
1.4.11February 11th, 2017 9:00 PM PST
1.4.12Unaffected

You can verify your app's impact date by setting your computer's clock ahead and then check to see if https://symbeta.symantec.com/welcome/ successfully loads from it.

More Information

You can read more about this topic, the original issue, and the fix at the following places:

Septembre 2016 : Nouvelles applications

· 3 mins de lecture

Voici les nouvelles applications et conférences d'Electron qui ont été ajoutées au site en septembre.


This site is updated with new apps and meetups through pull requests from the community. Vous pouvez surveiller le dépôt pour être informé des nouveaux ajouts ou, si vous n'êtes pas intéressé par toutes les modifications du site, vous pouvez vous abonner au fil RSS du blog.

Si vous avez créé une application Electron ou si vous organisez une réunion, faites une requête pour l'ajouter au site et elle fera partie du prochain regroupement.

Nouvelles discussions

En septembre, GitHub a tenu sa conférence GitHub Universe présentée comme l'événement pour les personnes qui construisent l'avenir des logiciels. Il y a eu quelques présentations intéressantes d'Electron lors de l'événement.

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

Nouvelles applications

PexelsSearch for completely free photos and copy them into your clipboard
TimestampA 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
SoubeSimple music player
(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

Les documents de l'API d’Electron en tant que données structurées

· 4 mins de lecture

Nous annonçons aujourd’hui, quelques améliorations de la documentation d’Electron. Chaque nouvelle version inclut désormais un fichier JSON décrivant en détail toutes les API publiques d’Electron. Nous avons créé ce fichier pour permettre aux développeurs d’utiliser la documentation de l’API d’Electron de manière plus intéressante.


Aperçu du schéma

Chaque API est un objet avec des propriétés telles que nom, description, type, etc. Les classes telles que BrowserWindow et Menu ont des propriétés supplémentaires décrivant leurs méthodes d’instance, propriétés d’instance, événements d’instance, etc.

Voici un extrait du schéma décrivant la classe BrowserWindow:

{
nom: 'BrowserWindow', description
: 'Créer et contrôler les fenêtres du navigateur.', processus
: {
main: true,
renderer: false
}, type
: 'Class',
instanceName: 'win',
slug: 'browser-window',
websiteUrl: 'https://electronjs.org/docs/api/browser-window',
repoUrl: 'https://github.com/electron/electron/blob/v1.4.0/docs/api/browser-window.md',
staticMethods: [...],
instanceMethods: [...],
instanceProperties: [...],
instanceEvents: [...]
}

Et cet autre exemple exemple de description dune méthode, ici, la méthode d'instance apis.BrowserWindow.instanceMethods.setMaximumSize:

{
name: 'setMaximumSize',
signature: '(width, height)',
description: 'Sets the maximum size of window to width and height.',
parameters: [{
name: 'width',
type: 'Integer'
}, {
name: 'height',
type: 'Integer'
}]
}

Utilisation de ces nouvelles données

Pour faciliter l'utilisation de ces données structurées dans leurs projets par les développeurs, nous avons créé electron-docs-api, un petit package npm publié automatiquement chaque fois qu'il y a une nouvelle version d'Electron .

npm install electron-api-docs --save

Pour une appréciation rapide, essayez le module dans votre REPL Node.js :

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

Comment les données sont collectées

La documentation API d'Electron adhère à Electron Coding Style et au Electron Styleguide et donc son contenu peut être analysé par programme.

Le electron-docs-linter est une nouvelle dépendance de développement du dépôt electron/electron. C'est un outil en ligne de commande qui effectue un lint de tous les fichiers markdown et applique les règles du styleguide. Si des erreurs sont trouvées, elles sont listées et le processus de publication est interrompu. Si les docs de l'API sont valides, le fichier electron-json.api est créé et téléchargé sur GitHub pour être inclus dans la version d'Electron.

Javascript standard et Markdown standard

Plus tôt dans l'année, la base de code d'Electron a été mise à jour pour utiliser le linter standard pour tout JavaScript. Le README de Standard résume le raisonnement derrière ce choix :

L'adoption d'un style standard donne plus dl'importance à la clarté du code et des conventions communautaires que le style personnel. Cela n'est peut être pas judicieux pour 100 % des projets et des cultures de développement, toutefois l'open source peut être un environnement hostile pour les débutants. La mise en place d’attentes claires et automatisées des contributeurs rend un projet plus sain.

Nous avons également récemment créé markdown-standard pour vérifier que tous les snippets de code JavaScript de notre documentation sont valides et cohérents avec le style de la base de code elle-même.

Ensemble, ces outils nous aident à utiliser l'intégration continue (CI) pour trouver automatiquement des erreurs dans les pull requests. Cela réduit le fardeau imposé aux humains qui effectuent la revue du code et nous donne plus de confiance quant à l’exactitude de notre documentation.

Un effort de la communauté

La documentation d’Electron s’améliore constamment, et nous devons remercier notre formidable communauté open-source pour cela. Au moment d’écrire ces lignes, près de 300 personnes ont contribué aux documents.

Nous sommes heureux de voir ce que les gens font avec ces nouvelles données structurées. Utilisations possibles:

Electron Internals: Weak References

· 6 mins de lecture

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.

Un autre exemple est le problème de disparition de fenêtre, qui montre visuellement comment la fenêtre est des ordures collectées quand toutes les références à lui sont terminées.

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:

// Le code ci-dessous ne peut s'exécuter que sur 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 exemple est le module distantd'Electron, , qui est un module d'appel à distance (RPC) qui permet d'utiliser des objets dans le processus principal à partir des processus de rendu.

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. Whenever an object is requested, a message is sent to the main process and Electron will store the object in a map and assign an ID for it, then send the ID back to the 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;
};

Dans le processus principal :

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
}

Notez que le remoteObjectCache conserve des objets comme des références faibles, il n’est donc pas nécessaire de supprimer la clé lorsque l’objet est collecté par le garbage collector.

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:

Août 2016 : Nouvelles applications

· 3 mins de lecture

Voici les nouvelles applications Electron qui ont été ajoutées sur le site en août.


The site is updated with new apps and meetups through pull requests from the community. Vous pouvez surveiller le dépôt pour être informé des nouveaux ajouts ou, si vous n'êtes pas intéressé par toutes les modifications du site, vous pouvez vous abonner au fil RSS du blog.

Si vous avez créé une application Electron ou si vous organisez une réunion, faites une requête pour l'ajouter au site et elle fera partie du prochain regroupement.

Nouvelles applications

Code RPGifyRPG style coding application
PamFaxA cross-platform app for sending and receiving faxes
BlankUpMarkdown editor witch clarity +1
RamboxFree and Open Source messaging and emailing app that combines common web applications into one
GordieThe best app for your card collections
Ionic CreatorBuild amazing mobile apps, faster
TwitchAlertsKeep your viewers happy with beautiful alerts and notifications
MuseeksA simple, clean and cross-platform music player
SeaPigA converter from markdown to html
GroupMeUnofficial GroupMe App
MoeditorYour all-purpose markdown editor
SoundnodeSoundnode App is the Soundcloud for desktop
QMUI WebQMUI Web Desktop is an application for managing projects based on QMUI Web Framework
SvgsusOrganize, clean and transform your SVGs
RammeUnofficial Instagram Desktop App
InsomniaREST API Client
CorreoA menubar/taskbar Gmail App for Windows, macOS and Linux
KongDashDesktop client for Kong Admin API
Translation EditorTranslation files editor for INTL ICU messages (see formatjsio)
5EClient5EPlay CSGO Client
Theme JuiceLocal WordPress development made easy