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 work 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.
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_118.0.2060.1-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
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:\users\MyUser\.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.
In this tutorial, we explain maybe the simplest possible method for installing a Linux Desktop and Linux Graphics User Interface (GUI) in Windows Subsystem for Linux (WSL2). Here is a brief overview of the tasks that we will perform in this tutorial in order to install the desktop environment:
1. Install WSL2 and a desired Linux distribution. In our case, we will install Ubuntu 24.04
2. Install Tasksel: https://wiki.debian.org/tasksel
Tasksel is a software package that can be used to install the Linux Desktop Environment (Linux GUI)
3. Install xrdp. Xrdp is a software package that enables us to setup and use a remote desktop protocol. Xrdp is developed by Microsoft and it allows us to remotely access and interact with a server’s graphics user interface. Xrdp is an abbreviation (acronym) for X Remote Desktop Protocol.
4. Use the Windows remote desktop connection to connect to the Linux Desktop Environment.
The YouTube tutorial is given below.
1. Install WSL2
If you do not have WSL2 installed on your system, you can install it as follows. Click on Start and search for Windows PowerShell. Open power shell in the administrator mode by doing a right click and by clicking on “run as administrator”. Check if WSL is already installed. You can do that by typing
wsl -l -v
If you see an output this means that WSL is installed. If not, to install WSL, you need to type
wsl --install
Then, after restarting the system, you will be able to use WSL. Note that with WSL there will be a default Linux Ubuntu version installed. We can change the default distribution and install any other supported distribution. We will install Ubuntu 24.04.
After you restart the system, open again Windows PowerShell in the administrator node. Type this
wsl -l -v
and you will see the list of installed distributions.
To list all available Linux distributions that can be run through WSL, type:
wsl --list --online
We will install Ubuntu 24.04. To do that, type this:
wsl --install -d Ubuntu-24.04
Type exist to exit the installed linux distribution. We will manually start the installed distribution later on.
To list all installed distributions, type this
wsl -l -v
To start Ubuntu 24.04. Click on start and search for Ubuntu 24.04. By clicking on Ubuntu 24.04, Ubuntu session will start.
Another way to start Ubuntu is to go back to the power shell and to type
wsl -d Ubuntu-24.04
Let us use a graphical approach to start Ubuntu. Click on Start and search for Ubuntu 24.04, and start Ubuntu 24.04.
Then, update
sudo apt update
sudo apt upgrade
Install Tasksel, Select the Linux GUI Distribution, and Install Xrdp
To install and run tasksel, type this
sudo apt install tasksel
sudo tasksel
After starting tasksel, you will see this menu
Here, we will select GNOME, to do that use the keyboard arrows to navigate and press space to select, then, press TAB to move to OK and press enter.
After that, the installation process will start.
To install xrdp, type this
sudo apt install xrdp -y
Confirm the installation with
sudo systemctl status xrdp
The status should be active (running). To exit this window, type this CTRL+C
If this program is not running, start it with
sudo systemctl start xrdp
Check the address of the Ubuntu Session and Start Remote Desktop Connection
To check the address, type this
ip a
and copy the inet address. In our case, the inet address is 172.29.173.75
Then, start a Windows Remote Desktop Connection, by clicking on Start and searching for Remote Desktop Connection
Start the Remote Desktop Connection, and type the inet address in the Computer field.
Then connect.
Then, you will see this screen
and enter the username and password you used to start the Ubuntu 24.04. After you enter the username and password, the Ubuntu GNOME section will start
Компонент WSL (Windows Subsystem for Linux или Подсистема Windows для Linux) появился в Windows 10 и с тех пор постоянно развивается. Одна из новых возможностей, которую кто-то из пользователей мог пропустить — возможность простого и удобного запуска программ Linux с GUI прямо в ОС Windows.
В этом материале — пример быстрой установки всего необходимого и запуска приложений с графическим интерфейсом в Windows 11 и 10 и дополнительная информация, которая может оказаться полезной.
Установка WSL, дистрибутива Linux и приложений
Установить WSL и нужный дистрибутив можно разными способами:
- Включив необходимые компоненты в дополнительных компонентах Windows и загрузив дистрибутив в Microsoft Store (подробнее).
- Почти автоматически в командной строке.
Далее будет рассмотрен второй вариант, как более быстрый в контексте рассматриваемой темы.
Для установки WSL и конкретного дистрибутива Linux достаточно выполнить следующие шаги:
- Запустите командную строку от имени администратора, введите команду
wsl --install
и нажмите Enter, дождитесь завершения выполнения команды.
- Перезагрузите компьютер и снова зайдите в командную строку. Если на первом шаге была также произведена установка Ubuntu (в некоторых версиях Windows устанавливается автоматически), завершите установку с помощью
wsl --install Ubuntu
В процессе потребуется задать имя пользователя и пароль.
- Если требуется другой дистрибутив или автоматическая установка не выполнялась, по порядку введите команды (первая покажет список доступных дистрибутивов, во второй укажите имя дистрибутива из левого столбца):
wsl --list --online wsl --install NAME
Готово, дистрибутив установлен, а поддержка графического интерфейса приложений в WSL текущих версий включается автоматически (ранее этого можно было добиться лишь обходными путями, по умолчанию приложения работали только в режиме терминала), переходим к установке приложений:
- Введите команду
sudo apt-get update
также можно использовать apt вместо apt-get. Дождитесь обновления репозиториев.
- Для установки приложения по его имени введите команду
sudo apt-get install ИМЯ_ПРИЛОЖЕНИЯ -y
- Приложение будет установлено и появится в меню «Пуск» Windows (в папке соответствующего дистрибутива), откуда его можно будет запустить:
- Тем же способом можно установить и другие необходимые приложения, а для их удаления используйте команду
sudo apt-get remove ИМЯ_ПРИЛОЖЕНИЯ
Результат: приложения Linux с графическим интерфейсом исправно работают прямо в Windows:
Делают это со звуком, ускорением графики OpenGl, пробросом локальных дисков.
При желании вы даже можете установить менеджер пакетов с графическим интерфейсом (своего рода «магазин приложений»). Например, мне удалось добиться вполне исправной работы Gnome Software:
- Устанавливаем с помощью команды в WSL
sudo apt install gnome-software -y
- Изменяем свойства ярлыка, добавленного в меню «Пуск» (правый клик по ярлыку в меню Пуск — перейти к расположению файла — открыть свойства ярлыка), заменив поле объект на (пример для Ubuntu)
"C:\Program Files\WSL\wslg.exe" -d Ubuntu -u root sudo gnome-software
Подобным же способом можно «заставить» запускаться от имени суперпользователя с ярлыков Windows и другие программы.
- Пользуемся для установки, обновления и удаления приложений Linux прямо в Windows, в графическом интерфейсе:
Подробная техническая информация о том, как именно работают Linux-приложения с GUI доступна на GitHub проекта WSLg, с помощью которого реализована соответствующая функциональность.
Время на прочтение9 мин
Количество просмотров99K
Введение
Данная статья предназначена вниманию системных администраторов, которые подготавливают типовые рабочие места на компьютерах под управлением ОС Windows 10, в том числе для разработчиков ПО.
Следует отметить, что существует определенная проблема, связанная с невозможностью интеграции ПО, полученного в on-line магазине Microsoft Store для использования в пользовательском образе Windows 10. Не вдаваясь в подробности уточню, что данная проблема связана с тем, что установленные из Microsoft Store программы связываются со служебной учетной записью Administrator, и при завершении создания пользовательского образа утилитой sysprep
возникают обусловленные этим обстоятельством ошибки.
Рассмотренный в данной статье способ позволить избежать такой проблемы при подготовке образа ОС Windows 10 с предварительно настроенной подсистемой WSL2, а также с заранее подготовленным и настроенным образом ОС Ubuntu 20.04 с GUI KDE Plasma, который в свою очередь может иметь свой набор пользовательского ПО.
В сети Интернет имеется большое количество примеров и руководств по настройке подсистем WSL (т.е. WSL1 и сравнительно новой WSL2), с настройкой GUI интерфейса для linux систем на базе ОС начиная с версии Ubuntu 16.04 и заканчивая Ubuntu 20.04, но в основном это касалось рабочих столов на основе т.н. «легковесного» xfce4, имеющий вполне объяснимые ограничения в пользовательских настройках. Но что касается GUI KDE Plasma для Ubuntu 20.04, в сети не нашлось какой-либо существенной информации. Но именно этот вариант предоставляет конечному пользователю практически неограниченный набор настроек как внешнего вида системы, так и настроек оборудования, конечно с учетом текущих возможностей интеграции linux-систем, реализованных в подсистеме WSL2.
Установка требуемого набора ПО и настройка WSL2
Проверяем текущую версию Windows, для этого в строке поиска Windows вводим команду winver
и получаем примерно следующее:
Важно, чтобы ОС имела версию 1903 или 1909 (указанные версии ОС должны быть с установленным накопительным обновлением KB4566116), либо 2004 (номер сборки не менее чем 19041), остальная информация не имеет значения. Если номер версии меньше, то для корректного повторения результатов, изложенных в данной статье, рекомендуется обновиться до последней версии Windows.
Для удобства дальнейших действий устанавливаем бесплатный Windows Terminal, используя Microsoft Store (также существует возможность загрузки из других источников):
Устанавливаем X Server X410 через тот же Microsoft Store, это ПО платное, но имеется бесплатный период в 15 дней, что вполне достаточно для проведения различных тестов.
В качестве бесплатной альтернативы X410 скачиваем и устанавливаем X-сервер VcXsrv.
В любом удобном месте на диске создаем каталог, в котором будем хранить наши файлы. В качестве примера создадим каталог C:\wsl
.
Скачиваем и устанавливаем автономный установщик Ubuntu 20.04, распаковываем полученный файл с помощью архиватора (например 7-zip). Переименовываем распакованный каталог с длинным именем Ubuntu_2004.2020.424.0_x64
во что-то более приемлемое, например Ubuntu-20.04
и копируем его в каталог C:\wsl
(далее по тексту просто \wsl
).
Скачиваем и распаковываем в каталог \wsl
кроссплатформенный звуковой сервер PulseAudio v.1.1., также вносим исправления в его конфигурационные файлы.
В файле \wsl\pulseaudio-1.1\etc\pulse\default.pa
в разделе Load audio drivers statically
редактируем строку:
load-module module-waveout sink_name=output source_name=input record=0
а в разделе Network access
редактируем строку:
load-module module-native-protocol-tcp auth-ip-acl=127.0.0.1 auth-anonymous=1
В файле \wsl\pulseaudio-1.1\etc\pulse\daemon.conf
раскомментируем и изменяем строку
exit-idle-time = -1
Настраиваем подсистему WSL2 в соответствии с документацией Microsoft. Единственное замечание — дистрибутив Ubuntu мы уже скачали, и устанавливать его будем на следующем шаге. В основном, настройка сводится к включению дополнительных компонентов «Подсистема Windows для Linux» и «Платформа виртуальной машины», и последующей перезагрузки для применения изменений в настройках компьютера:
При необходимости скачиваем и устанавливаем пакет обновлений для ядра Linux в WSL2.
Запускаем Windows Terminal и выбираем режим работы Command Prompt нажатием клавиш Ctrl+Shift+2
.
В первую очередь устанавливаем режим работы WSL2, для этого вводим команду:
wsl --set-default-version 2
Переходим в каталог с автономным загрузчиком Ubuntu 20.04, в моем случае это \wsl\Ubuntu-20.04
и запускаем файл ubuntu2004.exe
. При появлении запроса имени пользователя указываю имя engineer
(можно ввести любое другое имя), ввести свой пароль и подтвердить введенный пароль для указанной учетной записи:
Появилась строка приглашения терминала, ядро Ubuntu 20.04 установлено. Проверим правильность настройки режима WSL2, для этого в Windows Terminal выбираем закладку Windows PowerShell и вводим команду:
wsl -l -v
результат выполнения должен быть такой:
Настраиваем брандмауэр Microsoft Defender, т.е. отключаем его для общедоступной сети:
Настройка Ubuntu 20.04
В Windows Terminal снова выбираем закладку Command Prompt и устанавливаем обновления для Ubuntu 20.04. Для этого в командной строке вводим:
sudo apt update && sudo apt upgrade –y
Устанавливаем рабочий стол KDE Plasma:
sudo apt install kubuntu-desktop -y
установка занимает до 30 минут в зависимости от производительности компьютера и пропускной способности канала доступа в Internet, при появлении запроса установщика подтверждаем OK
.
Устанавливаем русскую локализацию и словари Ubuntu 20.04. Для этого в командной строке вводим:
sudo apt install language-pack-ru language-pack-kde-ru -y
sudo apt install libreoffice-l10n-ru libreoffice-help-ru -y
sudo apt install hunspell-ru mueller7-dict -y
sudo update-locale LANG=ru_RU.UTF-8
sudo dpkg-reconfigure locales # примечание: выбираем ru_RU.UTF-8 UTF-8, см. скриншоты ниже.
sudo apt-get install --reinstall locales
Добавляем последнюю версию рабочего стола KDE Plasma:
sudo add-apt-repository ppa:kubuntu-ppa/backports
sudo apt update && sudo apt full-upgrade -y
Добавляем свой набор консольных приложений, например mc
и neofetch
:
sudo apt install mc neofetch -y
Проверяем, что получилось, вводим в командную строку neofetch
, см. скриншот:
Редактируем конфигурационный файл WSL /etc/wsl.conf
:
sudo nano /etc/wsl.conf
в открывшееся пустое окно текстового редактора копируем текст:
[automount]
enabled = true
root = /mnt
options = «metadata,umask=22,fmask=11»
mountFsTab = true
[network]
generateHosts = true
generateResolvConf = true
[interop]
enabled = true
appendWindowsPath = true
сохраняем изменения (Ctrl+O
), подтверждаем операцию и выходим из текстового редактора (Ctrl+X
).
Экспортируем настроенный образ Ubuntu-20.04 в созданный нами каталог \wsl
. Для этого в Windows Terminal снова выбираем закладку Windows PowerShell и вводим команду:
wsl --export Ubuntu-20.04 c:\wsl\Ubuntu-plasma-desktop
созданный образ поможет нам автоматизировать операции запуска/переустановки настроенной Ubuntu 20.04, при необходимости позволит легко перенести на другой компьютер.
Подготовка bat-файлов и ярлыков на рабочий стол Windows
С помощью редактора Notepad++ создаем bat-файлы (обязательно в кодировке OEM-866 для корректного вывода символов кириллицы):
Файл Install-Ubuntu-20.04-plasma-desktop.bat
— предназначен для автоматизации первоначальной установки созданного образа Ubuntu 20.04 на компьютере с уже настроенной подсистемой WSL2 и X-сервером. Если имя пользователя и пароль отличается от указанных в примере, то необходимо внести соответствующие изменения в этот bat-файл:
@echo off
wsl --set-default-version 2
cls
echo Ожидайте окончания установки дистрибутива Ubuntu-20.04...
wsl --import Ubuntu-20.04 c:\wsl c:\wsl\Ubuntu-plasma-desktop
wsl -s Ubuntu-20.04
cls
echo Дистрибутив Ubuntu-20.04 успешно установлен!
echo Не забудьте сменить учетную запись по умолчанию «root» на существующую учетную запись пользователя,
echo либо используйте предустановленную учетную запись «engineer», пароль: «password».
pause
Файл Reinstall-Ubuntu-20.04-plasma-desktop.bat
— предназначен для переустановки подготовленного образа Ubuntu 20.04 на компьютере.
@echo off
wsl --unregister Ubuntu-20.04
wsl --set-default-version 2
cls
echo Ожидайте окончания переустановки дистрибутива Ubuntu-20.04...
wsl --import Ubuntu-20.04 c:\wsl c:\wsl\Ubuntu-plasma-desktop
wsl -s Ubuntu-20.04
cls
echo Дистрибутив Ubuntu-20.04 успешно переустановлен!
pause
Файл Set-default-user.bat
— для установки пользователя «по умолчанию».
@echo off
set /p answer=Введите существующую учетную запись в Ubuntu (engineer):
c:\wsl\Ubuntu-20.04\ubuntu2004.exe config --default-user %answer%
cls
echo Учетная запись пользователя %answer% в Ubuntu-20.04 установлена по умолчанию!
pause
Файл Start-Ubuntu-20.04-plasma-desktop.bat
— собственно запуск рабочего стола KDE Plasma.
@echo off
echo ===================================== Внимание! ============================================
echo Для корректной работы GUI Ubuntu 20.04 в WSL2 необходимо использовать X Server.
echo Примечание: в случае использования VcXsrv Windows X Server необходимо раскомментировать
echo строки в файле Start-Ubuntu-20.04-plasma-desktop.bat, содержащие "config.xlaunch" и
echo "vcxsrv.exe", и закомментировать все строки, содержащие "x410".
echo ============================================================================================
rem start "" /B "c:\wsl\vcxsrv\config.xlaunch" > nul
start "" /B x410.exe /wm /public > nul
start "" /B "c:\wsl\pulseaudio-1.1\bin\pulseaudio.exe" --use-pid-file=false -D > nul
c:\wsl\Ubuntu-20.04\Ubuntu2004.exe run "if [ -z \"$(pidof plasmashell)\" ]; then cd ~ ; export DISPLAY=$(awk '/nameserver / {print $2; exit}' /etc/resolv.conf 2>/dev/null):0 ; setxkbmap us,ru -option grp:ctrl_shift_toggle ; export LIBGL_ALWAYS_INDIRECT=1 ; export PULSE_SERVER=tcp:$(grep nameserver /etc/resolv.conf | awk '{print $2}') ; sudo /etc/init.d/dbus start &> /dev/null ; sudo service ssh start ; sudo service xrdp start ; plasmashell ; pkill '(gpg|ssh)-agent' ; fi;"
rem taskkill.exe /F /T /IM vcxsrv.exe > nul
taskkill.exe /F /T /IM x410.exe > nul
taskkill.exe /F /IM pulseaudio.exe > nul
Файл Start-Ubuntu-20.04-terminal.bat
— запуск графического терминала без рабочего стола KDE Plasma.
@echo off
echo ===================================== Внимание! ============================================
echo Для корректной работы GUI Ubuntu 20.04 в WSL2 необходимо использовать X Server.
echo Примечание: в случае использования VcXsrv Windows X Server необходимо раскомментировать
echo строки в файле Start-Ubuntu-20.04-plasma-desktop.bat, содержащие "config.xlaunch" и
echo "vcxsrv.exe", и закомментировать все строки, содержащие "x410".
echo ============================================================================================
rem start "" /B "c:\wsl\vcxsrv\config.xlaunch" > nul
start "" /B x410.exe /wm /public > nul
start "" /B "c:\wsl\pulseaudio-1.1\bin\pulseaudio.exe" --use-pid-file=false -D > nul
c:\wsl\Ubuntu-20.04\Ubuntu2004.exe run "cd ~ ; export DISPLAY=$(awk '/nameserver / {print $2; exit}' /etc/resolv.conf 2>/dev/null):0 ; export LIBGL_ALWAYS_INDIRECT=1 ; setxkbmap us,ru -option grp:ctrl_shift_toggle ; export PULSE_SERVER=tcp:$(grep nameserver /etc/resolv.conf | awk '{print $2}') ; sudo /etc/init.d/dbus start &> /dev/null ; sudo service ssh start ; sudo service xrdp start ; konsole ; pkill '(gpg|ssh)-agent' ;"
taskkill.exe /F /T /IM x410.exe > nul
rem taskkill.exe /F /T /IM vcxsrv.exe > nul
taskkill.exe /F /IM pulseaudio.exe > nul
Также для удобства использования в каталоге \wsl
подготавливаем ярлыки, указывающие на соответствующие bat-файлы. После чего содержимое каталога \wsl
выглядит следующим образом:
Запуск рабочего стола KDE Plasma
Проверяем, что все подготовительные действия выполнены, пробуем запустить ярлык Plasma-desktop
. Появляется запрос пароля, вводим пароль для учетной записи и… окно закрывается. В первый раз это нормально. Пробуем еще раз — и видим знакомую панель задач KDE Plasma. Настраиваем требуем внешний вид панели задач, на примере для удобства использования панель переносится в правую часть экрана и центрируется. Проверяем настройки локализации, при необходимости добавляем русский язык:
При необходимости выносим ярлыки для установленных linux-приложений на панель задач KDE Plasma.
Если Ubuntu 20.04 требует выйти из учетной записи пользователя для применения изменений в настройках, или Вам необходимо перезагрузить ОС, для этого в Windows Terminal введите команду:
wsl -d Ubuntu20.04 --shutdown
С помощью ярлыка Plasma-desktop
или Konsole
можно запустить GUI KDE Plasma Ubuntu 20.04. Например, установим с помощью Konsole
графический редактор GIMP:
После окончания установки запускаем из Konsole
графический редактор GIMP:
GIMP работает, что и требовалось проверить.
А вот как работают различные linux-приложения в KDE Plasma в WSL2:
настроенная панель задач KDE Plasma находится в правой части экрана. а видео в окне Firefox воспроизводится со звуком.
При необходимости можно настроить доступ к Ubuntu20.04 по SSH
и RDP
, для этого необходимо установить соответствующие службы командой:
sudo apt install ssh xrdp -y
примечание: для включения парольного доступа по SSH
необходимо отредактировать файл /etc/ssh/sshd_config
, а именно параметр PasswordAuthentication no
необходимо установить в значение PasswordAuthentication yes
, сохранить изменения и перезагрузить Ubuntu20.04.
При каждом запуске Ubuntu20.04 меняется внутренний ip-адрес, перед настройкой удаленного доступа необходимо уточнить текущий ip-адрес с помощью команды ip a
:
Соответственно, этот ip-адрес необходимо внести в настройки сессий SSH
и RDP
перед запуском.
Вот так выглядит удаленный доступ по SSH
с помощью MobaXterm:
А вот так выглядит удаленный доступ по RDP
:
Использование X-сервера vcxsrv вместо x410
Запускаем и настраиваем vcxsrv
, внимательно устанавливаем соответствующие флажки:
Сохраняем настроенную конфигурацию в каталоге \wsl\vcxsrv
со стандартным именем config.xlaunch
.
Редактируем bat-файлы Start-Ubuntu-20.04-plasma-desktop.bat
и Start-Ubuntu-20.04-terminal.bat
в соответствии с имеющимися в них инструкциями.
Запускаем ярлык Plasma-desktop
, и вот что получаем:
Рабочий стол KDE Plasma полностью закрывает рабочий стол Windows, для переключения между окнами linux- и windows-приложений используем известную комбинацию клавиш Alt+Tab
, что не совсем удобно.
Кроме того, выяснилась неприятная особенность X-сервера vcxsrv
– он «падает» при запуске некоторых приложений, в частности того же GIMP или LibreOffice Writer. Возможно следует подождать, когда разработчики уберут замеченные «баги», но это не точно… Так что для получения приемлемых результатов лучше использовать X Server Microsoft x410.
Заключение
Все-таки надо отдать должное компании Microsoft, продукт WSL2 получился вполне рабочим, и на мой неискушенный взгляд — весьма удачным. И насколько мне известно, разработчики продолжают усиленно его «допиливать», и возможно — через годик-другой, данная подсистема предстанет во всей своей функциональной полноте.
In recent years, Windows and Linux have slowly begun to coexist more harmoniously. Windows Subsystem for Linux (WSL) has bridged the gap for developers who wish to use Linux tools while running Windows. WSL2, the second iteration of this subsystem, introduced significant improvements, including full system call compatibility and better performance. Until recently, users could run command-line Linux applications, but the ability to run Linux GUI applications was not supported out of the box. Fortunately, with the release of WSL2 and subsequent updates, running Linux GUI applications on Windows has become a reality.
In this comprehensive guide, we’ll walk through everything you need to know about running Linux GUI apps on WSL2, from setting it up to troubleshooting common issues.
What Is WSL2?
The Windows Subsystem for Linux (WSL) allows users to run a Linux environment directly on Windows without the need for a virtual machine or dual-boot configuration. WSL2 is a major update that contains a real Linux kernel and does not rely on translation layers like its predecessor. This means better performance, compatibility with more software, and a more robust environment overall.
Key Features of WSL2
- Full System Call Compatibility: WSL2 supports Linux binaries natively, including those requiring system calls not present in the previous version.
- Virtualized Architecture: It runs a complete Linux kernel in a lightweight virtual machine, providing greater compatibility with Linux applications.
- Improved File System Performance: WSL2 provides faster file system performance and better integration with Windows.
- Networking Capabilities: Enhanced capabilities allowing Linux apps to communicate more easily with Windows apps.
Prerequisites for Running GUI Apps in WSL2
Before diving into the setup process, ensure you meet the following prerequisites:
- Windows Version: You need Windows 10 version 2004 or higher, or Windows 11.
- WSL2 Installed: Make sure you have WSL2 set up. You can install it from PowerShell.
- Graphical Display Server: Linux GUI apps will require an X server or a Wayland compositor. You can use third-party solutions like Xming, VcXsrv, or even install a native X server like GWSL.
- Linux Distribution: Choose a Linux distribution from the Microsoft Store (e.g., Ubuntu, Debian, etc.).
Setting Up WSL2
Step 1: Enable WSL and Virtual Machine Platform
- Open PowerShell as Administrator. Right-click on the Start button and select “Windows PowerShell (Admin).”
- Run the following command to enable WSL and the Virtual Machine Platform:
dism.exe /Online /Enable-Feature /FeatureName:Microsoft-Windows-Subsystem-Linux /All /LimitAccess /Restart dism.exe /Online /Enable-Feature /FeatureName:VirtualMachinePlatform /All /LimitAccess /Restart
- Once your system reboots, you’ll need to set WSL2 as your default version. Open PowerShell again and run:
wsl --set-default-version 2
Step 2: Install a Linux Distribution
- Visit the Microsoft Store and search for a Linux distribution. Some popular choices include Ubuntu, Debian, and Kali Linux.
- Click on “Install” to download and install the distribution of your choice.
- After installation, launch the distribution from the Start Menu. The first time you launch it, it will run through some setup steps, including creating a user account.
Step 3: Update Your Distribution
After installation, it’s a good practice to update packages in your distribution. Inside your Linux terminal, run:
sudo apt update
sudo apt upgrade
This ensures that all software is up to date before proceeding.
Setting Up GUI Applications
Step 1: Choose an X Server
To run GUI applications, you need an X server installed on your Windows machine. Below are a few popular options:
- VcXsrv:
- Download and install VcXsrv from its official website.
- Launch VcXsrv with the default settings, allowing it to listen on all interfaces and disabling access control.
- Xming:
- Similar to VcXsrv, Xming is another lightweight X server for Windows. Download and install it following the same parameters as above.
- GWSL:
- GWSL is a more user-friendly option that integrates with WSL. Install it from the Microsoft Store.
Step 2: Configure the Display Variable in WSL2
After setting up your X server, you need to configure your DISPLAY environment variable in WSL2:
- Open your Linux terminal.
- Run the following command to set the DISPLAY variable:
echo "export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}'):0" >> ~/.bashrc
- To apply the changes, run:
source ~/.bashrc
By setting this variable, you’re telling Linux applications where to display their GUI.
Step 3: Test Your Setup
To verify that everything is set up correctly, you can install a simple GUI application. Use gedit
, for example:
sudo apt install gedit
gedit
If configured correctly, gedit should launch and display on your Windows desktop.
Troubleshooting
Issue: GUI Does Not Launch
- Check Firewall Settings: Ensure that your firewall permits traffic from the X server.
- X Server Configuration: Make sure your X server (like VcXsrv) is running and properly configured to allow connections.
- DISPLAY Variable: Verify that your DISPLAY variable in WSL2 is correctly set. You can check by running:
echo $DISPLAY
The output should be something like 192.168.x.x:0
.
Issue: Performance Issues
If you experience lag or poor performance with graphical applications, consider the following:
- More RAM/CPU Resources: Increase the resources allocated to WSL by modifying the
.wslconfig
file in your user profile directory. You could reserve more RAM or CPU if your machine supports it:[wsl2] memory=4GB # Limits memory processors=2 # Limits number of processor cores
- Use Lightweight Applications: Some applications are more resource-intensive than others; try to use lighter alternatives.
Issue: Text Rendering Problems
If text appears strange or doesn’t render as expected, it could be due to font configurations. Ensure that the fonts used in the GUI applications are properly installed and configured.
Running Popular GUI Applications
Once your environment is up and running, the possibilities with Linux GUI applications are vast. Here are some popular applications you might want to try and how to install them.
1. GIMP (GNU Image Manipulation Program)
GIMP is a powerful image editor. To install it:
sudo apt install gimp
2. LibreOffice Suite
If you need a robust office suite, LibreOffice offers a complete set of tools:
sudo apt install libreoffice
3. Visual Studio Code
Visual Studio Code, being a prevalent code editor, can be installed by adding the Microsoft repository:
wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
sudo install -o root -g root -m 644 microsoft.gpg /usr/share/keyrings/
echo "deb [signed-by=/usr/share/keyrings/microsoft.gpg] https://packages.microsoft.com/repos/vscode stable main" | sudo tee /etc/apt/sources.list.d/vscode.list
sudo apt update
sudo apt install code
4. Firefox
For web browsing needs, you can easily install Firefox as follows:
sudo apt install firefox
Conclusion
With the advancements in WSL2, Linux and Windows users can now enjoy the best of both worlds. Running Linux GUI applications not only expands the toolkit for developers but also creates many possibilities for utilizing open-source software alongside commercial applications.
The seamless integration of Linux GUI apps on Windows makes it simpler than ever to work in mixed-OS environments and allows for enhanced productivity. With this guide, you’re equipped to set up and troubleshoot your WSL2 and graphical applications, enhancing your development and operational capabilities. Happy coding!