#1 11.09.06 10:44
опитимизация кде
Укроп написал(а):
Performance Tips
This page describes some tips to improve KDE performance
правка печать
Table of Contents
o Introduction
o Don't try to optimize too much
o A fast system makes KDE run fast
o Reducing number of running applications
o Removing applications from the Autostart folder
o Removing docked applications (in systray)
o Alarm daemon and KOrganizer alarm client
o KHotKeys
o Artsd
o KXKB
o Reducing startup time
+ KDE startup sound
+ The KDE splashscreen
+ Konqueror reusing
+ Konqueror preloading
+ Scanning for Netscape plugins
+ Directory prescanning in KDM
+ Faster startup of KDE applications outside of KDE
+ Turning off system configuration startup check (kbuildsycoca)
+ Avoid very long delays by startup
o Various KDE settings
+ Desktop background
+ Disabling various eye-candy features
+ Antialiasing
o Not really KDE things but worth checking anyway
+ malloc()
+ Fonts (fontconfig)
+ Key composing (XIM)
+ /tmp/.ICE-unix
+ DMA for disk access
Introduction
This page is a list of tips how to improve KDE performance.
KDE is constantly being optimized, and every new KDE version is generally perceived as being more efficient than older versions. However, many aspects of KDE performance depend on the underlying system or configuration, which KDE usually cannot affect. This page lists some of the related issues together with instructions how to avoid or fix the problems.
If you would like to add new tips to this page, update the ones already listed, or discuss them, please use the kde-optimize@kde.orgexternal link mailing list. Do not edit the content of this page (except for small changes like fixing typos or improving formatting) without approval.
Don't try to optimize too much
Take care, especially if you're less experienced. It is possible to change your settings so much that KDE won't work correctly anymore. For example, don't remove things from the startkde script unless you have a way to roll back your changes from the shell if something unexpected happens. Most of the tips have a short summary of the benefits and disadvantages of following them. Evaluate the potential value of implementing tips, and the risks too, if any.
A fast system makes KDE run fast
This may seem obvious, and may not appear to be a performance tip, but it is in fact the thing that is guaranteed to make the biggest performance improvement, and that's why it is here, whether one likes it or not. A computer with 1GHz processor and 256MB RAM (a configuration which is probably not even being offered by shops these days anymore) is perfectly sufficient for decent KDE performance.
Computers get more powerful, and more features, faster development times and better quality result in more demanding software. KDE will probably never run acceptably on a 100MHz 32MB RAM computer, just like Microsoft Windows 95, almost ten years old software by now, has never run acceptably on PC i386 with 4MB RAM, which would be more than enough for software twenty years old.
KDE is mostly developed by volunteers working on KDE in their spare time. And optimizing software is a difficult, time-consuming and tedious work. People who think KDE is too slow and inefficient are welcome to join and work on optimizing KDE even further.
It is also not fair to compare KDE to environments such as WindowMaker, because that is like comparing a Jumbo Jet and a glider. A glider may be perfectly fine for some people, but it is not going to fly several hundred people thousands of kilometers away. The same way WindowMaker is not going to help in any way with developing applications or having a consistent GUI. In fact WindowMaker with several applications running using different development frameworks may be eventually more resource demanding than the KDE equivalents.
A system is not only the hardware, but also the software. KDE should not be expected to run at its maximum performance on a system which is already several years old. While new features in new software versions may have negative performance impact, software is also being optimized and problems are being fixed. For example Linux kernel version 2.6 is generally perceived as having better performance than version 2.4. Also KDE may rely on new features or fixes in system libraries in order to perform better. The same way KDE itself is constantly being improved and optimized, and newer KDE versions generally have better performance (some of the tips listed below rely on a certain minimal KDE version).
Reducing number of running applications
Every KDE application (process, to be precise) requires certain amount of memory to run and certain time to start up. Therefore reducing their number will reduce memory usage, and if they're started during KDE startup, also reduce KDE startup time.
In Konsole, do 'ps x', or use KDE System Guard, you'll see a list of all processes you're running as the user. Processes that are required for KDE desktop are startkde, kdeinit (shown as 'kdeinit: Running...' in the 'ps ux' output), dcopserver, klauncher, kded, ksmserver (shown twice, once as 'kwrapper ksmserver'), knotify, kwin, kdesktop and kicker. You may also ignore kioslaves (kio_file etc.), as those are automatically terminated after being idle for some time. Some of the remaining processes may be required for functionality you expect from KDE, but you can check the list and find processes that you don't need.
Removing applications from the Autostart folder
Visit the directory /opt/kde3/share/autostart/ (this assumes that /opt/kde3 is the KDE installation prefix). The desktop files located there will be started automatically when the KDE desktop starts. Remove the desktop files you don't need. If you don't want to delete them, create a new folder /opt/kde3/share/autostart_bak/ and move the desktop files you don't need there.
Note that many of the files specify a startup condition, which allows turning them off from the GUI, without removing the file. Also note that several core components such as the panel are started this way, so removing entries without knowing what they do may result in reduced KDE functionality.
Removing docked applications (in systray)
Most of systray icons represent one application, so you can try removing as many of those as possible. Moreover there are panel applet equivalents for many docked applications, so you won't lose the functionality in such cases (in fact some of the applets may be even considered superior), and panel applets don't require their own process.
Note that some docked applications need to be explicitly disabled in their configuration in order not to be started after next KDE startup, or you need to confirm while removing them that you don't want them to restart next time.
Using applets instead of docked applications reduces KDE startup time and memory usage.
Alarm daemon and KOrganizer alarm client
You can turn off the alarm daemon and KOrganizer alarm client if you don't need them. Alarm daemon is turned off in the control center in KDE Components/Service Manager. For the KOrganizer alarm client, right click on it, disable 'Start Alarm Client at Login' and quit it.
Disabling alarm daemon and KOrganizer alarm client will reduce KDE startup time and memory usage at the expense of not having alarms.
KHotKeys
If you have running process 'khotkeys', it's used for starting applications from K-Menu using keyboard shortcuts. In KDE 3.2 it's also responsible for mouse gestures. If you don't want it running, delete all actions in the KHotKeys KControl module, or delete file $KDEHOME/share/config/khotkeysrc.
KDE 3.4 and newer: KHotKeys has been turned into a KDED module, which means it no longer runs in its own process. Therefore this tip applies only to KDE 3.3.x and older.
Disabling KHotKeys will reduce KDE startup time and memory usage at the expense of not being able to assign keyboard shortcuts for launching K-Menu entries or to use mouse gestures.
Artsd
Disable the artsd sound server in its control center module. Note that obviously without the sound server running, applications using aRts for sound won't work, so this is useful mainly if you don't use aRts or don't have a soundcard.
Note that many multimedia applications can be configured to use other sound system than aRts, or don't depend on aRts at all. Also, for system notifications, you can configure an external player for the sounds instead of aRts (in the System Notifications control module, use the Player Settings button, and enter e.g. "aplay" for using ALSA play directly).
Disabling artsd startup will reduce KDE startup time and memory usage at the expense of having no sound in aRts applications.
KXKB
If you're using KXKB, the docked application for keyboard layouts, you may try disabling it, and either configuring your keyboard layout directly in the XF86config file (consult its manual page), or adding shell script calling setxkbmap (consult its manual page) to your Autostart folder.
Disabling KXKB reduces KDE startup time and memory usage.
Reducing startup time
KDE startup sound
Turning off the KDE startup sound will slightly reduce the KDE startup time. The KDE startup sound can be disabled in the System Notifications control module, either by turning off all sounds, or by selecting "KDE System Notifications" as event source and turning off only the sound for the "KDE is starting up" event.
KDE 3.4: A special code handling events during KDE startup has been added, which should delay startup of the KNotify notification daemon in case all those events are configured to be turned off. So turning off the KDE startup sound will additionally avoid one KDE process started during KDE startup, making KDE startup faster.
The KDE splashscreen
Try disabling the splashscreen shown during KDE startup. Currently, you can do so only by editing the startkde script. As user root, modify $KDEDIR/bin/startkde and remove the line saying 'ksplash --nodcop'. Note that disabling the splashscreen may actually make KDE startup seem to take longer because of the missing feedback.
KDE 3.4: In the list of available splashscreens in its control module, there are two options "None" and "Simple", first of them turning the splashscreen off completely, second selecting a very simple optimized splashscreen.
Disabling ksplash reduces KDE startup time.
Konqueror reusing
In order to reduce time needed for opening new Konqueror windows, Konqueror may be configured to reuse already running processes instead of starting new ones. The setting in the control center in File Browsing/File Manager (the 'Minimize Memory Usage' radio buttons). It may be set to 'Never', which disables Konqueror reusing and always starts a new instance, making all Konqueror windows independent, and when one of them crashes, others are unaffected. Next two values are 'For local browsing' and 'For web browsing', which will reuse already running Konqueror instance (if there's any) if you requested to open a new window for browsing local files or web pages respectively. The last value is 'Always', causing Konqueror processes to be reused independent of what you're browsing. The default value is reusing for local browsing, which should be safe. Unless you're experiencing Konqueror crashes, you can try setting it to 'Always'. In such case it may also help to have always one Konqueror window open unused.
Having Konqueror configured for reusing processes often reduces memory usage and time needed for opening new Konqueror windows, at the expense of losing more Konqueror windows in case of a crash.
Konqueror preloading
Another possibility reducing time needed for opening new Konqueror windows is enabling so-called Konqueror preloading. With the option enabled, when a Konqueror process should be terminated because its last window is closed, it will be kept running without a window only hidden, and reused next time a Konqueror window is needed. The setting is in the Performance tab in Konqueror's settings, or in the Control Center in KDE Components/Performance. It is possible to specify maximum number of instances kept in the background, and whether such instances should be even explicitly loaded for preloading, for example at KDE startup.
Enabling Konqueror preloading often reduces time needed for opening new Konqueror windows, at the expense of having memory used by Konqueror even if no window is open.
Scanning for Netscape plugins
It's possible that your KDE is configured to scan for new Netscape plugins during every startup, which is unnecessary and may be turned off (you'll have it run it manually in such case when there will be changes though). Check that your startkde script doesn't contain any call to nspluginscan. Also check in Konqueror's settings that in the module Plugins that the checkbox "Scan for new plugins at KDE startup" is disabled. There's also a button for manual search in case you installed a new plugin.
Disabling scanning for Netscape plugins reduces KDE startup time.
Directory prescanning in KDM
Loading data from disk is slow, especially when disk seeks are involved (e.g. when
searching directories). During KDE startup a large amount of data needs to be loaded,
and many files need to be accessed. The impact of disk reading can be demonstrated
by the fact that when starting KDE, immediately logging out and starting KDE again,
the second startup takes only half the time on the average. This is caused by recently
accessed disk data being stored in memory caches, which considerably speeds up
repeated attempts to read this data.
KDM, the KDE login manager, offers the possibility to start a task that will be running
in the background while the login screen is either idle or while the login information
is being filled in, and this task will be terminated right before KDE loading starts.
It is possible to configure a task that will read data that are accessed during KDE
startup, thus loading them into memory caches and reducing the number of disk accessed
during the actual KDE startup.
The command to run is specified in KDM's configuration file, usually /opt/kde3/share/config/kdm/kdmrc or /etc/opt/kde3/share/config/kdm/kdmrc (this tip assumes KDE is installed in /opt/kde3 - all paths need to be modified if the location is different). The options should be specified in the group [X-*-Greeter] as 'Preloader=command', where command can be e.g. '/opt/kde3/bin/preloadkde'.
The actual script should contain something like:
exec find /etc/opt/kde3 /home/user/.kde /opt/kde3/share/applications \
/opt/kde3/share/applnk /opt/kde3/share/mimelnk /opt/kde3/share/services \
/opt/kde3/share/servicetypes /opt/kde3/share/config \
/opt/kde3/share/icons /opt/kde3/
/home/user is the home directory of the user who uses the computer (this assumes there is only one user on the computer using KDE). If there are more users, it might be better to avoid specifying any home directory.
Warning: The 'exec' in the script is necessary. The script should not start any subtasks, as they will not be terminated by KDM before launching KDE. That would result in actually slowing KDE startup.
Note that this option has no effect if KDM is configured to perform automatic login, because there is no idle period during which the data could be read from the disk.
Also, massive disk accessing in the background may slightly affect the responsiveness of the foreground application, making KDM feel slightly less responsive. As keyboard input is queued for processing, this should not be a problem in practice though.
A mechanism for the Linux kernel is currently being developed that will precache disk contents needed during startup.
Prescanning directories in KDM reduces KDE startup time, but may make KDM appear to be slightly less responsive.
Faster startup of KDE applications outside of KDE
KDE applications usually require several small KDE daemons (kdeinit, dcopserver, klauncher, kded) to be running. These daemons are launched during first phases of KDE startup, so they are normally available in a KDE session. However when a KDE application is launched outside of KDE, and these daemons are not running (i.e. no other KDE application is running), they need to be launched first. This makes the startup of the KDE application somewhat longer. Since the daemons automatically terminate after a small delay when the last KDE application running exits, repeated usage of a single KDE application outside of KDE can make its startup appear longer than it really is.
In order to avoid this, KDE daemons can be launched manually, in which case they will remain running even if no KDE application is running. This can be achieved by running 'kdeinit'. This command should be launched in some startup script, or specified as startup command in the GUI used (using some equivalent of KDE's Autostart folder).
One problem with having KDE daemons running permanently is the fact that some of them keep a connection to the X server, which for example prevents logout from ssh session with X forwarding. To avoid this problem, the daemons should be terminated manually by running 'dcopserver_shutdown' (this command should be specified in a logout script).
Keeping KDE daemons running permanently in non-KDE GUI will reduce startup time of KDE applications at the expense of more memory used.
Turning off system configuration startup check (kbuildsycoca)
KDE system configuration (installed applications, mimetypes, etc.) is specified as many so-called .desktop files. This has several technical benefits, but the disadvantage is that checking and using so many files has a negative performance impact. For this reason KDE includes a mechanism called KSyCoCa (KDE System Configuration Cache), which is a single file that stores all the information provided by .desktop files in a format which is very efficient to use. This avoids the performance problem for KDE applications.
For obvious reasons it must be ensured this file does not contain obsolete information. Therefore while KDE is running, a daemon watches for changes in the .desktop files, and triggers rebuilding the ksycoca file in such case. However, during KDE startup, it is not known if the .desktop files have changed since the last time or not. Any application, even a non-KDE one, can install new .desktop files, and there's no mechanism to check for updates if KDE is not running. Therefore a check of all the files needs to be done during KDE startup. This check is very optimized in the usual case (only a check of timestamps), however searching many directories with files is inefficient.
KDE allows disabling this check of the .desktop files, in the Performance module in the Control Center. The option will delay the check by 60 seconds, thus avoiding searching of the directories during KDE startup. This option can lead to problems in rare cases though, these problems include missing applications in the K Menu, missing mimetypes, and similar. Since changes to .desktop files mostly happen by installing and uninstalling applications, it is recommended this option is at least temporarily turned off during doing so (alternatively, it is possible to run 'kbuildsycoca' manually as the user before logging into KDE, or waiting 60 seconds before using newly installed software).
Due to these possible problems, the usage of this option is not recommended, and is meant only for people who are aware of the possible problems and want to reduce KDE startup time as much as possible. The KDE crash handler will refuse to provide a backtrace in case it detects this option is turned on (unless it is configured to run in the developer mode), and you will need to turn the option off and reproduce the problem again in order to get a backtrace for the bugreport.
This option also affects launching KDE applications outside of KDE in case no other KDE application is used. In such case several small KDE daemons need to be launched first, and checking of .desktop files is done by one of the daemons. In this case it is however recommended to have the daemons running permanently for even better (see the tip dedicated to this case).
Note that the prescanning in KDM described in another tip also reduces the benefits of disabling system configuration startup check.
Turning off system configuration startup check reduces KDE startup time, but may in rare cases lead to various problem, and as such its usage is discouraged.
Avoid very long delays by startup
If the loopback interface is not configured, KDE startup could easily take 10 minutes, probably due to the fact, that it tries to reach localhost, without success... As there is no error message, and later the system is fully functional, it's pretty hard to find out what went wrong... So if you experience such an 'endless' delay by startup, check '/etc/network/interfaces'... Or simply do a 'ping localhost'...
Various KDE settings
Desktop background
Use only single color or simple horizontal/vertical gradient for desktop background, with no wallpaper.
Using simple desktop background will reduce KDE startup time and memory usage.
Disabling various eye-candy features
Obviously, KDE without fading menus, transparency, animated icons and similar should run somewhat faster.
* How do I configure this?
o Open Control Center.
o Go to Appearance & Theme and click on Theme Manager.
o Find Customize your theme: at the bottom of the window. Click on Style.
o Choose tab Effects.
o Uncheck Enable GUI effects.
o Click OK.
o Hint: This change will only affect newly started applications.
Antialiasing
Having antialiasing (AA) turned on slows down drawing of texts, so you may consider turning it off in the control center, in the fonts module.
Not really KDE things but worth checking anyway
malloc()
Function malloc() is responsible for dynamic allocation of memory, and is called very often in KDE applications. KDE therefore performs worse on systems with inferior malloc() implementations. For this reason KDE includes its own optimized version of malloc(), which may be enabled during building the kdelibs package by using the --enable-fast-malloc configure switch. Consult file kdelibs/kdecore/malloc/README for details.
This option is not necessary with Linux kernel v2.6 and glibc-2.3, it however provides noticeable performance boost with glibc-2.2. It is possible this option provides performance boost also on other platforms.
Note: In rare cases, there may be conflicts between the system and KDE versions of malloc, leading to crashes.
Fonts (fontconfig)
Current versions of the fontconfig library have rather inefficient handling of fonts, meaning that the more fonts are installed, the longer and the more memory will every KDE application use. Therefore removing as many fonts as possible will improve KDE performance.
As root, run 'fc-cache -v', which will list directories where fontconfig looks for fonts, and the number of fonts in each of those directories. The first step is to uninstall unnecessary font packages using the package management for your distribution. More experienced users can selectively remove fonts manually from the directories.
Truetype fonts should be in general preferred to bitmap fonts, because you don't need different versions of the same font for different sizes. Also, bitmaps fonts often tend to be compressed (.pcf.gz), so they additionally need to be uncompressed by the application before being usable.
Warning: Removing fonts may seriously affect the appearance of your desktop, or even make it completely unusable if you remove important fonts. Reducing the number of fonts reported by fc-cache to less than 100 already requires a lot of checking.
KDE 3.3: KDE has a workaround in kdeinit which tries to reduce the impact of this fontconfig inefficiency. For this workaround to work, at least fontconfig version 2.2.3 (or development version 2.2.96) needs to be installed.
Fontconfig developers have been notified about the problem (http://freedesktop.org/pipermail/fontconfig/2004-June/000937.htmlexternal link), however it's not known when this problem will be fixed.
Reducing number of installed fonts will reduce memory usage and startup time of KDE applications. As long as only unused fonts are removed, there should be no negative effect.
Key composing (XIM)
In many languages, some characters are not entered by pressing only a single key (possibly with some modifiers pressed), but by a sequence of keys. This applies e.g. to accented characters, when first a key with the accent needs to be pressed, and then the key with the unaccented version of the character. Current versions of X11 libraries responsible for this key composing have a rather inefficient handling of the list of such compositions, especially in UTF8 locales where the composition table is very large.
Users can install their own version of the composition table in file .XCompose located in their $HOME directory. If you don't use composing (or don't know what it is), you can simply create empty .XCompose file. In other cases, it is possible to copy a compose file from the standard location (/usr/X11R6/lib/X11/locale/encoding/ , where encoding is the locale's encoding, or en_US.UTF-8 for UTF8 locales).
For users without knowledge to edit the file manually, it is possible to use this scriptexternal link which will create a subset of the full UTF8 compose file (in Konsole, 'echo $LANG' should reveal if UTF8 locale is used or not - it is in most recent distributions). The script needs to be run as './compose_locale_subset.sh Compose.utf8 Compose.locale >Compose.new', and the script will try to find all entries from the locale file in the UTF8 file and output them (it is not possible to use the locale compose file directly because it is not in the UTF8 encoding). Since most people need compositions only for their language, this locale subset should be sufficient.
Additionally, the compositions involving the Compose key (Multi_key) may be removed too if they are not used. This can be achieved by running 'cat Compose.old | grep -v 'Multi_key' >Compose.new'.
For your convenience, there are resulting files for X.Org version 6.8.1 for some locales provided at http://ktown.kde.org/~seli/ximexternal link .
X.Org developers have been notified about the problem, and a patch fixing the issue is being developed.
Using a smaller XIM compose file will reduce startup time and memory usage of KDE applications, at the expense of not having all compositions available.
/tmp/.ICE-unix
Make sure the directory /tmp/.ICE-unix exists, is owned by user root and has permissions 1777 (accessible to all and sticky). The command 'ls -ld /tmp/.ICE-unix' should show something like
drwxrwxrwt 2 root root 176 2003-01-06 21:25 /tmp/.ICE-unix/
First, third and fourth columns should be like shown above. When this directory isn't created correctly, you may also see message 'IceTransmkdir: Owner of /tmp/.ICE-unix should be set to root' in your ~/.xsession-errors file.
To fix the problem, put the following commands in your system startup scripts (e.g. /etc/init.d/boot.local or /etc/rc.d/rc.local):
chown root:root /tmp/.ICE-unix
chmod 1777 /tmp/.ICE-unix
Note that with the latest version of the X.Org XServer your desktop will be unusable without properly setup /tmp/.ICE-unix, so this problem will hopefully soon become a history.
Having correctly setup /tmp/.ICE-unix saves 5 seconds from the startup time.
DMA for disk access
Make sure that you have not disabled DMA (Direct Memory Access for transfers) for disks. While most modern distributions already enable this by default, and modern disks should not have any problems with it, DMA may be still disabled by default on some systems. Some distributions have configuration tools for DMA, or you can check and setup it manually.
As user root, type 'hdparm /dev/hda', where /dev/hda is your disk device. It should also print line 'using_dma = 1 (on)', if it says 'off', you could try turning it on. In order to turn DMA on, type 'hdparm -d1 /dev/hda' (use 'hdparm -t /dev/hda' to check disk throughput). Note that if you explicitly need to turn DMA on, you'll have to do it after every boot, so you should put the command in your system startup scripts. Consults the manual page for hdparm for details and possible problems, especially options -c, -d, -X, -k and -m.
On Redhat and Redhat-like systems, uncomment the line USE_DMA=1 in the file /etc/sysconfig/harddisks to enable DMA with each boot.
FreeBSD variant (from Mark Rowlands): Type 'sysctl hw.ata.ata_dma', it should return 1 indicating disk is using DMA. If it's not set, put 'hw.ata.ata_dma=1' in your /boot/loader.conf. You may also check hw.ata.wc and hw.ata.tags. Please consult manpages for ata(4), atacontrol(4) and sysctl(8) for details and possible problems.
Extra tuning parameters: There exists two more commonly unused optimizations with IDE hard drives. The first is the -c option, which turns on 32 bit transfers across the BUS / VLB to the interface card. "hdparm -c1 /dev/hda" is the fastest option, -c3 works for buggier hardware/drivers. The other option is slightly more dangerous and one should definitely consult the man pages before using it: "hdparm -u1 /dev/hda" sets the unmask irq flag on the drive. From the man pages: "This permits the driver to unmask other interrupts during processing of a disk interrupt, which greatly improves Linux's responsiveness".
People from #kde-freebsd also pointed out http://www.freebsd.org/cgi/man.cgi?tuningexternal link as a good manpage about general FreeBSD tunning.
Having DMA enabled decreases CPU usage and increases disk throughput.
Contributors to this page: bygdog708 points , luci1428 points , JeramyRutley6 points , Seli72 points , cm488 points and 0 points .
Последнее изменение старницы Суббота 26 of Август, 2006[00:43:43 UTC] автор bygdog708 points .
The content on this page is licensed under the terms of the GNU Free Documentation License.
Это не я бляяя...
Offline
#2 11.09.06 10:45
Re: опитимизация кде
Укроп написал(а):
то такое WM, DE и чем они отличаются? Что лучше?
Есть X-сервер (XFree86, xorg). Он отвечает за устройства ввода-вывода, графику и вывод окон.
А еще есть менеджеры окон и рабочие среды, которые отвечают за поведение окон, число рабочих столов, вид окон, иными словами, за поведение и вид. К числу менеджеров окон можно отнести FluxBox (да любой *box), IceWM, Window Maker, FVWM, AfterStep и прочее. К группе вторых относятся вторым - KDE и Gnome, ну может еще XFCE. Где-то отдельно стоит Enlightenment - он вроде как теперь проходит по спецификациям к рабочим средам, но программ под его API почти нет.
Аббревиатура WM переводится как Window Manager (менеджер окон), коротко и довольно доступно об этом написано здесь или здесь, вот кусочек:
X-сервер -- программа в определенном смысле довольно глупая. Все, что он умеет -- это выделять программам прямоугольные области экрана ("окна") и рисовать в них то, что программы попросят; плюс он знает, что одно окошко может располагаться поверх другого, и правильно их отрисовывает.
Но ведь надо еще изобразить рамку вокруг окошка, заголовок над ним, уметь "сворачивать" окно в пиктограмму и еще многое другое. Этим занимается специальная программа, называемая "Window Manager" (дословно - "менеджер окон").
В список функций хорошего window manager'а входят: декорирование окон (бордюр, заголовок, кнопочки), манипуляции с окнами (перемещение, изменение размера, свертывание в пиктограмму и т.д.), разнообразные меню и панели инструментов (например, для запуска программ), виртуальный экран.
Аббревиатура DE переводится как Desktop Environment (рабочая среда), на пальцах объясню - криво и коряво, зато понятно:
Рабочие среды имеют свои библиотеки (GTK, QT) и средства для более легкого создания приложений и их более тесной интеграции (собственный API). Соответственно, если я беру и собираю тот же licq с поддержкой KDE, то он будет убираться в трей, вызывать kmail, работать с Konqueror и получит поддержку arts. Если нет - получим тоже рабочее приложение, но без таких вкусностей.
Если программа собрана под рабочую среду, ее запуск и работа возможна и в оконном менеджере, но она утащит за собой необходимые библиотеки из своей рабочей среды. Например, kppp утащит kdeinit, а тот - kaccess и кучу еще всего, а StarDict (который работает только с Gnome) возьмет с собой еще и bonobo-activation-server.
Кстати, если программа написана к примеру на GTK, это еще не значит, что она написана под Gnome. Во-первых это значит, что такая программа не обязательно будет "прятаться в трей" и т.д. в этом самом Gnome, и во-вторых - она не будет "тянуть за собой" его сервисы.
Многие менеджеры могут собираться с поддержкой рабочей среды - тогда программы из сред смогут работать корректнее - например, убираться в тот же трей менеджера (который работает иначе, чем у рабочей среды).
В принципе, DE - это более прогрессивный (хоть и не unix-way) подход, если проблем с ресурсами нет, проще поставить рабочую среду.
Если хочется чего-нить эдакого, а используемые программы в рабочей среде не нуждаются, можно ставить что нравится.
Вопрос же о том, что лучше WM или DE весьма спорный - эффективно работать можно и там и там, а вопрос красивости - это дело вкуса (многим просто НЕ нравится тот-же KDE на генном уровне). Т.е. стоит попробовать несколько и выбрать то, что /просто нравится именно вам/.
Здесь имеется рейтинг самых разнообразных WM и DE, с описанием и ссылками на их домашние странички.
Несколько интересных, хоть и местами спорных, статей.
"Как поменять Display Manager" в подробностях.
[править]
Размер десктопа = разрешению монитора при переключении разрешения. Это возможно? Как поменять разрешение, не завершая X-сервер?
В KDE 3.1.x и выше есть программа "Screen Resize & Rotate". Пускаете ее как апплет, она садится в трей. Ею переключаете разрешение - размер десктопа тоже будет меняться.
Что-то такое планируется (или уже есть) в Gnome.
Или же можно переключить вручную (если wm поддерживает расширение xrandr):
Запустите xrandr, он выдаст нечто вроде:
SZ: Pixels Physical Refresh
*0 1152 x 864 ( 333mm x 252mm ) *78
1 1024 x 768 ( 333mm x 252mm ) 84
2 800 x 600 ( 333mm x 252mm ) 88
3 640 x 480 ( 333mm x 252mm ) 84
4 400 x 300 ( 333mm x 252mm ) 84
5 832 x 624 ( 333mm x 252mm ) 74
6 640 x 512 ( 333mm x 252mm ) 60
7 720 x 400 ( 333mm x 252mm ) 85
8 640 x 400 ( 333mm x 252mm ) 85
9 576 x 432 ( 333mm x 252mm ) 75
10 640 x 350 ( 333mm x 252mm ) 85
11 512 x 384 ( 333mm x 252mm ) 84 75 70 60
12 416 x 312 ( 333mm x 252mm ) 74
13 320 x 240 ( 333mm x 252mm ) 85 75 72 60
14 320 x 200 ( 333mm x 252mm ) 89
15 320 x 175 ( 333mm x 252mm ) 85
Current rotation - normal
Current reflection - none
Rotations possible - normal
Reflections possible - none
Теперь напишете, например, xrandr 1 и вы получите 1024x768 с изменившимся размером окон.
[править]
Как в KDE переключать языки по Ctrl+Shift?
Вообще-то никак :) Лучше выключить эту возможность в KDE, и использовать средства X-сервера, а в качестве индикатора - xxkb или kkbswitch.
Видел предположение, что если в файле /.kde/share/apps/kcmkeys/my.kksrc поменять строку
Switch to Next Keyboard Layout=Ctrl+Alt+K
на
Switch to Next Keyboard Layout=Ctrl+Shift_L;Ctrl+Shift_R
то работать будет как надо. На KDE версий выше 3.1.4 этот способ не работал.
[править]
Как отключить сглаживание шрифтов (anti-aliasing) в приложениях GTK?
Для GTK-приложений - в консоли выполнить export GDK_USE_XFT=0 или прописать эту команду в /.gtkrc. Если после этого приложения перестанут видеть TTF-шрифты, нужно прописать директорию с ними в файле конфигурации X-сервера, либо FontServer'а. Читайте Как настроить шрифты?
Также можно добавить параметр в $HOME/.Xresources
Xft.antialias: false
[править]
Как отключить сглаживание шрифтов (anti-aliasing) в приложениях QT?
Для Qt-приложений можно через Центр Управления KDE - Центр Управления -> Внешний вид -> Шрифты -> Использовать сглаживание для шрифтов (Control Center -> Appearance & Themes -> Fonts -> Use anti-alising for fonts)
[править]
Как включить "нормальное" сглаживание шрифтов (anti-aliasing)?
Из-за проблем с лицензированием алгоритма сглаживания FreeType распространяется с выключенными по умолчанию функциями сглаживания шрифтов, где используются пропиетарные алгоритмы. В нашей России патенты на эти алгоритмы не действуют, поэтому мы можем включить их использование и пересобрать FreeType. В общем случае подойдет способ, описанный [здесь].
В redhat/fedora вы можете поправить соответствующий параметр в spec-файле и пересобрать пакет.
Есть дополнительные способы по улучшению вида шрифтов: http://www.freebsd.org/gnome/docs/faq2.html#q11
[править]
Какие файлы отвечают за внешний вид (шрифт, тема, стиль...) GTK приложений? Дайте пример такого файла.
Это файлы gtkrc. Существуют глобальные настройки и локальные. Локальные хранятся в домашней папке, в файле &.gtkrc, глобальные в /etc/gtk/gtkrc и /etc/gtk/gtcrc.ru.
[править]
Настройки внешнего вида приложений GTK 1.x
Файл /etc/gtk/gtkrc в общем случае выглядит так и трогать его не нужно:
style "gtk-tooltips-style" {
bg[NORMAL] = "#ffffc0"
fg[NORMAL] = "#000000"
}
widget "gtk-tooltips" style "gtk-tooltips-style"
style "gtk-progressbar-style" {
bg[NORMAL] = "#ffffff"
bg[PRELIGHT] = "#a0a0a0"
}
class "GtkProgressBar" style "gtk-progressbar-style"
Файл /etc/gtk/gtkrc.ru выглядит примерно так:
style "gtk-default-ru" {
fontset = "-*-arial-medium-r-normal--12-*-*-*-*-*-koi8-r,\
-*-helvetica-medium-r-normal--12-*-*-*-*-*-koi8-r,\
-*-arial-medium-r-normal--12-*-*-*-*-*-koi8-r,*-r-*,\
-adobe-helvetica-medium-r-normal--12-*-*-*-*-*-koi8-r-*
"
}
class "GtkWidget" style "gtk-default-ru"
Мы можем настроить gtk исключительно под себя, если создадим подобный файл в домашнем каталоге ( /.gtkrc или gtkrc.ru):
include "/home/fagot/.themes/Industrial/gtk/gtkrc"
style "user-font"
{
font="-monotype-arial-medium-r-normal-*-*-140-*-*-p-*-koi8-ru"
}
widget_class "*" style "user-font"
include "/home/fagot/.gtkrc.mine"
[править]
Настройки внешнего вида приложений GTK 2.x
Глобальные настройки зависят от выбранной темы /etc/gtk-2.0/gtkrc:
gtk-theme-name = "Bluecurve"
<verb>
Локальные настройки для приложений GTK 2.x хранятся в ~/.gtkrc-2.0:
<verb>
~/.gtkrc-2.0:
include "/usr/local/share/themes/Default/gtk-2.0/gtkrc"
style "user-font"
{
font_name="sans 12"
}
widget_class "*" style "user-font"
include "/home/sk/.gtkrc.mine"
Файл .gtkrc-kde - раньше был нужен для указания шрифтов GTK-приложений, теперь - нет. Если не ошибаюсь, можно удалить и выключить галку KDE Control Center -> Appearance & Themes -> Apply Colors to non-KDE Applications.
Для некоторых тем кроме "картинок" (из /.themes/Theme-name/gtk-* например) также нужны библиотеки, которые должны быть правильно размещены. При сборке темы следует указать ./configure --prefix=PREFIX, где PREFIX тот же что и у установленного GTK (для Slackware это /usr, к примеру).
Дополнение от eRazor
Для GTK2-приложений в KDE используются настройки из конфигурационных файлов перечисленных в переменной GTK2_RC_FILES, например:
$GTK2_RC_FILES:
/etc/opt/gnome/gtk-2.0/gtkrc: /opt/gnome/share/themes/Qt/gtk-2.0/gtkrc: ~/.gtkrc-2.0-plastik: ~/.kde/share/config/gtkrc
Обратите внимание на то, что суффикс в имени rc-файла содержит имя темы. Когда вы в KDE, используется не /.gtkrc-2.0, а /.gtkrc-2.0-plastic, если он есть конечно.
[править]
Как переключить тему в gnome или приложениях gtk?
Скачиваем тему, распаковываем ее куда-нибудь, вроде $HOME/themes/_название_темы_
Далее в файле .gtkrc пишем include "$HOME/themes/_название_темы_/gtkrc"
Если есть файл .gtkrc.ru или gtkrc.ru проще всего сделать их ссылками на .gtkrc
Если у вас стоит KDE, то влияние на тему оказывает файл gtkrc-kde. Чтобы этого не происходило, вы можете снять галку в Центре Управления: Appearance & Themes -> Colors KDE -> Apply colors to non-KDE applications.
Если у вас стоит Gnome, проще (и лучше всего - со слов пользователя Gnome) воспользоваться gtk-theme-switch. Вы можете скачать его отдельно (версия для приложений gtk-1 и gtk-2) или попробовать найти в своем дистрибутиве.
[править]
Почему в GTK-программах, например VWware, xmms, jpilot вместо русских букв квадраты?
Это происходит потому, что в файле /etc/gtk/gtkrc.utf8 (или /etc/gtkrc.ru - в файле, соответвующим вашей локали) фигурирует ссылка на шрифт семейства helvetica, в котором отсутствуют русские символы или указан несушествующий шрифт.
Данную неприятность легко исправить, вписав вместо него любой шрифт, который реально присутствует в системе. Например, на RedHat или Fedora Core, файл может выглядеть так:
style "default-text" {
fontset = "-urw-urw bookman l-medium-r-normal-*-14-*-*-*-p-*-koi8-uni"
}
class "GtkWidget" style "default-text"
Также примеры для redhat можно посмотреть в предыдущем вопросе.
[править]
Как настроить шрифты в Motif-приложениях?
man editres
man xrdb
[править]
Как сделать, чтобы xmms можно было свернуть в трэй KDE/Gnome?
Данный плагин работает и в GNOME и в KDE. Для Fedora Core есть готовый пакет.
Или скачать и поставить соответствующий plug-in. На сайте также есть бинарники (rpm) под SuSe и RedHat.
[править]
Как сделать, чтобы xxkb "висел" в трее IceWM?
Waso отвечает :
~/.xxkbrc:
XXkb.mainwindow.enable: yes
XXkb.mainwindow.geometry: 15x15+985-31 !Цифры можно подобрать и другие
и
~/.icewm/winoptions:
XXkb.dTitleBar:0
XXkb.dBorder:0
XXkb.dResize:0
XXkb.ignoreTaskBar:1
XXkb.ignoreWinList:0
XXkb.dTitleBar:0
XXkb.dBorder:0
XXkb.dSysMenu:0
XXkb.dResize:0
XXkb.dClose:0
XXkb.allWorkspaces:1
XXkb.layer:AboveDock
[править]
Почему Mozilla грузит процессор на 100%?
Скорее всего это не Mozilla, а контент открытых страниц. Одним из радикальных, но довольно действенных методов борьбы с этим явлением является отказ от использования flash-plugin (просто не устанавливать). Как вариант, можно поставить Adblock и запретить *.swf.
[править]
Как ускорить проигрывание FLASH (заставить его использовать меньше ресурсов)?
Задать такую переменную:
export FLASH_GTK_LIBRARY=libgtk-x11-2.0.so.0
[править]
Как включить java в mozilla?
* Нужно поставить j2re или j2sdk.
* Перейти в папку вида $JAVA_HOME/jre/plugin/i386/ns610-gcc32/
* Сделать симлинк с libjavaplugin_oji.so в папку plugins браузера mozilla (например, /usr/lib/mozilla/plugins)
[править]
Почему-то mozilla тормознуто открывает странички, а остальные браузеры нормально. Как лечить?
Скорее всего это проблема с обращением к ipv6. Добавьте в /etc/modprobe.conf (для ядер 2.4 - /etc/modules.conf):
# Turn off IPv6
alias net-pf-10 off
alias ipv6 off
[править]
После того как вхожу в инет машина начинает дико тормозить. Все открывается долго. Что делать?
Убрать в своей программе дозвона получение имя хоста от провайдера. В том же kppp, например, есть галочка на эту тему. О параметрах pppd читайте man pppd
[править]
Как поменять в KPPP тоновый набор на импульсный?
Либо перед номером телефона пишем букву 'P' (латинская!), либо заходим в свойства kppp, команды и пишем вместо ATDT команду ATDP.
[править]
Что делать, если при запуске wvdial не от рута программа пишет device busy?
Дайте пользователю права на запись в директорию /var/lock (скажем, включив его в группу, владеющую данной папкой)
[править]
А можно пример конфига для wvdial?
/etc/wvdial.conf:
[Dialer Defaults]
Modem = /dev/ttyS0
Baud = 112500
Init = ATZ
Init2 = AT S11=50
Dial Command = ATDP
Phone = 9955555
Username = int1104221
Password = LyQSptAy
New PPPD = yes
#Init3 = ATM0
[Dialer phone2]
Phone = 9955556
[Dialer phone3]
Phone = 1055555
[Dialer phone4]
Phone=9519024
[Dialer phone5]
Phone=9613332
[Dialer norm]
Init3 = ATM1
[Dialer phone6]
Phone=7132245
[Dialer phone7]
Phone=7113676
[править]
Как отключить beep?
Если хочется отключить писк в консоли (для bash и программ, использующих readline), можно добавить в /.inputrc строку
`set bell-style off`
или
`xset -b`
(что эквивалентно `xset b off`), затем выйти из нее (консоли) и зайти снова -- должно получиться. Или сделать
setterm -blength 0
Для xterm, rxvt и других графических эмуляторов также можно использовать команду
`xset b off`.
Для более глубокого ознакомления со способами управления звуком (и не только) в консоли рекомендую поселить [1] и [2].
[править]
Как запустить программу в фоне, без привязки к терминалу?
user@linux# nohup COMMAND [ARG]...
Программа nohup запускает COMMAND таким образом, что она игнорирует сигнал hangup, что позволяет ей продолжать работу и после выхода из терминала. Также, она перенаправляет весь вывод программы в файл $HOME/nohup.out и понижает приоритет выполняемой программы.
[править]
Как понизить/повысить приоритет запускаемой программе?
Воспользуйтесь командой nice. Чтобы понизить приоритет, напишите нечто вроде:
user@linux$ nice -n 10 myprogram
Подробности можно узнать, набрав man nice
[править]
Как сделать терминал без рамки?
Это настройка не терминала, а WindowManager'а.
Для FluxBox, это можна сделать например так: добавить в /.fluxbox/keys строку
~/.fluxbox/keys:
"Mod4 d : ToggleDecor"
После этого нажатием на [Win+d] можно управлять наличием рамки у любого окна.
Для WindowMaker - Свойства окна (правая кнопка мыши по заголовку)->Атрибуты->Скрыть строку заголовка
[править]
Как разделить tar.gz на равные части?
man tar в районе -M
Либо man split и натравить split на tar.gz.
[править]
Как просматривать ресурсы сети Windows (сетевое окружение) из консоли? Как его смонтировать?
Для начала нужно посмотреть ресурсы при помощи команды smbclient -L winmachine. На данный момент ресурсы с названием более 16 символов поддерживаются некорректно, т.е. все символы в названии после 16-го отсекаются.
Чтобы смонтировать нужный ресурс, дайте примерно такую команду:
smbmount //winmachine/movie /home/jackill/mnt/movie -o iocharset=koi8-r,rw,codepage=cp866,umask=0
Для ресурсов с паролем дайте команду:
smbmount //winmachine/work /home/jackill/mnt/work -o iocharset=koi8-r,rw,umask=0,codepage=cp866,username=_username_,password=_password_
Также существуют [[Чем просматривать ресурсы MS Windows-сети (сетевое окружение)? Как сделать доступными машинам с MS Windows свои директории? Чем автоматически монтировать ресурсы samba? | GUI-утилиты и специальный скрипт]], искать ресурсы которыми и монтировать значительно удобнее.
[править]
Как перевести текстовый файл из одной кодировки в другую?
Смотри вопрос Какие есть программы, для конвертации содержимого текстового файла из одной кодировки в другую?
[править]
Как провести операцию по преобразованию группы графических файлов (например, уменьшить размер ста файлов)?
Есть такой пакет ImageMagick (http://www.imagemagick.org/), Входит он практически в любой дистрибутив и содержит группу утилит, предназначенных для различного преобразования файлов. Полный список поддерживаемых форматов вы можете узнать, набрав man ImageMagick.
В качестве примера возьмем задачу по уменьшению группы файлов (jpeg уменьшить пропорционально, чтобы координата x равнялась 800 пикселям).
Пишем такой скрипт, у меня он называется conv (автор неизвестен):
#!/bin/sh
for i in $@ ; do convert -geometry 800 $i small/$i ; done
Дальше делаем просто:
* В папке с картинками создаем папку small.
* В папку с картинками переписываем наш скрипт.
* Запускаем скрипт ./conv *.jpg
[править]
Как установить Maya 4.5 (В том числе под RedHat 9/ASP 9/Fedora Core 1 и прочее)?
1. Ставим maya из rpm.
2. Переходим в /usr/aw/maya/bin
3. Находим файлик Maya 4.5
4. В этом файле ищем строчки (27 строка):
case Linux:
set lib = lib
После них ставим
set lsFlags = '-l'
setenv LD_ASSUME_KERNEL 2.4.2
И весь кусок у нас выглядит так:
/usr/aw/maya/bin/Maya4.5:
case Linux:
set lib = lib
set lsFlags = '-l'
setenv LD_ASSUME_KERNEL 2.4.2
breaksw
[править]
Как установить в консоли развертку больше 60Гц при использовании framebuffer?
Нужно настроить framebuffer.
Но есть тонкость - если вы используете родные модули для карт от ATI, Matrox и NVIDIA (и в случае последней карты остаетесь без драйверов с поддержкой 3D), то проблем не будет.
Но если вы используете универсальный vesa framebuffer, ядро придется предварительно патчить, потому как 60Гц на мониторе при высоком разрешении никому не нужно. Есть небольшая тонкость - кажется, что карты GForce FX 5600 и 5900 игнорируют команды переключения частоты.
Есть патч, почитать о котором можно в этом обсуждении. Подходит только для карт, поддерживающих VBE 3.0 (например, GeForce), для VBE 2.0 (например, Radeon 8500) придется делать дополнительные телодвижения.
[править]
Как изменить разрешение в консоли? Как настроить framebuffer?
Нужно настроить framebuffer, а если он уже настроен и драйвер не стандартная vesafb, а специфичный драйвер карты, то можете для изменения частоты использовать утилиту fbset (иначе частоту придется менять при загрузке).
Почитать о том, как все настроить, можно на http://kmxb.narod.ru/rivafb1.html и по материалу этой статьи написана еще одна: http://linuxshop.ru/linuxbegin/article675.html.
Есть две тонкости:
1. Стандартный драйвер vesafb выдает только 60Гц, но это можно обойти (см. предыдущий вопрос).
2. Русский шрифт будет только в первой консоли. Для руссификации остальных придется сделать скрипт (или взять готовый из документа по русификации Slackware.
[править]
Как увеличить разрешение и частоту развертки консоли не используя framebuffer?
Для этого нужна специальная утилита SVGATextMode. Лежит она здесь: ftp://sunsite.unc.edu/pub/Linux/utils/console/
Чтобы она нормально собралась на современных системах, нужно в файл cfgfile.y добавить после строки #include <stdlib.h> строчку #include <stdio.h>
Также рекомендуется посмотреть на патчи под определенные карточки.
За ответ благодарим lumag.
[править]
Как ускорить работу KDE?
Помимо пересборки ядра под свою систему, X-сервера, выключения ненужных системных служб и сервисов самого KDE можно прочитать вот эту статью.
Это не я бляяя...
Offline
#3 11.09.06 10:46
Re: опитимизация кде
Укроп написал(а):
Графика в консоли Linux.
j1m mailto: j1m@list.ru
Сейчас многие предпочитают работать с X Window. И правда, зачем напрягаться, выучивать сотни команд, когда можно легко все сделать в KDE или Gnome с помощью различных конфигураторов. Возможно, это результат продолжительного ядовитого воздействия Windows, возможно стремление к ко всему красивому, ровному плавному, ко всему, что дает X Window, возможно многим необходимо каждый день работать с OpenOffice, возможно, да много чего возможно :). А ведь консоль, при правильной настройке выглядит очень даже привлекательно, и с ее помощью можно решить большинство задач, которые обычно принято решать с помощью X.
Эта статья не для тех, кто не может без Mozilla и Sylpheed, и не для тех, чей runlevel - 5 :), она для тех кто по каким-либо причинам или не хочет или не может использовать X Window. Она для тех кто хочет использовать все или почти все возможности графических программ в консоли без взаимодействия с X Window.
Наверно многие мне возразят, мол зачем парится, ставить какое-то дополнительное программное обеспечение, когда можно запустить X Window, сделать, что хотел, затем ctrl+alt+backspace и ты опять радуешься черному экрану и мигающему курсору, или поступить еще проще, держа иксы загруженными и переключаться в них по мере надобности. Это конечно все верно, но
во-первых: на моем pentium-233 32RAM иксы жутко тормозят, о KDE или Gnome не может быть и речи, все-же некоторое время я работал в иксах, используя fluxbox в качестве WM, но все время давал о себе знать недостаток памяти,
во-вторых: все время запускать или держать в памяти иксы очень накладно, хотя, если у тебя гиг оперативки, то это к тебе не относится (также как и первый пункт),
в-третьих: зачем мне ставить иксы, если мне из графических приложений нужны только jpeg-вьюер, видео-плейер и, иногда, графический браузер (я обычно пользуюсь elinks), а работать мне удобнее в консоли,
в-четвертых: ну не нравятся мне иксы :).
Так что все, кто не согласен с первыми тремя пунктами делают startx, остальные за мной, в дебри инета, на поиски программ и библиотек. Итак, что нам нужно?
SDL (идет во со всеми дистрибутивами)
directFB
GGI (под нее я ничего хорошего не видел)
SVGAlib (я ее не использую)
Перед тем как выкачивать и компилить все эти пакеты необходимо включить в ядро поддержку framebuffer'а. Возможно ваше ядро уже поддерживает fb (здесь и дальше будем обозначать так framebuffer), Стандартные ядра, идущие с дистрибутивами обычно скомпилированы с поддержкой vesa-fb, если ваша карточка не поддерживает vesa 2.0 или вы хотите использовать bootsplash (см. ниже) тогда идем на ftp.kernel.org и качаем последнее стабильное ядро (на момент написания статьи его номер был 2.6.4), также советую скачать патч, после наложения которого появится возможность повесить wallpaper в консоли(!). Патч можно найти по адресу: ftp://ftp.suse.com/pub/people/stepan/bo … 2.6.3.diff (патч для 2.6.3 ядра, но нормально ложится и на 2.6.4) также необходимы утилиты: ftp://ftp.suse.com/pub/people/stepan/bo … .7.tar.bz2 (Вообще-то bootsplash изначально задумывался для того чтобы показывать анимированную загрузку линукс, но я не вижу в этом необходимости и покажу как использовать его для другой цели).
По умолчанию bootsplash работает через vesafb, но это легко исправить, необходимо изменить несколько строк в самом bootsplash-3.1.4-2.6.3.diff:
!!!ВНИМАНИЕ!!! Все это было протестировано только на sstfb (voodoo1/2), так что ни за какие ваши действия ответственности я не несу. Также хочу заметить то, что если ваша видеокарта поддерживает vesa 2.0, то лучше ничего не менять и сразу перейти к наложению патча. !!!ВНИМАНИЕ!!!
строка 107:
+extern struct fb_ops vesafb_ops;
меняем на:
+extern struct fb_ops sstfb_ops;
^^^^^^^^^
(это для voodoo1/2, также может быть radeonfb_ops, cirrusfb_ops, etc)
строка 598:
+ if (!vc_cons[unit].d || info->fbops != &vesafb_ops) {
меняем на:
+ if (!vc_cons[unit].d || info->fbops != &sstfb_ops) {
^^^^^^^^^
(опять-же для voodoo)
строка 2065:
+ depends on FRAMEBUFFER_CONSOLE && FB_VESA
меняем на:
+ depends on FRAMEBUFFER_CONSOLE && FB_VOODOO1
^^^^^^^^^^
или
+ depends on FRAMEBUFFER_CONSOLE
Дальше лезем в /usr/src/linux/drivers/video/sstfb.c (radeonfb.c, cirrusfb.c, etc),
находим строку:
static struct fb_ops sstfb_ops = {
меняем на целых четыре:
#ifndef CONFIG_BOOTSPLASH
static
#endif
struct fb_ops sstfb_ops = {
Также хочу заметить, что необходимо поменять дефолтовые установки для разрешения, глубины цвета, частоты. (для sstfb по умолчанию выставлено 640x480-60), конечно можно поменять эти установки и после загрузки, с помощью fbset, но тогда будут большие проблемы с bootsplash. Далее приводятся действия по изменению этих параметров для voovoo1/2, для других видеокарт это делается по аналогии. (если ваша видеокарта поддерживает modedb, то видеорежим можно выставить во время загрузки, как это сделать и какие видеокарты поддерживаются можно посмотреть в /usr/src/linux/Documentation/fb/modedb.txt).
Открываем все тот-же /usr/src/linux/drivers/video/sstfb.c
строка 83:
#define DEFAULT_MODE 3
меняем на:
#define DEFAULT_MODE 4
строка 148:
#elif ( DEFAULT_MODE == 3 )
{ /* 640x480@60 , 16bpp glide default ?*/
640, 480, 640, 480, 0, 0, 16, 0,
{11, 5, 0}, {5, 6, 0}, {0, 5, 0}, {0, 0, 0},
0, 0, -1, -1, 0,
39721 , 38, 26 , 25 ,18 , 96 ,2,
0, FB_VMODE_NONINTERLACED };
дописываем после этих строк:
#elif ( DEFAULT_MODE == 4 )
{ /* 800x600@82 */
800, 600, 800, 600, 0, 0, 16, 0,
{11, 5, 0}, {5, 6, 0}, {0, 5, 0}, {0, 0, 0},
0, 0, -1, -1, 0,
17460, 160, 64, 30, 4, 64, 6,
0, FB_VMODE_NONINTERLACED };
Это для режима 800x600-82@16, тайминги берутся из /etc/fb.modes.
Хочу заметить, что эти значения заносятся в структуру
имя-драйвера_default, например:
static struct fb_var_screeninfo sstfb_default = {
...
... };
Все, теперь можно наложить патч:
cp bootsplash-3.1.4-2.6.3.diff /usr/src/linux
cd /usr/src/linux
patch -p1 --dry-run < bootsplash-3.1.4-2.6.3.diff
если ошибок нет, тогда:
patch -p1 < bootsplash-3.1.4-2.6.3.diff
make menuconfig (xconfig не предлагаю, читай выше)
Необходимо встроить все эти параметры в ядро (т.е. не модулем):
Device Drivers -> Block Devices -> Loopback device support
Device Drivers -> Block Devices -> RAM disk support
Device Drivers -> Block Devices -> Initial RAM disk (initrd) support
Device Drivers -> Graphics support -> Support for frame buffer devices
Device Drivers -> Graphics support -> VESA VGA graphics support (или выбираем свою видюху)
Device Drivers -> Graphics support -> Console display driver support -> VGA text console
Device Drivers -> Graphics support -> Console display driver support -> Framebuffer Console support
Device Drivers -> Graphics support -> Bootsplash configuration -> Bootup splash screen
Хочу заметить, что для того, чтобы включить последний пункт, необходимо включить VESA VGA graphics support или специфичный для вашей видеокарты драйвер (в том случае, если патч был подогнан под вашу видеокарту).
После того как конфигурация ядра будет закончена:
make bzImage && make modules && make_modules_install
После успешной компиляции:
cp arch/i386/boot/bzImage /boot/vmlinuz-2.6.4-splash
Теперь. когда у нас есть ядро с поддержкой bootsplash, необходимо установить утилиту splash
tar xvjf splashutils.tar.bz2
(вообще-то гораздо удобнее работать с архивами при помощи mc)
cd bootsplash-3.0.7/Utilities
make splash
Далее можно скопировать получившийся на выходе splash в /sbin
cp splash /sbin
Итак, теперь необходимо настроить bootsplash. Создаем файл /etc/bootsplash/splash.cfg и пишем в него следующее:
# версия :)
version=3
# показывать ли wallpaper
state=1
# цвет букв
fgcolor=3
# цвет, который будет прозрачным
bgcolor=0
# отступ от каждого края по оси X и Y в пикселях,
# изменение этих параметров вызвало у меня
# проблемы с загрузкой и запуском графических
# приложений
tx=0
ty=0
# ширина и высота экрана с учетом отступов
tw=800
th=600
# путь до изображения в формате jpeg
jpeg=/путь/до/изображения
Замечу, что изображение должно быть точно такого-же разрешения, что и экран.
Далее пишем скрипт splash.sh:
#!/bin/sh
if [ "$1" = "now" ]; then
for i in 0 1 2 3 4 5 6; do
splash -s -u $i /etc/bootsplash/splash.cfg
done
else
splash -s -f /etc/bootsplash/splash.cfg > /boot/initrd.splash
fi
Запуск этого скрипта с параметром now приведет к смене фонового изображения на первых 6 консолях, запуск без параметров приведет к записи изображения в /boot/initrd.splash, чтобы фоновый рисунок устанавливался во время загрузки.
Теперь необходимо переконфигурировать lilo, открываем /etc/lilo.conf и пишем туда примерно следующее:
boot = /dev/hda
lba32
prompt
timeout = 150
append = "video=ваш-видеодрайвер"
# Оставляем путь для отката на старое
# ядро в случае, если что-то пойдет не так
image = /boot/vmlinuz-2.6.4
root = /dev/hda2
label = Linux
read-only
image = /boot/vmlinuz-2.6.4-splash
root = /dev/hda2
label = Linux-new
read-only
initrd = /boot/initrd.splash
Если, при конфигурировании ядра вы выбрали VESA VGA graphics support вместо специфического видеодрайвера, то строка append = "video=ваш-видеодрайвер" не нужна, а вместо нее необходимо прописать что-то типа vga = 316 (подробнее см. /usr/src/linux/Documentation/fb/vesafb.txt)
Все, теперь необходимо выполнить команду lilo, перезагрузиться, и любоваться красивой консолью ;)
Итак, можно перейти к установке библиотек.
SDL (www.libsdl.org)
SDL расшифровывается как Simple DirectMedia Layer. Под эту библиотеку в основном пишутся игры и различные эмуляторы приставок (для этого она и была создана), также mplayer довольно шустро работает через нее. SDL может осуществлять видеовывод как через иксовый видеодрайвер, так и через fb, directfb, ggi, что позволяет использовать ее как в иксах, так и в консоли. Также поддерживается аппаратное 3d-ускорение посредством OpenGL. SDL входит в любой дистрибутив, но лучше скачать и скомпилировать самому, т.к. версия SDL, идущая с дистрибутивами обычно требует для работы установленных в системе некоторых библиотек X11 а также звуковых серверов от KDE (arts) и Gnome (esd), а собрать библиотеку можно без поддержки X11, arts и esd, оставив только frambuffer для видеовывода и oss/arts для аудиовывода. Я не буду здесь расписывать все шаги установки, т.к. все стандартно:
./configure --help
./configure
make
make install
Замечу лишь, что не стоит использовать в качестве видеовывода directfb (хотя мы его еще не установили :)) Когда я впервые запустил программу в консоли, написанную под SDL, я долго не мог заставить работать мышь, поэтому хочу избавить вас от мучений, и сказать, что все очень просто, необходимо запускать gpm с флагом "-R raw" (без кавычек естественно :)). Второе, что меня озадачило, как эту библиотеку настраивать, ни конфигурационных файлов, НИЧЕГО нет, оказалось, что настраивается она посредством глобальных переменных, самые важные из которых:
SDL_VIDEODRIVER=videodriver
(указывает, какой видеодрайвер следует использовать
может быть: fbcon, directfb, ggi, x11 и т.д.)
SDL_AUDIODRIVER=audiodriver
(тоже, для аудиодрайвера, dma - это oss, с использованием
dma-режима, может быть: dsp, dma, alsa, esd, arts и т.д.)
у меня в /etc/profile прописано:
export SDL_VIDEODRIVER=fbcon
export SDL_AUDIODRIVER=dma
Что я использую с SDL:
mplayer (www.mplayerhq.hu) Как я уже говорил очень шустро работает через SDL, вообще-то самый быстрый видеовывод осуществляется через vesa, но необходимо чтобы карточка поддержи- вала vesa2. Я на своем pentium-233 смотрю все новые фильмы в mpeg и divX.
zsnes (zsnes.sourceforge.net) Очень хороший эмулятор Super Nintendo
jjffe (www.jaj22.demon.co.uk) reverse engineered версия elite3: first encounters
directFB (www.directfb.org)
Относительно новая библиотека. Создает надстройку над стандартным fb (в этом я не уверен, т.к. directfb может использовать SDL), добавляет множество новых возможностей, поддерживает современные 3d-ускорители, имеет интерфейс с opengl (необходимо устанавливать дополнительные пакеты), использует свои драйвера для клавиатуры и мыши, даже присутствует аудиодрайвер (поставляется отдельно), имеет более удобный программный интерфейс (в общем это тоже самое, что использовать printf вместо write :)), ко всему этому добавлю, что мне редко удавалось заставить нормально работать программы, написанные, с использованием fb, но все теже программы, скомпилированные под directfb нормально работали.
Компиляция также стандартна, для видеовывода лучше использовать fbdev. Настройка осуществляется посредством конфигурационного файла /etc/directfbrc (есть возможность указать другое местоположение файла). Вот мой /etc/directfbrc:
# видеодрайвер
system=fbdev
# видеорежим, в котором по умолчанию будут запускаться
# приложения
mode=800x600
# глубина цвета
depth=16
# не показывать баннер перед запуском приложений
no-banner
# режим отладки
#debug
# включить аппаратное ускорение
#hardware
# возможность переключения между консолями, во
# время работы приложения
#vt-switching
# протокол работы с мышью:
# MS - Micro$oft
# MS3 - Micro$oft для трехкнопочной мыши
# MouseSystems - MouseSystems ;)
mouse-protocol=MS3
Больше об опциях конфигурирования можно узнать, набрав man directfbrc.
У меня и с этой библиотекой были проблемы с мышью, не работала мышь для COM-порта, которая висела на /dev/tts/1 (/dev/ttyS1), проблема решилась так: ln -s /dev/tts/1 /dev/mouse
Что я использую с directfb:
dfbsee (можно взять с www.directfb.org) Ма-а-аленький вьюер графических файлов, умеет устраивать слайд-шоу, масштабировать изображения и все :), также умеет проигрывать видео, но эту возможность я не пробовал.
links (http://atrey.karlin.mff.cuni.cz/~clock/twibright/links) Этот, изначально текстовый браузер умеет работать в графическом режиме, а также поддерживает ssl и javascript.
Также хотел включить в статью описание gtk-directfb (с ее помощью можно запускать приложения написанные под gtk+ в консоли!), но так и не смог заставить ее работать, если кому удастся привести ее в рабочее состояние напишите мне, на j1m@list.ru, саму библиотеку можно скачать с www.directfb.org
GGI (www.ggi-project.org)
GGI - General Graphics Interface Про эту библиотеку я не много знаю, она, также как и directfb имеет собственные драйвера для клавиатуры и мыши, которые, кстати, идут в отдельном пакете - GII - General Input Interface и перед сборкой GGI сначала следует собрать GII. Также эта библиотека может использовать в качестве видеовывода fb и directfb, а сама она может использоваться SDL для видеовывода. Вот и все что я могу сказать про эту библиотеку. Ничего хорошего я под нее не видел (да и плохого мало :)).
Что я использую с GGI:
Ничего! Не видел ничего кроме quake, hexen и ggv, этот ggv представлял из себя очень урезанный вариант графического вьюера zgv (работает через SVGALib).
Может я ошибаюсь (очень хочется надеяться), но по-моему под эту библиотеку уже ничего не пишется (если кто хочет переубедить меня - мыло вверху).
SVGALib
По-моему одна из первых графических библиотек, поэтому под нее успел накопится софт. Про нее я ни чего не скажу, включил ее в обзор, чтобы читатель знал о ее существовании :)
THE END
Вот и все, что я хотел сказать, не много, но я не хотел описывать все тонкости работы графической подсистемы в линукс, я всего лишь хотел рассказать о том, какие есть пути для преодоления графического барьера в консоли, ведь когда я впервые отказался от иксов (удалил их с винта) у меня не было не одного работающего в консоли графического приложения, я даже не знал, что SDL может работать с fb :)
Критика приветствуется, все замечания, вопросы, etc направляйте по адресу j1m@list.ru
Это не я бляяя...
Offline

