Windows subsystem for linux wslg preview

Enabling the Windows Subsystem for Linux to include support for Wayland and X server related scenarios - GitHub - microsoft/wslg: Enabling the Windows Subsystem for Linux to include support for Way...

Welcome to WSLg

WSLg is short for Windows Subsystem for Linux GUI and the purpose of the project is to enable support for running Linux GUI applications (X11 and Wayland) on Windows in a fully integrated desktop experience.

WSLg provides an integrated experience for developers, scientists or enthusiasts that prefer or need to run Windows on their PC but also need the ability to run tools or applications which works best, or exclusively, in a Linux environment. While users can accomplish this today using a multiple system setup, with individual PC dedicated to Windows and Linux, virtual machine hosting either Windows or Linux, or an XServer running on Windows and projected into WSL, WSLg provides a more integrated, user friendly and productive alternative.

WSLg strives to make Linux GUI applications feel native and natural to use on Windows. From integration into the Start Menu for launch to appearing in the task bar, alt-tab experience to enabling cut/paste across Windows and Linux applications, WSLg enables a seamless desktop experience and workflow leveraging Windows and Linux applications.

WSLg Integrated Desktop

Installing WSLg

Pre-requisites

  • WSLg is supported on both Windows 11 and Windows 10. Windows 10 users must ensure their Windows 10 installation is fully up to date by visiting Windows Update and installing all available updates.

  • WSLg is available both as part of the Windows 11 WSL inbox support as well as through the Windows Subsystem for Linux from the Microsoft Store. It is highly recommended to use the Microsoft Store version of WSL, which supports both Windows 10 and Windows 11, and contains the most up to date version of WSL and WSLg.

  • Make sure to update your graphics driver to the latest driver available from your GPU manufacturer’s website to benefit from GPU acceleration in your WSL environment.

Install instructions (Fresh Install — no prior WSL installation)

From a command prompt with administrator privileges, run the command wsl --install -d Ubuntu, then reboot if prompted.

After reboot the installation will continue. You’ll be asked to enter a username and password. These will be your Linux credentials, they can be anything you want and don’t have to match your Windows credentials.

Voilà! WSL and WSLg are installed and ready to be used!

Install instructions (Existing WSL install)

If you have an existing WSL installation without WSLg and want to update to the latest version of WSL which includes WSLg, run the command wsl --update from an elevated command prompt.

Please note that WSLg is only compatible with WSL 2 and will not work for WSL distribution configured to work in WSL 1 mode. Verify that your Linux distro is configured for running in WSL 2 mode, if not switch to WSL 2. While you can continue to run Linux distro in WSL 1 mode after installing WSLg if you so desired, a distro configured to run in WSL 1 mode will not be able to communicate with WSLg and will not be able to run GUI applications.

You can list your currently installed distro and the version of WSL they are configured for using the following command from an elevated command prompt.

If running in version 1 mode, switch to version 2. This can take a while.

   wsl --set-version _distro_name_ 2

Restart WSL by running this command from an elevated command prompt, make sure to save any pending work first:

Updating WSL + WSLg

To update to the latest version of WSL and WSLg released for preview, simply run wsl --update from an elevated command prompt or powershell.

You’ll need to restart WSL for the changes to take effect. You can restart WSL by running wsl --shutdown from an elevated command prompt. If WSL was currently running, it will shutdown, make sure to first save any in progress work! WSL will be automatically restarted the next time you launch a WSL application or terminal.

First Launch

If you have installed the Ubuntu Linux distro per these instructions, you’ll find an Ubuntu icon in your start menu, launch it. This will launch the WSL 2 VM, launch the Ubuntu WSL distro in that VM and give you a terminal to interact with it. Voilà! You’re running Linux on Windows!

If you would like to explore additional Linux distributions built for WSL, you can use the wsl --list --online command from an elevated command prompt to enumerate the list of available distributions for your system. You can have multiple Linux distributions installed within WSL and they will happily coexist side-by-side, so don’t be scared to experiment and try things out.

Congrats you are done and ready to use GUI apps!

Install and run GUI apps

If you want to get started with some GUI apps, you can run the following commands from your Linux terminal to download and install some popular applications. If you are using a different distribution than Ubuntu, it may be using a different package manager.

## Update list of available packages
sudo apt update

## Gedit
sudo apt install gedit -y

## GIMP
sudo apt install gimp -y

## Nautilus
sudo apt install nautilus -y

## VLC
sudo apt install vlc -y

## X11 apps
sudo apt install x11-apps -y

## Google Chrome
cd /tmp
sudo wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb 
sudo apt install --fix-broken -y
sudo dpkg -i google-chrome-stable_current_amd64.deb

## Microsoft Teams
cd /tmp
sudo curl -L -o "./teams.deb" "https://teams.microsoft.com/downloads/desktopurl?env=production&plat=linux&arch=x64&download=true&linuxArchiveType=deb"
sudo apt install ./teams.deb -y

## Microsoft Edge Dev Browser
sudo curl https://packages.microsoft.com/repos/edge/pool/main/m/microsoft-edge-dev/microsoft-edge-dev_101.0.1193.0-1_amd64.deb -o /tmp/edge.deb
sudo apt install /tmp/edge.deb -y

Once these applications are installed, you’ll find them in your start menu under the distro name. For example Ubuntu -> Microsoft Edge. You can also launch these from your terminal window using the commands:

  • xcalc, xclock, xeyes
  • gimp
  • gedit ~/.bashrc
  • nautilus
  • vlc
  • google-chrome
  • teams
  • microsoft-edge

WSLg Architecture Overview

WSLg Architecture Overview

User Distro

The user distro is essentially the WSL distribution you are using for your Linux work. You can use the command wsl --list --online from an elevated Windows command prompt to list the WSL distributions available on your system. You can run multiple user distros side-by-side and they will peacefully coexist, so don’t be afraid of trying out new distro. Each user distro will be paired with a unique instance of the system distro, but you can still interact across GUI applications running in different user distro seamlessly, such as cut/paste between them. The underlying containerization of the various userspace should be invisible to you.

All user and system distros for a particular Windows user run within the same WSL virtual machine against a single instance of the Linux kernel. Different Windows users on a PC have their own VM and instance of WSL. Your Linux environment is guaranteed to always be your own and not shared with other Windows users on the same PC.

WSLg System Distro

The system distro is where all of the magic happens. The system distro is a containerized Linux environment where the WSLg XServer, Wayland server and Pulse Audio server are running. Communication socket for each of these servers are projected into the user distro so client applications can connect to them. We preconfigure the user distro environment variables DISPLAY, WAYLAND_DISPLAY and PULSE_SERVER to refer these servers by default so WSLg lights up out of the box.

Users wanting to use different servers than the one provided by WSLg can change these environment variables. User can also choose to turn off the system distro entirely by adding the following entry in their .wslconfig file (located at c:usersMyUser.wslconfig). This will turn off support for GUI applications in WSL.

[wsl2]
guiApplications=false

The system distro is based on the Microsoft CBL-Mariner Linux. This is a minimal Linux environment, just enough to run the various pieces of WSLg. For details on how to build and deploy a private system distro please see our build instructions.

Every WSL 2 user distro is paired with its own instance of the system distro. The system distro runs partially isolated from the user distro to which it is paired, in its own NS/PID/UTS namespace but shares other namespaces such as IPC, to allow for shared memory optimization across the boundary.

While a user can get a terminal into the system distro, the system distro is not meant to be used directly by users. Every instance of the system distro is loaded read-only from its backing VHD. Any modifications, made to the in-memory instance of the system distro (such as installing new packages or creating a new file), are effectively discarded when WSL is restarted. The reason we do this is to enable a servicing model for the system distro where we replace the old one with the new one without having to worry about migrating any user data contained within. We use a read-only mapping such that the user gets a well known discard behavior on any changes, every time WSL is restarted, instead of getting a surprise when WSL is serviced.

Although the Microsoft published WSLg system distro as read-only, we do want to encourage folks to tinker with it and experiment. Although we expect very few folks to actually need or want to do that, we’ve shared detailed instruction on our contributing page on how to both build and deploy a private version of the system distro. Most users who just want to use GUI applications in WSL don’t need to worry about those details.

WSLGd

WSLGd is the first process to launch after init. WSLGd launches Weston (with XWayland), PulseAudio and establishes the RDP connection by launching mstsc.exe on the host in silent mode. The RDP connection will remain active and ready to show a new GUI applications being launch on a moment’s notice, without any connection establishment delays. WSLGd then monitors these processes and if they exit by error (say as a result of a crash), it automatically restarts them.

Weston

Weston is the Wayland project reference compositor and the heart of WSLg. For WSLg, we’ve extended the existing RDP backend of libweston to teach it how to remote applications rather than monitor/desktop. We’ve also added various functionality to it, such as support for multi-monitor, cut/paste, audio in/out, etc…

The application integration is achieved through an RDP technology called RAIL (Remote Application Integrated Locally) and VAIL (Virtualized Application Integrated Locally). The main difference between RAIL and VAIL is how pixels are transported across from the RDP server to the RDP client. In RAIL, it is assumed that the Server and Client are running on different physical systems communicating over the network and thus pixels need to be copied over the RDP transport. In VAIL, it is understood that the Server and Client are on the same physical system and can share memory across the Guest/Host VM boundary. We’ve added support for both RAIL and VAIL to the libweston RDP backend, although for WSLg only the VAIL support is effectively used. While building WSLg, we first implemented RAIL while the necessary pieces enabling the switch to VAIL were being developed in parallel. We decided to keep that support in as it could reuse in other interesting scenarios outside of WSLg, for example for remoting application from a Pi running Linux. To share memory between the Linux guest and Windows host we use virtio-fs.

RAIL-Shell

Weston is modular and has various shells today, such as the desktop shell, fullscreen shell (aka kiosk), and automative shell. For WSLg we introduced a new shell called the RAIL Shell. The purpose of the RAIL Shell is to help with the remoting of individual windows from Linux to Windows, as such the shell is very simplistic and doesn’t involve any actual widgets or shell owned pixels.

FreeRDP

Weston leverages FreeRDP to implement its backend RDP Server. FreeRDP is used to encode all communications going from the RDP Server (in Weston) to the RDP Client (mstsc on Windows) according to the RDP protocol specifications. It is also used to decode all traffic coming from the RDP Client into the RDP server.

Pulse Audio Plugin

For audio in (microphone) and out (speakers/headphone) WSLg runs a PulseAudio server. WSLg uses a sink plugin for audio out, and a source plugin for audio in. These plugins effectively transfer audio samples between the PulseServer and the Weston RDP Server. The audio streams are merged by the Weston RDP Server onto the RDP transport, effectively enabling audio in/out in the Weston RDP backend across all scenarios (Desktop/RAIL/VAIL style remoting), including WSLg.

WSL Dynamic Virtual Channel Plugin (WSLDVCPlugin)

WSLg makes use of a custom RDP virtual channel between the Weston RDP Server and the mstsc RDP Client running on the Windows host. This channel is used by Weston to enumerate all Linux GUI applications (i.e. applications which have a desktop file entry of type gui) along with their launch command line and icon. The open source WSLDVCPlugin processes the list of Linux GUI applications sent over this channel and creates links for them in the Windows start menu.

OpenGL accelerated rendering in WSLg

While WSLg works with or without virtual GPU support, if you intend to run graphics intensive applications such as Blender or Gazebo, it is best to be running on a system with a GPU and driver that can support WSL. An overview of our vGPU architecture and how we make it possible for Linux applications to access the GPU in WSL is available at our DirectX blog.

Support for OpenGL accelerated rendering is made possible through the work our D3D team has done with Collabora and the Mesa community on creating a d3d12 Gallium driver.

Support for Linux, including support for WSLg, has been upstream and part of the Mesa 21.0 release. To take advantage of this acceleration, you’ll need to update the version of Mesa installed in your user distro. It also requires that your distro vendor chose to build and publish the new d3d12 Gallium driver to their package repository. We’re working with the various WSL distro publishers to inform them of these changes.

Please note that for the first release of WSLg, vGPU interops with the Weston compositor through system memory. If running on a discrete GPU, this effectively means that the rendered data is copied from VRAM to system memory before being presented to the compositor within WSLg, and uploaded onto the GPU again on the Windows side. As a result, there is a performance penalty proportionate to the presentation rate. At very high frame rates such as 600fps on a discrete GPU, that overhead can be as high as 50%. At lower frame rate or on integrated GPU, performance much closer to native can be achieved depending on the workload. Using a vGPU still provides a very significant performance and experience improvement over using a software renderer despite this v1 limitation.

WSLg Code Flow

WSLg builds on the great work of the Linux community and makes use of a large number of open source projects. Most components are used as-is from their upstream version and didn’t require any changes to light up in WSLg. Some components at the heart of WSLg, in particular Weston, FreeRDP and PulseAudio, required changes to enable the rich WSLg integration. These changes aren’t yet upstream. Microsoft is working with the community to share these contributions back with each project such that, over time, WSLg can be built from upstream component directly, without the need for any WSLg specific modifications.

All of these in-flight contributions are kept in Microsoft mirror repos. We keep these mirrors up to date with upstream releases and stage our WSLg changes in those repos. WSLg pulls and builds code from these mirror repos as part of our Insider WSLg Preview releases. These mirrors are public and accessible to everyone. Curious developers can take a peek at early stages of our contribution by looking at code in those mirrors, keeping in mind that the final version of the code will likely look different once the contribution reaches the upstream project and is adapted based on the feedback receives by the various project owners. All of our mirrors follow the same model. There is a main branch which correspond to the upstream branch at our last synchronization point. We update the main branch from time to time to pick update from the upstream project. There is also a working branch that contains all of our in-flight changes. WSLg is built using the working branch from each of the mirror projects.

The projects that WSLg maintains mirrors for will change over time as in-flight contributions evolve. Once some contributions are upstream, it may no longer be necessary to maintain a mirror, at which point it will be removed and WSLg will start to leverage the upstream version of the component directly. As we light up new functionality in WSLg, new mirrors may be introduced to stage contributions to new components. As such, expect the list of mirrors to change overtime.

At this point in time, we have the following project mirrors for currently in-flight contributions.

Project Upstream Repo WSLg Mirror
Weston https://github.com/wayland-project/weston https://github.com/microsoft/Weston-mirror
FreeRDP https://github.com/FreeRDP/FreeRDP https://github.com/microsoft/FreeRDP-mirror
PulseAudio https://github.com/pulseaudio/pulseaudio https://github.com/microsoft/PulseAudio-mirror

The following is a high level overview of the currently in-flight contributions to each project contained within these mirrors.

Weston

WSLg leverages Weston as the Wayland compositor bridging the Linux and Windows worlds using RDP technology to remote application content between them. Weston already had an RDP backend, but it was limited to single-monitor-desktop remoting. We’ve greatly enhanced that RDP backend to include advanced functionality, such as multi-monitor support, clipboard integration for copy/paste, and audio in/out. We’ve enabled new remoting modes called RAIL (Remote Application Integrated Locally) and VAIL (Virtualized Application Integrated Locally), where individual applications, rather than desktops/monitors, are remoted. These changes are not specific to WSLg; they add functionality to the existing RDP backend and are reusable in other scenarios as well (i.e. using the new Weston RDP backend to remote application running on a Raspberry Pi to another device running an RDP client).

To enable rich integration in WSLg, we’ve also added a small plugin to the RDP backend specific to WSLg. In Weston, the plugin is responsible for attaching to the user distro and searching for installed applications (aka the desktop file). The plugin sends the Windows host a list of all applications found along with their launch commands and icons. On the Windows host, an open source mstsc plugin part of the WSLg project uses that information to create shortcuts for these Linux applications to the Windows Start Menu.

We’ve also fixed several bugs impacting various applications. Generally, these were problems that impacted Weston in all modes and were not specific to WSLg.

FreeRDP

Weston currently uses FreeRDP for its RDP Backend. WSLg continues to leverage FreeRDP and we have added support for a new RDP Protocol/Channel to enable VAIL optimized scenario as well as support for the WSLg plugin. We’ve also fixed various bugs that were impacting interops with mstsc or causing instability.

PulseAudio

For PulseAudio, our contributions focused on a sink and a source plugin that shuffle audio data between PulseAudio and the Weston RDP backend such that the audio data can be integrated over the RDP connection back to the host. There are no changes to the core of PulseAudio outside of adding these new plugins.

Contributing

If you would like to tinker with or contribute to WSLg, please see our CONTRIBUTING page for details, including how to build and run private a version of WSLg.

Reporting a non-security issues

For non-security related issues, such as reporting a bug or making a suggestion for a new feature, please use this project’s issues tracker.

Reporting security issues

To report security issues with WSLg or any other Microsoft products, please follow the instructions detailed here.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft’s Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party’s policies.

April 21st, 2021

A year ago at BUILD 2020 we introduced our goal to bring Linux GUI applications to the Windows Subsystem for Linux (WSL) to run Linux GUI applications. We are proud to announce the first preview of this highly anticipated and open source feature! We’ve given this feature the nickname: “WSLg”. Please check out the video below or keep reading to see what you can use this feature for, how it works, and how to install it.

What can I use GUI application support for?

WSL lets you run a Linux environment, and up until this point has focused on enabling command line tools utilities and applications. GUI app support now lets you use your favorite Linux GUI applications as well. WSL is used in a wide variety of applications, workloads, and use cases, so ultimately, it’s up to you on what you’d like to use GUI app support for. Below, we’ve highlighted some key scenarios to help you fall in love with running applications in a Linux environment.

Use your IDE of choice to develop Linux projects

Visual Studio Code has an amazing experience using VS Code Remote to create a way for you to have a full-fledged Linux IDE directly on your Windows machine, keep extensions and settings across both Windows and different WSL distros (you can view our getting started with VS Code tutorial here. WSLg will let you run other IDEs such as gedit, JetBrains based editors, gvim, etc., to test, build, and debug your Linux applications in a performant manner.

Here’s an example of running gedit and gvim to edit Linux files directly in WSL.

GUI Apps Editor GIf

Run Linux only applications, or Linux specific use cases like testing

You can use this feature to run any GUI application that might only exist in Linux, or to run your own applications or testing in a Linux environment. This could be incredibly useful for developers who want to test their cross-platform app, as they can now run it directly on Windows 10, and then easily inside of Linux without ever needing to change machines or manage a virtual machine.

Let’s look at an example of running TestCafe Studio in WSL to do some web testing from a Microsoft Edge browser running in Linux.

Linux GUI apps testing

Build, test and use Linux applications that use audio or the microphone with built in audio support

Linux GUI applications on WSL will also include out of the box audio and microphone support. This exciting aspect will let your apps play audio cues and utilize the microphone, perfect for building, testing, or using movie players, telecommunication apps, and more.

Here’s an example of using Audacity running on Linux to record some audio and play it back.

Audio Linux GUI apps

Bonus: Leverage WSL’s GPU access to run Linux applications with 3D acceleration

As part of this feature, we have also enabled support for GPU accelerated 3D graphics! Thanks to work that was completed in Mesa 21.0, any applications that are doing complex 3D rendering can leverage OpenGL to accelerate these using the GPU on your Windows 10 machine. This will make some of your more complex applications run smoothly, such as running Gazebo, a robotics simulation tool. This experience will soon be included by default with different WSL distributions, however you can gain access to it right away by following the instructions in this blog post to get the right graphics driver and to ensure your distro has a compatible Mesa version..

Below you can see the Gazebo application simulating a robot exploring a virtual cave, as well as the Rviz application visualizing the camera feed of the robot and its laser field sensor’s output. Thanks to GPU accelerated 3D graphics we can run this demo at 60 FPS!

Image GUIAppsBlogPostDemo GIF4 ROS

How does this feature work?

From the demos above, you might have noticed we didn’t need to start an X server manually. That’s because with this feature we are automatically starting a companion system distro, containing a Wayland, X server, pulse audio server, and everything else needed to make Linux GUI apps communicate with Windows. After you’re finished using GUI applications and terminate your WSL distribution the system distro will automatically end its session as well.

Like with the rest of WSL plumbing, our intention is for this component to be fully managed and seamless for users. Our intentions are for this system distro to be as invisible to the user as possible, and this is why you won’t see this system distro when you run wsl -l -v. Lastly, we’re excited to present that we are using Microsoft’s CBL-Mariner distribution for this system distro! CBL-Mariner is an internal Linux distribution used traditionally for Microsoft’s cloud infrastructure and edge products and services, and we are now extending its use to support GUI apps inside of WSL. You can view the diagram below to see an overall summary of the architecture of this feature.

Image WSLg ArchitectureOverview

For a full in depth view of what we did to make this feature possible and the deep technical details, please view this blog post written by the developers who made this feature possible.

Getting started with this feature

We are starting the rollout of this feature as an initial preview before we fully roll it into the WSL experience. To get started using Linux GUI app support, you’ll need to make sure you’re on Windows 10 Insiders preview build 21364 or higher. If you already have WSL installed, all you need to do is run wsl --update and you’ll be set to use GUI apps. If you don’t have WSL enabled, running wsl --install will install WSLg automatically as part of the initial WSL setup.

You can find the full install instructions at the GitHub repositories’ README: https://github.com/microsoft/wslg . We also highly recommend that you have GPU compute support enabled in WSL for the best performance, please see this section of the install instructions to see how you can ensure that feature is enabled.

Feedback

Please file any technical issues, or feature requests for GUI application support on the WSLg Github repository. For general WSL issues, please file them at the WSL repository. You can also follow up with me on Twitter @craigaloewen and all WSL team members that are on Twitter using this list. Please stay tuned to this blog for more exciting WSL announcements, and we can’t wait to hear what you think about this new feature.

Windows Subsystem for Linux (WSL) — очень полезная возможность, которую Microsoft добавила в Windows 10 в 2017 году. Она позволяет разработчикам запускать среды GNU/Linux непосредственно в Windows, не требуя виртуальных машин (VM) или конфигураций с двойной загрузкой. Конечно, эта функция присутствует и в Windows 11. Ранее для включения WSL использовалось диалоговое окно «Включение или отключение компонентов Windows», но теперь Microsoft выпустила специальное приложение для WSL через Microsoft Store в Windows 11.

Приложение WSL в настоящее время доступно в виде предварительной версии в Microsoft Store для Windows 11. Microsoft отметила, что распространение WSL с помощью этого метода дает два взаимосвязанных преимущества. Во-первых, вы получите доступ к функциям быстрее, поскольку WSL можно обновлять прямо из магазина. Это также тесно связано со вторым преимуществом, когда WSL отделена от компонента Windows, а это означает, что вам не придется обновлять или изменять установку Windows только потому, что WSL получает новые функции.

Microsoft отметила, что она уже добавила некоторые новые возможности в предварительную версию WSL в Microsoft Store. Это:

• WSLg теперь входит в состав приложения WSL!;
• Новые функции wsl.exe —mount!;
• Добавляйте —mount —vhd, чтобы упростить монтирование файлов VHD;
• Реализуйте обнаружение файловой системы для wsl —mount. Это изменение реализует определение типа файловой системы, если при использовании wsl.exe —mount не указан —type;
• Добавляйте функцию —name в wsl —mount. Это изменение добавляет поддержку для необязательного наименования точки монтирования при монтировании диска через WSL;
• Ядро Linux обновлено до версии 5.10.60.1;
• Добавлена вспомогательная функция индикатора выполнения, используемая для отображения сообщения «Пожалуйста, подождите» с анимированными точками в процессе преобразования, чтобы показать пользователям, что WSL все еще работает;
• Переключено wsl —install, чтобы не требовать аргумент —distribution. Это изменение переключает wsl —install, чтобы не требовать аргумент —distribution, но поддерживает поддержку, чтобы избежать нарушения существующих сценариев.
• Добавлена команда wsl.exe —version, которая отображает соответствующую информацию о версии;

Важно отметить, что версия WSL для Windows и аналог WSL для Microsoft Store могут сосуществовать и будут иметь доступ к одним и тем же дистрибутивам. Однако вариант из Microsoft Store будет иметь приоритет. Можно использовать дистрибутивы WSL 1, но в качестве предварительного условия вам необходимо убедиться, что WSL также включена в Windows, поскольку связанный драйвер еще не отделен от ОС.

Интересно, что Microsoft отметила, что будет продвигать версию WSL для Microsoft Store как оптимальный способ задействовать эту возможность на вашем компьютере с Windows 11, поскольку это обеспечит более быструю частоту обновления. Однако те, кто использует версию для Windows, по-прежнему поддерживаются. Компания будет использовать отзывы, чтобы определить целесообразность включения WSL в образ Windows.

Вы можете загрузить

Windows Subsystem for Linux Preview из Microsoft Store для Windows 11 здесь

.

Security

As more apps are developed in Linux than ever before, Microsoft recognized that it needed to provide developers with an easy way to build, test, and run Linux apps without leaving the Windows desktop. The Windows Subsystem for Linux (WSL) was originally designed to provide an integrated Linux terminal environment in Windows without needing to set up and manage a virtual machine (VM).

But what if you want to run a Linux GUI editor, or other GUI app, using WSL?

Table of Contents

  • How to install a Linux GUI app in Windows 10 and Windows 11
  • Installing Linux GUI apps supported in Windows 10 21H2 and Windows 11
  • What can I do with WSL GUI app support?
  • How does WSL GUI app support work?
  • How to update WSL to support GUI apps
    • Update an existing WSL installation
    • Install WSL for the first time with GUI app support
  • Installing Linux GUI apps in Ubuntu
  • Starting Linux GUI apps and integration with the Windows UI
  • Linux GUI apps in Windows 10 and Windows 11

Microsoft announced on April 21st that WSL in Windows 10 Insider Preview Build 21364 now supports Linux GUI apps. So, using build 21364 and higher, developers can run their preferred GUI editors and tools for testing and building Linux apps without having to jump through hoops like installing an X Server.

In this article, I’ll show you how to update WSL to support GUI apps, how to install a GUI app in Ubuntu, and finally look at how GUI Linux apps are integrated with the Windows user interface.

How to install a Linux GUI app in Windows 10 and Windows 11

Here are the steps you need to follow to install a Linux GUI app in Windows 10 or Windows 11:

  1. Install WSL or update an existing WSL installation
  2. Install your Linux GUI app in Ubuntu or other supported Linux distribution
  3. Start your Linux GUI app from the Windows Start menu

For more detailed instructions, keep on reading!

Installing Linux GUI apps supported in Windows 10 21H2 and Windows 11

Windows 10 21H2 isn’t coming until the second half of 2021 but Microsoft is busy releasing previews to Insiders. Until recently, WSL only officially supported Linux terminal applications. But Microsoft recently came good on a promise it made last year to bring GUI app support to the Windows Subsystem for Linux (WSL).

If you don’t know, WSL 2 is a feature in Windows 10 that lets developers add a Linux kernel to Windows and then load terminal support for several Linux distributions, including Ubuntu and SUSE.

For more information on Microsoft’s announcement, check out Microsoft Brings Linux GUI Apps to Windows 10 on Petri.

What can I do with WSL GUI app support?

The primary use case for Linux GUI app support is to run IDEs that are only supported on Linux. While many developers use Visual Studio Code on Windows to connect to their Linux instances in WSL, some developers prefer to use Linux tools like gedit, JetBrains, and gvim.

There are other applications too that only run in Linux. WSL now lets developers run those apps without setting up a Linux VM. The new GUI app support in WSL, sometimes referred to as WSLg, also lets developers test cross-platform GUI apps. There’s even support for audio and microphone.

For resource-intensive graphics applications, WSLg supports 3D acceleration via OpenGL. GPU hardware acceleration can benefit developers running complex apps that take advantage of WSL’s virtual GPU.

If you want to experiment with 3d accelerated graphics in WSL, Microsoft says for the time being, you’ll need to manually download a WDDMv3.0 driver for AMD, Intel, and NVIDIA GPUs respectively. These drivers will eventually be deployed automatically using Windows Update.

How does WSL GUI app support work?

When you run a Linux GUI app, Windows automatically starts a companion Linux distribution that includes XWayland, a pulse audio server, and everything needed for Linux GUI apps to run on Windows. Linux GUI apps are integrated with the Windows UI and when you terminate an app, the Linux companion distro session also ends to reduce system resource usage.

WSL architecture diagram

How to Install Linux GUI Apps in Windows 10 21H2 with WSL (Image Credit: Microsoft)

WSLg supports Wayland and X11 GUI applications. Microsoft developed WSLg as an open-source application, but it is designed to work without needing any changes. WSLg is isolated from the user’s Linux distribution so that WSLg can be serviced independently.

The WSLg companion distro uses CBL-Mariner, a lightweight and customizable Linux distribution maintained by Microsoft’s Linux System Group. CBL-Mariner was originally designed for headless, containerized workloads running in Azure or Microsoft’s edge services.

How to update WSL to support GUI apps

If you have WSL already installed in Windows and are upgrading to Insider Preview Build 21364, then you’ll need to update your existing WSL installation to support WSLg.

Update an existing WSL installation

There are two simple steps to update WSL. First, shutdown any running distros and then update WSL using the wsl.exe command-line tool.

  • Open an elevated command prompt. In the search box in the bottom left of the taskbar, type cmd.
  • In the search results, make sure that Command Line is highlighted and in the panel on the right, click Run as administrator.
  • Give consent or type an administrator username and password as prompted.
  • In the command line window, run the following type commands.
wsl --shutdown
wsl --update

Update an existing WSL installation

How to Install Linux GUI Apps in Windows 10 21H2 with WSL (Image Credit: Russell Smith)

WSLg only supports WSL 2, so you’ll need to make sure any existing and future Linux distributions are configured to run in WSL 2. You can set existing distributions to use WSL 2 using the –set-version switch and by replacing distroname with the name of a Linux distribution installed on your PC. Use wsl –list -v to show the Linux distributions you have installed on your PC.

wsl --list -v
wsl --set-version distroname 2

Then restart WSL to complete the process:

wsl --shutdown

Install WSL for the first time with GUI app support

If you want to install WSL for the first time in Windows 10 Build 21364 or higher, then you just need to install WSL using the command line. WSLg support comes built-in. The command below installs WSL and then adds the Ubuntu distribution. You’ll be prompted to reboot your PC.

wsl --install -d Ubuntu

Installing Linux GUI apps in Ubuntu

Now launch your Linux distribution from the Windows Start menu. In this example, I’m using Ubuntu, so I’ll find the Ubuntu icon in the apps list on the Start menu. Clicking the Ubuntu icon launches an Ubuntu terminal window. Now install Linux GUI apps in the same way you would on any other Ubuntu distro.

For example, because Ubuntu is based on Debian, use the apt command to install apps. You’ll need to sudo the command to run it with elevated privileges in Linux. The first step is to update all my existing packages in Ubuntu:

sudo apt update

Here I use apt to install Nautilus, a GUI file manager for Linux:

sudo apt install nautilus -y

Installing Linux GUI apps in Ubuntu

How to Install Linux GUI Apps in Windows 10 21H2 with WSL (Image Credit: Russell Smith)

Another example is to install the preview version of Microsoft Edge for Linux. Here I need to download the package from Microsoft’s website and then run it using apt.

sudo curl https://packages.microsoft.com/repos/edge/pool/main/m/microsoft-edge-dev/microsoft-edge-dev_91.0.852.0-1_amd64.deb -o /tmp/edge.deb

sudo apt install /tmp/edge.deb -y

Starting Linux GUI apps and integration with the Windows UI

Once your chosen apps have been installed, you’ll find them in the apps list on the Windows Start menu. Launch your Linux GUI apps like you’d run any Windows app.

Starting Linux GUI apps and integration with the Windows UI

How to Install Linux GUI Apps in Windows 10 21H2 with WSL (Image Credit: Russell Smith)

Alternatively, you can launch GUI apps from your Linux terminal window. For example, to launch Nautilus from the terminal, I’d just type nautilus and press ENTER. Or microsoft-edge and press ENTER to run Microsoft Edge.

How to Install Linux GUI Apps in Windows 10 21H2 with WSL

How to Install Linux GUI Apps in Windows 10 21H2 with WSL (Image Credit: Russell Smith)

Edge is even identified as distinct from the version installed in Windows by the penguin in the bottom-right of the application icon.

How to Install Linux GUI Apps in Windows 10 21H2 with WSL

How to Install Linux GUI Apps in Windows 10 21H2 with WSL (Image Credit: Russell Smith)

Linux GUI apps in Windows 10 and Windows 11

WSLg is still a work in progress but it seems far along at this stage. Microsoft will be tweaking it in upcoming Insider builds before Windows 10 21H2 launches later in 2021. In my short time with it, WSLg seemed to work as expected. I didn’t install the virtual GPU graphics drivers as recommended by Microsoft. But even without them, everything seemed to work just fine.

If you can’t wait to get official support for Linux GUI apps in WSL, then you can switch to the Insider channel. Although these updates for WSL are currently only available to Insiders on the Dev Channel, which is considered the most unstable. So, you might want to wait until either the official 21H2 release or at least until WSLg makes it to the Beta or Release Preview Channels.

Related articles

  • How to Install WSL on Windows Server

Microsoft introduced support for graphical Linux programs on WSL (WSLg) with Windows 10 build 21364. Like the subsystem as a whole, this feature is primarily aimed at developers and admins, who can now find tools from both worlds on one system in a single interface.

Contents

  1. Wayland instead of X11
  2. Windows integration over RDP
  3. Installation of WSLg
  4. Adding graphical Linux programs
  5. Conclusion
  • Author
  • Recent Posts

Wolfgang Sommergut has over 20 years of experience in IT journalism. He has also worked as a system administrator and as a tech consultant. Today he runs the German publication WindowsPro.de.

The subsystem for Linux initially had only the goal of running a Linux shell, together with the most important command line tools, natively under Windows. With version 2, it made a big leap forward by getting its own Linux kernel running in a utility VM. In addition, it uses a native EXT4 file system.

In the fall of 2020, Microsoft announced plans to allow graphical Linux programs to run under WSL. The first publicly available version is now available as an early preview in build 21364 of Windows 10.

Wayland instead of X11

Traditionally, graphical Unix programs were based on X11, but most newer applications use the modern Wayland platform. Compatibility with X11 is ensured by XWayland.

Microsoft apparently considered remoting the Wayland protocol from Linux to the host OS and displaying the programs’ output there via a Wayland compositor developed specifically for Windows.

Instead, the manufacturer decided to use the Wayland reference implementation Weston and run it in its own WSL system distro. This is a CBL-Mariner that is maintained by Microsoft itself.

Windows integration over RDP

Weston has an RDP backend based on FreeRDP to display Linux programs via remote desktop. WSLg thus uses a mechanism similar to Hyper-V, where the VM console is displayed on the host OS desktop via RDP.

Microsoft upgraded Weston’s RDP capabilities with technologies used in Windows Virtual Desktop (remote application integrated locally, or RDP RAIL) and Application Guard (virtualized application integrated locally, or RDP VAIL).

The Wayland implementation based on Weston runs in the Linux VM and Windows integration is done via RDP

The Wayland implementation based on Weston runs in the Linux VM and Windows integration is done via RDP

They ensure that graphical Linux programs appear in their own windows on the Windows desktop. WSLg also supports multi-monitor configurations, audio input and output via a PulseAudio server, and copy/paste between Linux and Windows applications. There are also hardware-accelerated graphics on GPUs with support for WDDMv3.0.

An RDP plugin integrates Linux applications automatically into the Windows 10 Start menu, where Linux distros also show up once added under WSL.

Installation of WSLg

In newer versions, wsl.exe offers an extended set of commands, which also includes the —update parameter. If the subsystem for Linux is already installed, then you simply execute

wsl.exe --shutdown
wsl.exe --update

For a new installation, run

wsl.exe --install

The latter performs all the steps you had to do manually in the past, from enabling optional features to downloading the distribution. As an additional action, the tool now downloads and installs GUI app support.

The installation of WSL including support for GUI application is now completely handled by wsl.exe

The installation of WSL including support for GUI application is now completely handled by wsl.exe

If you do not use the -d switch to instruct the installation command as to which Linux you want, you will automatically get Ubuntu. You can find out which other distros are available via

wsl.exe -l -o

It is also important that you run the selected distribution under WSL 2; version 1 does not support WSLg. With the command

wsl.exe -l -v

you can see the version of all installed distros. If necessary, you can convert them with

wsl.exe --set-version <distro-name> 2

After completing this preliminary work, you will find an icon for the installed distros in the Start menu.

Installed distros and their applications appear in the Windows 10 Start menu

Installed distros and their applications appear in the Windows 10 Start menu

When you run Linux for the first time, WSL integrates it into the system. There, you have to set up an initial account and password.

During my test in a virtual machine, the registration of several distros failed with the error «The parameter is incorrect». Although the issue is known, currently there seems to be no solution. If you want to be able to use WSL2, at least without a GUI, create a file named .wslconfig in the user’s profile and add the following entry:

[wsl2]
guiapplications=false

Then restart the subsystem with

wsl.exe --shutdown

If WSL fails with an incorrect parameter message you can reactivate the subsystem via the configuration file

If WSL fails with an incorrect parameter message you can reactivate the subsystem via the configuration file

Adding graphical Linux programs

If you start up Linux, you don’t end up on the graphical desktop, as you are used to from a native installation on bare metal or in a VM. Rather, as before, only a command shell opens from which you first have to install GUI programs.

A package manager is used for this, as is common in Linux. In the case of Ubuntu, this is apt. First you update the package list with

sudo apt update

Then, you can start to install the desired applications. If you want to search for the right software first, you can do that using

apt search <search term>

For example, the popular editor gedit could be added like this:

apt install gedit

When a GUI program is first installed apt downloads a large number of dependencies

When a GUI program is first installed apt downloads a large number of dependencies

After the successful installation, an icon for the tool should appear in the Start menu.

Conclusion

The Linux subsystem is one of the most interesting Windows innovations in years for developers and DevOps. It offers tight integration of the two operating systems on several levels, such as the coexistence of file systems and the ability to start native Windows and Linux programs from the command line.

WSLg continues this development by being able to run graphical Linux programs seamlessly on the Windows desktop. This feature is primarily intended for developer tools rather than for setting up Libre Office for end users.

Subscribe to 4sysops newsletter!

The hardware acceleration of graphical operations, as well as the support for multi-monitor systems, show that Microsoft’s ambitions for the integration of Linux go further than just offering a makeshift solution for occasional use.

avatar

image

В новостях прошла весть, что теперь WSL поддерживает демон systemd. В качестве преимущества использования systemd предлагается установка и запуск приложений и сервисов через snap. Для примера приведены Nextcloud, LXD, MySQL, MicroK8s и Docker. Я пока в преимущества самого snap не вникал. Но возможность запуска и управления демонами через systemd привлекает.

Начинаем с установки «Virtual Machine Platform». Запускать команду надо от имени администратора в консоли PowerShell:

PS C:> dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all
Cистема DISM
Версия: 10.0.22000.653
Версия образа: 10.0.22000.1042
Включение функций
[==========================100.0%==========================]
Операция успешно завершена.

Для запуска systemd нужна WSL версия 0.67.6. Статья на сайте Microsoft рекомендует установить предварительную версию WSL из магазина приложений. Проблема в том, что в магазине версия 0.66. Для установки WSL Preview требуется Windows 11 (сборка 22000 или более новая).

Поступаем следующим образом. Ставим из магазина приложений «устаревшую» версию (0.66), чтобы в дальнейшем получать обновления на нее. А дальше качаем с GitHub нужную нам версию 0.67.6. Она последняя доступная на момент написания статьи. Возможно, на момент прочтения выйдут версии поновее. При запуске скаченного с GitHub пакета Менеджер установки предложит обновить WSL до нужной нам версии, то есть распознает, что WSL Preview у вас уже установлен. Это позволит в будущем обновлять WSL Preview автоматически встроенными в магазин приложений средствами

Какие команды могут помочь. Проверка версии WSL.

PS C:> wsl.exe --version

Если команда не распознает параметр «—version», значит у вас старая версия WSL (0.65 и ниже).

Недопустимый параметр в командной строке: --version
(c) Корпорация Майкрософт (Microsoft Corporation). Все права защищены.
Использование: wsl.exe [Аргумент] [Параметры...] [Командная строка]
....


В этом случае будет работать параметр «—status»:

PS C:> wsl --status
Распределение по умолчанию: Ubuntu-20.04
Версия по умолчанию: 2
Подсистема Windows для Linux в последний раз обновлена 21.06.2022
Включены автоматические обновления WSL.
Версия ядра: 5.10.102.1


В версии 0.66 параметр «—version» (-v) и статус «—status» дают следующий вывод:

PS C:> wsl --status
Default Distribution: Ubuntu-20.04
Default Version: 2
WSL version: 0.66.2.0
Kernel version: 5.15.57.1
WSLg version: 1.0.42
MSRDC version: 1.2.3401
Direct3D version: 1.606.4
DXCore version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
Windows version: 10.0.22000.978
PS C:> wsl --version
WSL version: 0.66.2.0
Kernel version: 5.15.57.1
WSLg version: 1.0.42
MSRDC version: 1.2.3401
Direct3D version: 1.606.4
DXCore version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
Windows version: 10.0.22000.978


А вот в версии 0.67 вывод параметра «—status» меняет формат:

PS C:> wsl --status
Default Distribution: Ubuntu-20.04
Default Version: 2


Итого, надо добиться того, чтобы версия WSL («WSL version» в выводе команды) была 0.67.6.0.

PS C:> wsl -v
WSL version: 0.67.6.0
Kernel version: 5.15.62.1
WSLg version: 1.0.44
MSRDC version: 1.2.3401
Direct3D version: 1.606.4
DXCore version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
Windows version: 10.0.22000.1042
PS C:> wsl --status
Default Distribution: Ubuntu-20.04
Default Version: 2

Я предполагаю, что уже есть созданная виртуальная среда в WSL. Кратко, как создать, если еще нет. Смотрим список доступных систем в WSL:

PS C:> wsl.exe --list --online
The following is a list of valid distributions that can be installed.
Install using 'wsl.exe --install <Distro>'.
NAME               FRIENDLY NAME
Ubuntu             Ubuntu
Debian             Debian GNU/Linux
kali-linux         Kali Linux Rolling
SLES-12            SUSE Linux Enterprise Server v12
SLES-15            SUSE Linux Enterprise Server v15
Ubuntu-18.04       Ubuntu 18.04 LTS
Ubuntu-20.04       Ubuntu 20.04 LTS
OracleLinux_8_5    Oracle Linux 8.5
OracleLinux_7_9    Oracle Linux 7.9

Далее ставим выбранный дистрибутив параметром «—install», пример:

PS C:> wsl.exe --install Ubuntu


В конце установки предложат ввести имя пользователя Linux и пароль для него.

После установки надо в файл /etc/wsl.conf добавить ключ для запуска systemd. В моем случае файл /etc/wsl.conf не существовал и был создан при редактировании:

user@DESKTOP:~$ sudo vim /etc/wsl.conf
[boot]
systemd=true

Важно, файл редактируется в гостевой системе Linux, не на хосте.

PS C:> wsl.exe --shutdown

В консоли Linux появится сообщение:

user@DESKTOP:~$
[process exited with code 1 (0x00000001)]


Вообще рекомендую команду «wsl.exe —shutdown» вводить после каждого изменения в WSL. Чтобы запустить WSL после остановки, нужно открыть заново консоль гостевой ОС.

Проверяем, что всё получилось:

user@DESKTOP:~$ systemctl list-unit-files --type=service
UNIT FILE                                  STATE           VENDOR PRESET
accounts-daemon.service                    masked          enabled
apparmor.service                           enabled         enabled
apport-autoreport.service                  static          -
apport-forward@.service                    static          -
apport.service                             generated       -
apt-daily-upgrade.service                  static          -
apt-daily.service                          static          -
atd.service                                masked          enabled
autovt@.service                            alias           -
blk-availability.service                   enabled         enabled
bolt.service                               static          -
clickhouse-server.service                  masked          enabled
cloud-config.service                       enabled         enabled
cloud-final.service                        enabled         enabled
cloud-init-hotplugd.service                static          -
.........

И, например, так

user@DESKTOP:~$ systemctl status networkd-dispatcher.service
● networkd-dispatcher.service - Dispatcher daemon for systemd-networkd
     Loaded: loaded (/lib/systemd/system/networkd-dispatcher.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-09-25 23:57:28 MSK; 37s ago
   Main PID: 133 (networkd-dispat)
      Tasks: 1 (limit: 9390)
     Memory: 16.8M
     CGroup: /system.slice/networkd-dispatcher.service
             └─133 /usr/bin/python3 /usr/bin/networkd-dispatcher --run-startup-triggers
Sep 25 23:57:27 DESKTOP systemd[1]: Starting Dispatcher daemon for systemd-networkd...
Sep 25 23:57:28 DESKTOP networkd-dispatcher[133]: No valid path found for iwconfig
Sep 25 23:57:28 DESKTOP networkd-dispatcher[133]: No valid path found for iw
Sep 25 23:57:28 DESKTOP systemd[1]: Started Dispatcher daemon for systemd-networkd.
Sep 25 23:57:28 DESKTOP networkd-dispatcher[133]: WARNING:Unknown index 7 seen, reloading interface list

Всё, можно пользоваться. Примеры использования есть на видео и в статье выше:

Понравилась статья? Поделить с друзьями:
  • Windows subsystem for linux windows server
  • Windows subsystem for linux update что это
  • Windows subsystem for linux update скачать
  • Windows subsystem for linux update setup wizard ended prematurely
  • Windows subsystem for linux preview что это