Xorg linux что это

Обновлено: 04.07.2024

Где находится файл журнала, как произвести отладку? File:

содержит массу бесценной отладочной информации о том, что происходит, когда запускается Xorg. Найдите строки, содержащие EE (errors) и WW (warnings).

How to edit or add HorizSync and VertRefresh lines Find your monitors manual (manufacturers website and Google are useful). Look for hozizontal sync and vertical refresh rates, also if bandwidth or maximum dot clock / pixel clock is mentioned, write it down.

Be sure that Identifier is same as the Monitor line in Screen section.

Copy paste the new Modeline to Monitor section (for example):

Watch that the hsync is in range with the HorizSync on the same section (in this example the range is 31-101 and this modelines hsync is 60.15, so we're safe). Also the VertRefresh and the refresh rate you selected (75Hz in this example) should match - in this example VertRefresh is 60-160 and modeline is 75Hz, so that's all good.

Now you can select the default resolution and colordepth by tweaking the Screen section. It should look something like this:

Monitor name here (CM752ET) matches the Identifier on your Monitor Section. Device line here matches the identifier on your Device section - you get the idea? It ties together some settings for your screen - the graphics card and your monitor. You may have more Subsections here, but only one is needed.

Change the DefaultDepth to what you would want it to be, 16 (65536 colors) or 24 (16M colors). Change the Modes line to match the resolutions you want to use - Depth must match DefaultDepth (here it's 16).

Save the config. If you're in X, hit CTRL+ALT+BACKSPACE to restart X (if you're running logon manager like xdm, kdm or gdm). Change between virtual consoles with CTRL + F1 F2 F3 and so on - your X should be on F7.

Starting the X: startx OR sudo /etc/init.d/gdm start (in KDE it's kdm)

If that doesn't work, try fixing the xorg.conf or get back to your original by copying the backup over your changed one with:

When you're back in X, you can cycle through different modes by pressing CTRL+ALT++ (plus sign on numpad), or go to System->Preferences->Screen Resolution.

How to adjust position of your screen? open terminal(Applications->Accessories->Terminal), run xvidtune (type: "xvidtune"), adjust the screen and hit Show-button. You'll see a line with something like this on the terminal screen:

Next you should:

In Monitor section, add the above line with a prefix "Modeline", like this:

That should do it. There should be no need to restart X if you did make the change (hit Apply in xvidtune), but you should test that this new change works. Hit ctrl+alt+backspace to restart X. If it doesn't work, you can copy back the old configuration file using:

and restart X using:

    o online modeline generator

Miscellaneous resources (may contain outdated information)

  • xresprobe [driver=vesa,ati,nv,nvidia,i810]
  • ddcprobe

The material on this wiki is available under a free license, see Copyright / License for details.

Эта глава содержит графическое окружение пользователя.

Введение в Xorg

[Замечание]

Замечание

Есть два пакета в BLFS , которые реализуют систему X Window: Xorg и XFree86 . Эти пакеты очень похожи. Фактически, основная система Xorg это XFree86 -4.4.0RC2. Главным отличием этих пакетов является лицензия. Для тех, кто собирает пакет для себя, эти отличия не существенны. Большинство больших комерческих дистрибутивов решили использовать пакет Xorg , но некоторые все еще используют XFree86 .

XFree86 продолжает оставаться цельным, консервативным приложением с отличной поддержкой драйверов.

Xorg и XFree86 могут быть установлены одним и тем же способом, но этот раздел предоставит слегка отличные варианты установки.

Xorg это свободно распространяемая открытая реализация системы X Window. Это приложение предоставляет интерфейс клиент/сервер между аппаратурой отображения (мыш, клавиатура и видео дисплей) и окружением рабочего стола, а так же предоставляет оконную инфраструктуру и стандартный интерфейс приложений ( API ).

Информация о пакете

Контрольная сумма: 8131cd7ea1e4566e6e05c438a93fcfe1

Требуемое дисковое пространство: 655 MB

Расчетное время сборки: 17.8 SBU

Зависимости Xorg

Требуемые
Опционально

Инструкции для скачивания

Первый пакет содержит библиотеки и программы поддержки Xorg , второй содержит стандартные программы X , третий содержит сервер X , четвертый и пятый - шрифты, шестой - обычную документацию, а седьмой - жесткую копию документации.

Для проверки целостности ваших файлов скачайте файл md5sums. Затем:

Пакет (или все семь пакетов) должен дать статус OK.

Установка Xorg

Параметры компиляции ядра

Если увас установлен Intel P6 (Pentium Pro, Pentium II и позднее), то рекомендуется вкомпилировать поддержку MTRR (Memory Type Range Registers) в ядро. Ядро может использовать прцессоры Cyrix и AMD с интерфейсом MTRR , поэтому выбор этой опции полезен и для этих процессоров. Эта опция находится в меню "Processor type and features". Она может увеличить скорость операций записи изображений в 2.5 и более раза для PCI или AGP видео карт.

В разделе "Character Devices" включите поддердку AGP и выберите поддержку чипсета вашей материнской платы. Если вы не знаете чипсет, то вы можете выбрать все типы чипов за счет увеличеия размера ядра. Обычно вы можете определить чипсет вашей материнской платы запуском команды lspci , программы из пакета PCI Utilities-2.1.11.

В разделе "Character Devices" выключите Direct Rendering Manager если у вас нет видеокарты, поддерживающей Direct Rendering Infrastructure ( DRI ). Полный список видеокарт, поддерживающих DRI , может быть найден на http://dri.sourceforge.net в разделе "Status". В настоящий момент поддерживаются следующие видеокарты: 3dfx (Voodoo, Banshee), 3Dlabs, ATI (Rage Pro, Rage 128, Radeon 7X00, Radeon 2), Intel (i810, i815) и Matrox (G200, G400, G450).

Дополнительно NVidia предоставляет их собственные закрытые бинарные драйверы, которые не используют DRI . Если вы захотите использовать эти драйверы, то не включайте DRI .

Если вы внесете изменения в конфигурацию ядра, перекомпилируйте и установите новое ядро.

[Замечание]

Замечание

Если вы собираете Xorg в среде chroot , убедитесь, что версии ядра основной и целевой системы одинаковые.

Заперещение Xprint-связанной модификации в /etc

Xorg настаивает на размещении своих стартовых и профильных скриптов в директории /etc даже если особо сказано не компилировать Xprint сервер или клиент (смотрите host.def ниже). Следующая команда запретит любые такие изменения:

Установка теневой директории

Собирая Xorg , вы должны создать теневую директорию символических ссылок для скомпилированного кода. Чтобы это сделать, сначала создадим lndir . Выполним из директории xc:

А теперь, как пользователь root:

И вернемся как обычный пользователь:

Теперь создадим теневое дерево:

Создание host.def

Следующим шагом является создание файла config/cf/host.def. Документация по Xorg показывает, что приложения будут собраны без файла host.def, но включенные библиотеки для Fontconfig и FreeType2 будут собраны не правильно в базовой системе LFS . В этом случае вы должны указать, что эти библиотеки, как и другие, должны быть импортированы из системы.

[Замечание]

Замечание

config/cf/host.def это C файл, не скрипт оболочки. Убедитесь, что коментарии, установленные при помощи /* . */ сбалансированы после модификации файла.

Есть и другие опции, которые вы можете захотеть установить. Хорошо документироанным примером файла является config/cf/xorgsite.def.

Команды сборки

Установим Xorg запуском следующих команд:

Опять как пользователь root:

Описание команд

[Замечание]

Замечание

При пересборке Xorg отдельной командой, которая может быть использована, если были сделаны только небольшие изменения в исходниках, является make Everything . Она автоматически не удаляет сгенерированные файлы, а только пересобирает более новые.

Эти команды нужны, чтобы другие (неправильные) пакеты могли собираться с Xorg , даже если FHS говорит: "Обычно программа не дожна быть установлена или управляема через указанные символические ссылки. Они предназначены только для использования пользователями."

Конфигурация Xorg

Отредактируйте /etc/ld.so.conf и добавьте /usr/X11R6/lib. Запустите:

Убедитесь, что /usr/X11R6/bin и /usr/X11R6/lib/pkgconfig добавлены в ваш PATH и, соответственно, переменная окружения PKG_CONFIG_PATH. Инструкции о том, как это сделать, описаны в разделе "Стартовые файлы оболочки Bash".

Создадим файл xorg.conf при помощи:

Экран почернеет и вы можете услышать небольшие щелчки монитора. Эта команда создаст файл xorg.conf.new в вашей домашней директории.

Отредактируйте xorg.conf.new для настройки под вашу систему. Детальная информация по файлу находится в man странице по xorg.conf. Кое что из того, что вы можете захотеть сделать, это:

Раздел "Files". Измените порядок следования путей поиска директорий шрифтов. Вы можете захотеть поместить шрифты 100dpi перед шрифтами 75dpi, если ваша система с ними работает нормально. Вы можете захотеть полностью удалить некоторые директории шрифтов.

Раздел "Module". Если вы будете устанавливать драйвер NVidia, то удалите строчку "dri".

Разделы "InputDevice". Установите параметр Device на "/dev/input/mice" и Protocol на "auto" для настройки вашей мыши. Вы можете захотеть изменить скорость автоповтора клавиатуры, добавив Option "Autorepeat" "250 30".

Раздел "Monitor". Установите значения VertRefresh и HorizSync если система автоматически не определила монитор и его параметры.

Раздел "Device". Вы можете захотеть установить некоторые из опций, доступные для вашего выбранного видео драйвера. Описание параметров драйвера находятся в man странице для этого драйвера.

Раздел "Screen". Добавьте элемент DefaultDepth, например: DefaultDepth 16. В SubSection для вашей глубины цвета по умолчанию добавьте строчку Modes, например: Modes "1280x1024" "1024x768". Первая указанная мода будет стартовым разрешением экрана.

Переместим файл конфигурации в его положенное место:

Это предоставит начальный экран с xterm и часами, которые управляются простым оконным менеджером, Tab Window Manager. Для большей иформации о twm обратитесь к его man странице.

[Замечание]

Замечание

Если надо, Xorg создает директорию /tmp/.ICE-unix, если ее нет. Если эта директория не принадлежит root, то Xorg задерживает запуск на несколько секунд и добавляет предупреждение в лог-файл. Это так же действует на запуск других приложений. Для увеличения производительности рекомендуестя вручную создать эту директорию перед тем, как Xorg будет ее использовать. Добавим создание файла в /etc/sysconfig/createfiles, который используется стартовым скриптом /etc/rc.d/init.d/cleanfs.

Запустим X при помощи:

для получения базовой функциональности системы X Window.

В этом месте вы должны обратиться к разделу “Компоненты системы X Window”.

За списком содержания пакета и описанием команд обратитесь к разделу Содержание и описание XFree86.

Xorg is the X Window server which allows users to have a graphical environment at their fingertips. This guide explains what Xorg is, how to install it, and the various configuration options.

Contents

What is the X Window server?

Graphical vs command-line

An average user may be frightened at the thought of having to type in commands at a command-line interface (CLI). Why wouldn't they be able to point-and-click their way through the freedom provided by Gentoo (and Linux in general)? Well, of course they can!

Gentoo offers a wide variety of flashy graphical interfaces such as window managers and desktop environments which can be installed on top of an existing installation.

One of the biggest surprises users who are new to Linux come across: graphical user interfaces are nothing more than an application (or in some cases a suite of applications) which are run on a system. It is not part of the Linux kernel or any other internals of the system. That said, GUIs are powerful tools that unlock the graphical abilities of a workstation.

As standards are important, a standard for drawing and moving windows on a screen, interacting with the user through mouse, keyboard, and other basic, yet important aspects has been created and named the X Window System, commonly abbreviated as X11 or just X. It is used on Unix, Linux, and Unix-like operating systems throughout the world.

The application that provides Linux users with the ability to run graphical user interfaces and that uses the X11 standard is Xorg-X11, a fork of the XFree86 project. XFree86 has decided to use a license that might not be compatible with the GPL license; the use of Xorg is therefore recommended. XFree86 packages are no longer provided through the Gentoo repository.

Xorg provides an interface between your hardware and the graphical software you want to run. Besides that, Xorg is also fully network-aware, meaning you are able to run an application on one system while viewing it on a different one.

Installation

Before you can install Xorg, you need to prepare your system for it. First, we'll set up the kernel to support input devices and video cards. Then we'll prepare /etc/portage/make.conf so that the right drivers and Xorg packages are built and installed.

Input driver support

Support for Event interface ( CONFIG_INPUT_EVDEV ) needs to be activated by making a change to the kernel configuration. Read the Kernel Configuration Guide if you don't know how to setup your kernel.

KERNEL Enabling evdev in the kernel

Kernel modesetting

Modern open source video drivers rely on kernel mode setting (KMS). KMS provides an improved graphical boot with less flickering, faster user switching, a built-in framebuffer console, seamless switching from the console to Xorg, and other features.

Verify legacy framebuffer drivers have been disabled

Important
KMS conflicts with legacy framebuffer drivers, which must remain disabled in the kernel configuration.

First prepare the kernel for KMS. This step regardless of which Xorg video driver will be used:

KERNEL Disable legacy framebuffer support and enable basic console FB support

Next configure the kernel to use the proper KMS driver for the video card. Intel, NVIDIA, and AMD/ATI are the most common cards, so follow code listing for each card below.

Intel

NVIDIA

For NVIDIA cards, two driver options are available. For a full open source system, an open source driver entitled Nouveau is suggested. The second option is the closed source NVIDIA driver, which is officially supported by NVIDIA. This article recommends the Nouveau driver, however be aware not all functionally for certain cards may be supported using the open source driver.

In addition to the kernel driver, certain cards require closed source firmware to be built-in to the Linux kernel. Depending on the selected driver, readers should visit each respective article to check to see if firmware (from the sys-kernel/linux-firmware is necessary for their specific card.

AMD/ATI

For newer AMD/ATI cards (RadeonHD 2000 and up), emerge sys-kernel/linux-firmware (the package includes firmware for radeon and amdgpu drivers). Once one of these packages has been installed, make the Radeon driver a module in the kernel or, optionally, configure the kernel as detailed in the firmware section of the Radeon article or, for newer AMD graphics cards (GCN1.1+), the firmware section of the AMDGPU article.

Note
On x86/amd64, older Radeon cards (X1900 series and older) do not need extra firmware or any special firmware configuration. Direct Rendering Manager (DRM) and ATI Radeon modesetting driver are the only kernel settings necessary for correct operation. Note
Linux kernel >= 3.9 does not have the Enable modesetting on radeon by default since it is already implied by default. Do not be alarmed if you find this option missing in new kernels. Note
Linux kernel >= 4.15 does include Display Core (DC) which is required for AMDGPU to work. This newer driver was written for GCN5.0 Vega and DCN1.0 Raven Ridge (APU), but also adds additional functionality for older Radeon graphics cards starting with GCN1.1 Southern Islands and newer. It is planned to make this additional support for older Radeon cards the standard, so do not be alarmed if you find this option missing in newer kernels.

Now that KMS has been set up, continue preparing /etc/portage/make.conf in the next section.

Now that the kernel is prepared, some variables in the /etc/portage/make.conf file must be configured before installing Xorg.

Make.conf

Portage knows the USE=X USE flag for enabling support for X in other packages (default in all desktop profiles). Make sure this USE flag is added to the USE flag list to ensure X compatibility system wide:

The first variable is VIDEO_CARDS . This is used to set the video drivers that you intend to use and is usually based on the kind of video card you have. The most common settings are nouveau for NVIDIA cards or radeon for ATI cards. Both have actively developed, well-supported open-source drivers. If you have a newer AMD video card (Southern Islands and up), you may also try the new open-source amdgpu driver. See the AMDGPU article for more details.

Note
You may also try the proprietary drivers from NVIDIA and AMD/ATI, nvidia and fglrx respectively. However, setting up the proprietary drivers is beyond the scope of this guide. Please read the Gentoo Linux NVIDIA Guide and Gentoo Linux ATI FAQ. If you don't know which drivers you should choose, refer to these guides for more information.

The intel driver may be used for desktops or laptops with common Intel integrated graphics chipsets. See Intel X Drivers for more details.

Note
The VIDEO_CARDS variable may contain more than one value as long as each value is separated by a space.

The second variable is INPUT_DEVICES and is used to determine which drivers are to be built for input devices.

make.defaults has Libinput as the default input device driver.

To check what is presently set, run:

In case alternative input devices, such as a Synaptics touchpad for a laptop are needed, be sure to add them to INPUT_DEVICES the /etc/portage/make.conf file:

If the suggested settings does not work emerge the x11-base/xorg-drivers package (see the step below). Check all the options available and choose those which apply to the system. This example is for a system with a keyboard, mouse, Synaptics touchpad, and a Radeon video card.

The USE flags have the following meaning:

Emerge

After setting all the necessary variables and USE flags Xorg can be installed:

Note
The x11-base/xorg-x11 meta-package could be installed instead of the more lightweight x11-base/xorg-server. Functionally x11-base/xorg-x11 and x11-base/xorg-server are the same, however x11-base/xorg-x11 brings in many more packages that most systems will probably not require. Additional packages include a large assortment of fonts in many languages. They are not necessary for a working X11 framework.

When the installation is finished, some environment variables will need to re-initialized before continuing. Source the profile with this command:

Configuration

The X server is designed to work out-of-the-box, with no need to manually edit Xorg's configuration files. It should detect and configure devices such as displays, keyboards, and mice.

Try using startx without editing any configuration files. If Xorg will not start, or there is some other problem, then manual configuration of Xorg might be needed. This is explained in the following section.

To run Xorg with a non root user, see Non root Xorg.

Note
If changes have been made to the kernel, do not forget to restart the system before using startx in order to be using the newly built kernel. If the kernel was updated to a newer version in the process this will most likely require the bootloader's configuration files to be updated as well.

The xorg.conf.d directory

Important
Configuring files in xorg.conf.d should be seen as a last resort option. If possible it is desirable to run Xorg without any special configuration.

Most of the configuration files for Xorg are stored in /etc/X11/xorg.conf.d/ . If that directory does not exist you can create it. Each file is given a unique name and ends in .conf . The file names in Xorg's configuration directory will be read in alpha numeric order. For example, 10-evdev.conf will be read before 20-synaptics.conf ; a-evdev.conf will be read before b-synaptics.conf , and so on. The files in this directory are not required to be numbered, but doing so will help to keep them organized. Organization is helpful when debugging faulty configuration files.

Note
Xorg provides example configurations in /usr/share/doc/xorg-server-$/xorg.conf.example.bz2 . These can be used to create custom configuration files in /etc/X11/xorg.conf.d/ . The examples are heavily commented, but if more documentation regarding the syntax is needed, man xorg.conf is always available. Other examples can be found in the section Other resources at the end of this guide.

Using startx

Try startx to start up the X server. startx is a script (it's installed by x11-apps/xinit) that executes an X session; that is, it starts the X server and some graphical applications on top of it. It decides which applications to run using the following logic:

  • If a file named .xinitrc exists in the home directory, it will execute the commands listed there.
  • Otherwise, it will read the value of the XSESSION variable from the /etc/env.d/90xsession file and execute the relevant session accordingly. Values for XSESSION are available in /etc/X11/Sessions/ . To set a system wide default session run:
This will create the 90xsession file and set the default X session to Xfce. Remember to run env-update after making changes to 90xsession .

If no window manager has been installed a solid black screen will appear. Since this can also be a sign that something is wrong, the x11-wm/twm and x11-terms/xterm packages can be installed only to test X.

Once the programs are installed, run startx again. A few xterm windows should appear, making it easy to verify the X server is working correctly. Once satisfied with the results, depclean x11-wm/twm and x11-terms/xterm if installed in the step above to remove the testing packages. They will not be needed to setup a proper desktop environment.

The session (program to start) could also be given as an argument to startx :

You can also pass X11 server options, by preceding them with a double dash:

Tweaking X settings

Setting the screen resolution

If the screen resolution looks to be wrong, you will need to check two sections in your xorg.conf.d configuration. First of all, you have the Screen section which lists the resolutions that your X server will run at. This section might not list any resolutions at all. If this is the case, Xorg will estimate the resolutions based on the information in the second section, Monitor.

Now let us change the resolution. In the next example from /etc/X11/xorg.conf.d/40-monitor.conf we add the PreferredMode line so that our X server starts at 1440x900 by default. The Option in the Device section must match the name of your monitor ( DVI-0 ), which can be obtained by running xrandr . Install xrandr ( emerge xrandr ) just long enough to get this information. The argument after the monitor name (in the Device section) must match the Identifier in the Monitor section.

Run X ( startx ) to discover it uses the desired resolution.

Multiple monitors

More than one monitor in can be established in /etc/X11/xorg.conf.d/ . Give each monitor a unique identifier, then list its physical position, such as "RightOf" or "Above" another monitor. The following example shows how to configure a DVI and a VGA monitor, with the VGA monitor as the right-hand screen:

Configuring the keyboard

To setup X to use an international keyboard create the appropriate config file in /etc/X11/xorg.conf.d/ . This example features a Czech keyboard layout:

For methods of switching the keyboard layout see the Keyboard layout switching article.

The "terminate" command ( terminate:ctrl_alt_bksp ) lets users kill the X session by using the Ctrl + Alt + Backspace key combination. This will, however, make X exit disgracefully -- something that users might want to avoid. It can be useful when programs have frozen the display entirely, or when configuring and tweaking the Xorg environment. Be careful when killing the desktop with this key combination - most programs really do not like it when they are ended this way. Some, if not all, of the information that has not been written to the disk (information stored in "open documents") will be lost.

For more information about XkbModel and XkbOptions , consult /usr/share/X11/xkb/rules/base.lst and man xkeyboard-config .

Finishing up

Run startx and be happy about the result. Congratulations, you now (hopefully) have a working Xorg! The next step is to install a useful window manager or desktop environment such as KDE, GNOME, or Xfce. Information on installing these desktop environments can be found here on the wiki.

See also

    — a simpler and modern replacement for X display server. - The Security Handbook's entry on securing the X server.

External resources

Creating and editing config files

man xorg.conf and man evdev provide quick yet complete references about the syntax used by these configuration files. Be sure to have them open on a terminal when editing Xorg configuration files!

Example configurations can be found at /usr/share/doc/xorg-server-*/xorg.conf.example.bz2 .

There are also many online resources on editing config files in /etc/X11/ . Only a few are listed here; use a favorite search engine to find more.

Other resources

More information about installing and configuring various graphical desktop environments and applications can be found in the section of our documentation.

When upgrading to xorg-server 1.9 or higher, be sure to read the migration guide.

Одним из знаменательных Linux событий прошлого года стал выход 25-й Федоры с графическим окружением Gnome 3.22 на базе дисплейного сервера Wayland, который призван заменить X Window System. Но зачем вообще после стольких лет возникла такая необходимость?



В последнее время экипаж МКС пересел с Windows на Linux.
— Хьюстон, у нас проблемы. Нас сносит на Юпитер.
— Вы что, опять возились с xorg.conf?
— Да. Хьюстон, за три последних дня у нас почему-то выросли бороды.

Далее, речь о том, почему Linux необходима новая графическая среда, хотя бы в 2017 г, а отдельным постом я расскажу про Wayland и Mir.

Номенклатура X

Я уверен, что вы уже прочитали статью Хабрапост про графический стек Linux, а также страницу на Вики и теперь можете уверенно двигаться дальше. Ну, а если пока оставили в закладках, позвольте вкратце напомнить.


  • DIX — Device Independent X, что переводится как X не зависящий от устройств, в основном это программный рендеринг.
  • DDX — Device Dependent X, что переводится как X зависимый от устройств, взаимодействие с графической картой, устройствами ввода.

Еще немного тезауруса о технологиях, благодаря которым современное графическое окружение Linux держит свою марку.

Mesa — Реализация OpenGL, OpenCL и Vulkan API для Linux и Unix, включающая в себя как программные библиотеки, так и набор драйверов видеокарт. Mesa имеет и умеет много чего, но в основном это открытая реализация OpenGL API, для трансляции которого в исполнительные команды используются программные:

  • swrast — устаревший и слишком тормознутый,
  • softpipe — средне,

lvmpipe — может и быстрый,

и аппаратные бэкенды с помощью открытых драйверов intel, radeon и noveau.

Всемогущий X

Программирование на X — это как чтение французских философов, после этого начинаешь задаваться вопросом: что я на самом деле знаю?
Томас Турман.

Кому на сегодняшний день позарез нужны иксы? В Android телефонах, телевизорах, планшетах X Windows System не используется, Хромбуки тоже как-то без них обходятся. Значит речь идет только о Linux / Unix рабочих станциях, в основном по той причине, что тулкиты GTK+ и QT, долгое время не могли обходиться без X.

В этом году X11 исполняется 30 лет. Секрет живучести X Window System в следующих принципах, сформулированных в 1996 г.

  • Добавляй новую функциональность только в том случае, если без нее нельзя завершить уже существующее приложение.
  • Решить, чем система не является, столь же важно, сколь решить, чем она является. Не пытайся удовлетворить все мыслимые потребности; вместо этого сделай систему расширяемой, чтобы новые потребности могли быть удовлетворены совместимым образом.
  • Хуже обобщения одного примера может быть только обобщение вообще без примеров.
  • Если проблема не понята до конца, возможно, лучше не решать ее вовсе.
  • Если ты можешь добиться 90 процентов нужного эффекта, затратив всего 10 процентов сил, используй более простое решение.
  • Изолируй сложные места как можно тщательнее.
  • Обеспечивай механизм, а не политику. В частности, клиент должен определять политику пользовательского интерфейса.

Сочетание этих принципов позволило X11 быть невероятно гибким и масштабируемым решением для столь разных графических оболочек Unix в течении долгого времени. Особенное место занимает последний — обеспечить механизм, для того, чтобы X-клиент смог реализовать все свои затеи. Обратной стороной такой всеядности и живучести стало невероятное нагромождение устаревших стандартов, методов и технологий. Можно вспомнить сервер шрифтов вместе с XLFD или движок для отрисовки многоугольников и разноцветных полос.

Изначально X был государством в государстве и подменял собой множество функции ядра ОС:




  • Modesetting
  • 2D/3D ускорение
  • Ускорение рендеринга видео
  • Напрямую взаимодействует с GPU как root
  • Управление памятью
  • Привязка клавиатуры
  • Устройства ввода
  • Clipping

Из все этого списка, пункт первый являлся корнем всех добродетелей и зол, так как ни одна другая графическая система с открытым ПО не сумела решить эту задачу для всех платформ. Сейчас почти весь этот список в ядре, в том числе и modesetting , но позади долгий этап планомерного принуждения иксов к миру, то есть к разумному сосуществованию в окружении GNU/Linux.

Некоторое время всех все устраивало, программисты ваяли стильные приложения, примерно такие.




Затем внезапно устройства стали более быстрыми, мощными и сложными: несколько GPU, мониторов, разношерстые устройства ввода. Рендеринг также стал более сложным, появился OpenGL. X Window system стала обрастать расширениями, однако ядро протокола по политическим мотивам осталось нетронутым. На все недостатки находились обходные пути, и пошло и поехало… BIOS видеокарты, порты I/O, подсистема питания. И всем этим хозяйством X управлял из рук вон плохо, превратившись в ОС внутри ОС, причем достаточно паршивую ОС.

  • Монолитный X разбили на несколько частей. Ну как несколько… 345 git модулей. Правда большая часть из этого в итоге оказалось не нужна.
  • Затем пошла зачистка кода. Xserver 1.0.2: 879,403 строк кода, в 2013-м уже осталось 562,678. По оценке же Кита Пакарда выпилено аж 500 тыс. строк кода. Кто-нибудь из-за этого огорчился?
  • Modesetting, управление памятью, поддержка устройств ввода, все ушло в кернел. Привязка клавиатуры, правда, все еще в иксах из-за своей невероятной сложности. Кто-то советовался с Джа, когда придумал это.

Какие-же функции остались за X сервером после всех этих трансформаций? В принципе не так уж много. По сути основная работа иксов состоит в том, чтобы посредничать между X-клиентом и WM — оконным менеджером. Клиентская программа рисует фрейм, X сервер передает данные WM, который рендерит кадр, определяет местоположение окна и передает обратно серверу, который показывает готовый результат. Основную работу сейчас делает именно WM, и напрашивается вопрос. А что случится, если мы уберем посредника? Ответ — Wayland.

Состояние гонки

В силу своей асинхронности X11 предрасположен создавать состояние гонки между событиями X-клиента или между быстрым и мертвым тормознутым X-клиентом. Возьмем простейший случай: пользователь щелчком левой кнопки мыши вызывает меню приложения, затем отпускает кнопку и приложение при наведения курсора выполняет определенное действие. Покажем последовательность событий на диаграмме Фейнмана.

  1. Пользователь щелкает левой кнопкой мыши.
  2. Сервер посылает событие ButtonPress приложению.
  3. Приложение вызывает MapWindow для показа меню.
  4. Сервер открывает окно с меню приложения.
  5. Сервер посылает приложению событие Expose .
  6. Приложение рисует картинку с меню.

На диаграмме видно, что произойдет, если пользователь отпустит левую клавишу раньше события 4. Если натренированный на действие пользователь заранее переместился на место предполагаемого пункта меню до того момента, пока там возникло новое окно, то тогда произойдет состояние гонки mouse ahead. Событие ButtonRelease придется на еще не занятую новым окном область экрана. Это вполне вероятно на удаленных X-сессиях по медленной сети.

Указанный выше сценарий благополучно завершится без состояния гонки при использовании synchronous grab , т. е. синхронного захвата, который ставит на паузу все события с устройств ввода, точнее буферизирует их. Однако в более сложных сценариях и это не помогает. К тому же от этого страдает производительность приложения.

Промежуточные итоги




Вместе с тем создатели иксов явно где-то перемудрили. Принцип обеспечения механизмов, но не политики впоследствии сыграл злую шутку с экосистемой X и она обросла всем тем, чем обросла. За десятилетия ландшафт компьютеров, устройств и ПО радикально изменился, а X Window System проникла на лаптопы и даже смартфоны Нокиа. До сих пор разработчикам вполне удавалось держать проект на плаву, благодаря миграции значительной части функционала в ядро. Этот ресурс уже тоже исчерпан, и в силу вступил неумолимый закон убывающей отдачи. Наконец-то есть возможность начать с чистого листа, догнать и перегнать тренд, вместо того, чтобы плестись за ним. Я также связываю с этим давно обещанный прорыв Linux на десктопы. Закономерность или случайность, но Linux имеет полное доминирование на устройствах, где нет X сервера.

Как должна происходить замена X Window System на Wayland или Mir? Нельзя так просто дать готовый рецепт, но можно сказать как не должно поступать. Чтобы без хейтеров и фанбоев, без шоковой терапии и подозрительных двадцати раундов голосования с итоговым перевесом в один голос. Без раскола сообщества. Словом, без всего того, что имело место при замене систем инициализации на systemd . А вы как считаете?

Читайте также: