Tag Archives: unix

Графические среды в Unix

Сначала я это писал в форуме нашей сети, но потом понял, что получилось больше, чем просто сообщение для форума.

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

Проблема тут как раз в намерении показать “альтернативу” (1). Разработчики KDE дошли до той кондиции, что с каждой версией пытаются показать альтернативу сами себе, тщательно переделывая всё, что можно. Разработчики ASPLinux пытаются выпендриться в свою очередь перед ними, переделывая KDE под свой фирменный стиль, неизбежно добавляя туда новые баги. Это не имеет никакого отношения к заботе о пользователе, но требует вложения сил.

Я как-то уже излагал свои мысли на этот счёт, правда по-английски. Вкратце: нужна графическая среда для пользователя, но выполнена она должна быть в духе Unix. Ссылку на книгу Эрика Рэймонда, внятно изглагающего что есть дух Unix, я уже приводил. Среда должна быть максимально отделена от системы технически, для пользователя это выражаться должно в том, что при желании он всегда может посмотреть сквозь неё и увидеть те процессы, что происходят в ней. Среда должна быть максимально модульной, то есть состоять из небольших компонентов, а не монолитный монстр вроде KDE. В общем, принцип “K. I. S. S.” (keep it simple, stupid) должен работать на всю катушку.

Кроме того, минимум переделок непонятно ради чего, как в KDE. Стабильность и привычность прежде всего. Привычность означает похожесть на то, к чему пользователь привык. Как минимум это винда, хотя наличие разных режимов приветствуется. Всякие же попытки сделать “не как у них”, ничем не подкреплённые – это преступление против юзабилити, а значит неуважение и высокомерие по отношению к пользователю. Пример: GNOME Human Interface Guidelines – о чём они думали, переделывая привычное “Yes”, “No”, “Cancel” в “No”, “Cancel”, “Yes”?!

Пока разработчики графических сред будут городить огород из непонятно чего, вкладывая невероятное количество сил в разработку какой-то ерунды, о которой пользователь даже и не узнает, забывая свою цель помочь пользователю освоиться с незнакомой системой, пользователи будут шарахаться от незнакомых графических сред куда подальше, проклиная их за кривость, глюкавость и тормознутость, утверждая, что винда – самая надёжная, быстрая и удобная операционная система. Они, разумеется, не правы насчёт операционной системы, но поверхностное сравнение (а другое пользователь проделать и не в состоянии) оконных сред показывает именно такой результат.

Пример бестолковых действий разработчиков: KOffice. Пользователь, сев за новую ОС, чуть ли не сразу пойдёт искать Word. Найдёт KWord и попробует открыть в нём свой “Служебная записка.doc”. Полюбовавшись на результат, наверняка почувствует желание забыть о Unix навсегда. Что должны были сделать разработчики KDE: убрать свой дурацкий офис как только появился OpenOffice.org и вместо этого обеспечить нормальную интеграцию с ним от рождения. Тогда это бы оставило гораздо более приятное впечатление.

Другой пример: ранее упоминаемый DVD-плеер из 100 строк (2), который почти наверняка – дрянь редкостная. Если бы они вместо этого интегрировались с MPlayer, например, а дистрибутив Linux от рождения включал бы в себя его и кодеки к нему, пользователь бы имел возможность насладиться возможностью воспроизведения почти всех вообразимых форматов видео, что наверняка произведёт на него неизгладимое впечатление после первого опыта общения с Media Player с его набором кодеков по умолчанию, что не в состоянии даже DivX открыть, кажется.

Конечно, альтернативные решения имеют право на существования. Это тоже часть истинного пути Unix. Но они должны чем-то превосходить своих собратьев. KOffice ничем не лучше OpenOffice.org. Будь он хотя бы побыстрее и попроще в употреблении – но нет, это такой же навороченный тормоз, как и вся KDE.

Но почему-то никто об этом не думает, и пытается тщательно изобретать велосипеды, да ещё оригинальничать при этом. Вот и остаётся: либо следовать истинному пути Unix, либо сидеть в винде и не высовываться. Ну или высовываться раз в несколько лет, чтобы разведать обстановку.

Единственный способ применения всех этих велосипедов, это в качестве временного средства транспорта, чтобы доехать до приличных средств передвижения, а затем бросить их. Я сам начинал с KDE. Но будь я нормальным пользователем, я бы забил на Unix ещё в самом начале, в силу кривости и глюкавости – ведь это только потом я узнал, что кривы и глюкавы – дистрибутивы и среды, а не система или софт.

О, разработчики графических сред! Мало модульности, мало прозрачности, мало интеграции! Читайте Рэймонда, учите албанский!


(1) Цитата из форума: “Да дело не в “умных” или “неумных” системах, а в намериниях разработчиков показать альтернативу средне статистическому юзеру привыкшему к Винде”.
(2) Цитата из форума: “Enlightemnet (enlightenment.org) же – делала контора целиком, начиная с библиотек обработки графики (imlib) и заканчивая аж двд-проигрывателем на всего лишь 100 строках кода используя библиотеки той же разработки”.

GNOME Human Interface Guidelines

Misunderstand me not. I really love GNU. I really admire Richard Stallman and his followers. In a way, I am one of them as well. But I sometimes just can not understand what these guys are thinking about.

For example, I read in GNU coding standards “Please don’t use “win” as an abbreviation for Microsoft Windows”. Is it really that important that Windows should be written in full or abbreviated to one letter, but not to three? What about four? Will they say that I am being rude to Mother Nature abbreviating “Windows” to “Wind”? Or what if I really like the funny way “Windo” (accent on last “o”, please) sounds? Weird guys. But that is okay, that is just their religious preoccupations. It is harmless anyway.

Now here is another thing. GNOME Human Interface Guidelines say that in “confirmation alerts” (for example, when application asks whether it should save document before closing) buttons should be ordered like “Close without Saving”, “Cancel”, “Save”. Okay, calling them like this instead of usual “Yes”, “No”, “Cancel” seems like a good idea because it decreases the chance user will mistake one confirmation with another (for example, they may think that they are being asked whether application should really close). So that is perfectly fine.

But what the hell is about this weird ordering?! I had a discomforting feeling all the time that something is wrong here, and when I stopped and thought “Why do I dislike these GTK+ confirmation dialogs so much?”, I finally realised: it is not “Yes, No, Cancel”, it is “No, Cancel, Yes”! So, no single button is on its rightful place. I am not saying that “Yes, No, Cancel” should be like that simply because it is like that in Windows. But it is something most people used to. It is something natural, after all! I have seen many “Y/N” questions even in DOS, but I have never seen “N/Y” question. People say “Please answer with yes or no”, but they never say “no or yes”. The root of that discomforting feeling was that each time I knew I should save, I was tempted to press first button which is “Close without Saving”, but then I saw that it is not usual “Yes” and was stuck.

I thought that some developers do not really think about ordering when making such dialogs and so they mess it up. But now I see this thing in something like standard guidelines I just can not understand why they are making more enter barriers then there are already. After all, all the point of GNOME and similar environments is to give the right feeling to people who are used to GUI environments, not to give them something even more weirder than CLI which is just a different thing, but at least without any unnatural attachments.

I am really happy that I use very few of these GUI things, otherwise I would probably be constantly mad about stupid design and inconvenient interfaces. But I just can not rid of the feeling that all these GNOME things is just another “let us make something really different, no matter how and what”.

IDEs in Unix

It is often said that there is almost no good IDEs in Unix. I finally realised that this is wrong. There is one very good IDE called Emacs. It does not look like IDE simply because it uses very powerful mechanism of commands and keyboard shortcuts instead of fancy menus, buttons and stupid dialogs usually found in other IDEs. But other than that, Emacs is full-featured IDE which supports a lot of languages and at least compiling, debugging, navigation and completion. Compared to Borland IDEs, Emacs is a way better. Compared with things like Eclipse and IntelliJ IDEA it lacks only GUI builder and refactoring tools. Former is not a problem because there is a lot of very good GUI builders that can be used independently of editor (like Qt Designer), the latter is a little bit disappointing, though. Maybe I did not search well enough or maybe refactoring is not really needed with true Unix development style (this makes sense, since I did not miss refactoring even once).

Nonetheless, Emacs is really an IDE. If it seems strange to you, imagine that your favorite IDE has all its menus, toolbars and panels removed, their functions bound to key sequences (less often used ones to text commands), and you will quickly understand why Emacs looks like an editor.

So, to continue “Emacs and Vim” discussion, it becomes very simple: Vim is the best editor, Emacs is the best IDE.

Unix philosophy: reuse! Popt example

One of the concepts of the Unix philosophy is code reusing. Never write anything that is already written. Never invent the wheel. If you are not happy with any of the existing wheels, try to modify one of those instead of writing your own.

So I was writing class QuaArg for parsing command-line arguments, knowing that there are already such things as getopt and getopt_long. I was doing that because I needed more portable thing – I needed it to work on Windows too, for example. And I am not even sure whether getopt_long will work on HP-UX, for example.

But then I realized that I was still doing something wrong. The very idea of reimplementing such common thing as command-line arguments parsing by myself started to seem more and more ridiculous to me. So I stopped and thought a bit. Okay, so I am in need of portable command-line argument parsing library. Is it hard to implement? Not. Plain standard C is more than enough. So, am I the only one who needs it? Probably not. Therefore, there must be something like portable getopt_long implementation! There is no way it would not exist!

So I started to look for it and quickly found GnuWin32 project. There I looked for getopt_long, did not found it, but found popt instead. It is a library for command-line option parsing in C. A few external dependencies, but they are all portable C libraries too. Everything is available for Windows in that project. And it is of course available on any Unix, too. Easy to use, has all the features I need. I tried to use it, and it worked fine. I tried to compile then on Windows – worked fine, I only had to put DLLs in PATH, and properly set up paths to header files and libraries.

Now I already implemented half of my application that needed to use command-line arguments. If not for Unix philosophy, I would probably still be coding that QuaArg class, finding and fixing a lot of bugs and watching my code grow far beyond two simple functions.

Emacs and Vim

One of the most religious things in the Unix operating systems is probably a choice between Emacs and Vim – the two most powerful text editors in the world. I am not going to go into another kind of “Emacs vs Vim” philosophy, but instead I have something to say about Emacs and Vim together.

I am using Vim for a long time already, and I am not feeling like tossing it away. It is very good, if not even better. In fact, I have never seen an editor which allows to type so fast, and I probably never will. Well, at least while keyboard remains fastest input device. In addition to typing speed, Vim has very good basic editing primitives, syntax highlighting, ability to compile programs from within editor, folding, and tags support. Using folding you easily can edit large texts with structure such as programs and LaTeX sources. Very nice indeed. Syntax highlighting is not even worth mentioning because every good editor just must support it, but what is worth mentioning is that Vim supports about 400 different languages and dialects. Compiling programs from editor would be useless, but if compilation fails, Vim moves you to the first error – very useful. Tags support provides you a quick hypertext-like navigation mechanism – just press Ctrl+] on function name, help topic or alike – and you are there.

Having said it all, Vim still has some major flaws. Most important of them is a lack of the flexible interactive process integration mechanism. It does not work with debuggers, version control systems, spell checking software and everything else that requires non-batch interaction with external processes. It supports a spell checking, actually, but it is not very good, because it is based on periodical calls to the spell checker, not interactive communication. As for everything else mentioned, I have seen nothing good for this tasks in Vim.

And here is where Emacs comes in. While Vim is just powerful text editor and nothing more, Emacs is more like a generic template for some kind of IDE. It has very good version control system and debugger integration bundled right in. As for spell checking, it has much better engine, but I could not make it spell check UTF-8. Still, it does not change the fact that Emacs has very powerful interactive process integration mechanism, which Vim lacks. As for version control and debugging – it just rocks. Setting breakpoints from editor, tracing execution within it, syntax highlighting for interactive debugger output, basic version control commands bound to convenient keys, ability to view arbitrary file revisions from editor, and such.

Still, Emacs is much slower than Vim. All these “C-a C-u 3 C-k ESC S-<" instead of Vim's "3ddgg" can drive Vim's user crazy. Well, I am pretty sure that once I get used to it and find what operations I need the most and bind them to convenient keys, Emacs will become much more friendly to me, but I seriously doubt that it will give me typing speed comparable to Vim. Therefore I conclude that it is no wonder people keep arguing about these two editors, forgetting everything else. They are really good, each in its own way, and I see no other choice except using them both. What is left to decide is when use which. As far as I can see now, Vim is better when you need more typing and less other operations, and Emacs is better when you find yourself simultaneously fixing, debugging, committing, updating and such. Therefore, for mail - Vim is definitely better, for editing configuration files - too (I even use Vim to edit Emacs configuration file, and find it very useful), for initial stages of development, when you think about designing and coding more than about committing and debugging - Vim again. For debugging and quick fixing purposes, Emacs only. And what is really sucks about it, is that even basic operations are done in Emacs and Vim with completely different key bindings. For example, basic cursor movement in Vim is "h j k l" while in Emacs it "C-b C-n C-p C-f". I admit that latter is easier to remember (back-next-previous-forward), but if you look at your keyboard, you will have to agree that Vim's keys is much easier to use. Not to mention that in Vim you do not have to press Ctrl. I have to admit, though, that I only began learning Emacs. My Vim's knowledge is much better, although I am no expert in neither. One thing that is clear for me is that I have to use both to achieve maximum productivity.

FVWM WindowList usability problem solution

One funny thing just happened. FVWM has function called WindowList which acts similar to Windows’ Alt+Tab. But unlike Alt+Tab, which displays some special fancy thing, WindowList displays simple menu, just like many others. It is good. What is bad is that when I use Alt+Tab to switch between menu items, FVWM also moves mouse pointer over them, just like it does for other menus. But for some reason, it does not return mouse pointer back to where it was before I pressed Alt+Tab. For other menus there is no such problem, so it may be just a bug. Anyway, it is bad because I often keep my mouse pointer at the edge of the screen, where it does not bother me. And then I press Alt+Tab and get it in the center of the screen! So I have to move it away each time, which is really frustrating.

But of course FVWM is open source. Any bug can be fixed by any developer in the world. So I tried to look at the sources a little, but understood that it will take me a lot of time and effort to understand what is going on there. Well, low-level X programming was never one of my strong points. I also tried to read the documentation, but found no option like “DontTouchMyMouse”.

Then I thought: well, maybe there is a way to save mouse position before displaying WindowList and restore it back when WindowList closes. I looked at the documentation more, but found out that although there are variables $[pointer.x] and $[pointer.y] containing just what I need, but there is no way to save and restore them. Strangely enough, FVWM configuration file allows a lot of programming, but no data manipulation except read-only access to predefined variables.

Then I looked at the FVWM modules and became interested in the FvwmPerl module. After reading documentation a little, I came up with the following solution:

It certainly does not look too complicated, does it? Although I think that using Perl is a little bit of an overkill, but hey, it works and works almost fine. By “almost” I mean that it would be very nice not to move mouse back if I used mouse to select window to switch to, not keyboard. Still have no idea how to do that, though. But it is still better to have choice between “move back” and “do not move back” instead of just “do not move”.

One of the major UNIX flaws: lack of the user-friendly GUI

I already told several times why UNIX is so good.

But now, when I stumbled upon www.joelonsoftware.com (an invaluable resource indeed!) and read about “Biculturalism“, I finally realized one thing is terribly wrong about UNIX. That is exactly what Joel writes about:

“Aunt Marge can’t really use Unix, and repeated efforts to make a pretty front end for Unix that Aunt Marge can use have failed, entirely because these efforts were done by programmers who were steeped in the Unix culture.”

That is it! It is not that UNIX lacks good software (not talking about OCR here), it is not that UNIX installation procedure is too complicated for an inexperienced user (the same could be said about Windows as well). The main problem is different and that is exactly what Joel had written. Unix is just user unfriendly. It is very obvious thing, actually, but I realized it completely only now, because for me it is not unfriendly – it is exactly opposite, actually.

What do I mean here. No, it is not only that KDE really sucks. I new that for a long time. It is something much more deep. UNIX lacks “average user layer”. I mean, on Windows we have a nice desktop, “My Computer”, “My Documents” and such. I know that disks “C” and “D” is not a part of any logical unit in the file system that could be called “My Computer”. I know that “My Documents” is just another directory on the hard drive, so there is no reason to give it a special icon or to make it a default directory for a lot of operations. But Windows pretends that it is all different. It pretends that we really have something in our PC that could be called a “desktop”, “My Computer” and such. The bad thing about it is that it makes things more complicated than they should be – I mean, why the hell we should give some directory (which even has space in its name!) some special status just because Microsoft thinks so? The good thing is, ironically, the same – for average user it is easier to work with “My Documents”, “My Computer” and “desktop”. No, not because he is too stupid to know what directory and file is. No, those who are really stupid have a lot of troubles with Windows too, so we better leave them alone, hoping that they will do the same thing to us, heh. What I am talking about here is not just a matter of knowledge. The key point (the point I came to understand only now) is that people feel more comfortable with familiar concepts. That is, while I do not really care whether it is named “docs” or “My Documents” and therefore choose former because it is shorter, lowercase and have not spaces, at the same time Aunt Marge will just get scared of “docs” because it looks too weird and too similar to all those “lib”, “etc”, “bin” and stuff. As you can see, it is not only problem of the good desktop environment – the nature lies deep within system, even in such simple things as directory names.

So what do we need in UNIX for it to be able to beat Windows completely? First thing, we need an ideal Windows emulation. Yes, just like something Wine gives us, but much better. Well, the good news about it that Windows API seems to be completely abandoned so we can hope that Wine catches up to it someday. Now we have another evil weapon called .Net, but it already has UNIX implementations like “Mono“. Second thing, we need a lot of good software, better open source, but good commercial software will probably do as well. And third thing, we absolutely, undoubtedly need something called “average user interface” layer. No, this is not a reason to rename all those sacred directories as Apple developers did. UNIX is UNIX. “bin” should stay “bin”, and there is no reason to move away FreeBSD’s /etc/rc.conf file just because it scares Aunt Marge. After all, we have a lot of much more awful stuff in Windows – just look into system32 directory! But no users really see this stuff, so that is okay. And that exactly what we need on UNIX. We need file manager that not only resembles their favorite Explorer – it behaves like it, and it hides anything that users are not used to see. We need desktop environment, that is not so complicated and buggy as KDE and that enables people to do that they are used to do – like dragging their files from disk “A:” (well, it does not have to be called “A:” but it should have very similar icon to that in Windows and should be called in their native language (like “Floppy Disk”), not “fd0”) to their desktop. We need something similar to dreadful Autorun feature because very many people are used to inserting disk in the CD drive and waiting for Something Good to happen. And we need a lot of another stuff – and the main point that it all should work, should not be more buggy than Windows, and should make people feel comfortable! And to achieve it all, it should be done by people who feel what is “user friendly” like, not just by good UNIX software developers.

In ideal world, this should look almost identical to Windows, but be free, run faster, require a lot less RAM and disk space, should crash less often than Windows (easiest part, even when comparing to modern stable versions of Windows) and at the same time it should be UNIX – I mean, that pressing some magical key sequence like “Ctrl+Alt+Scroll Lock” or choosing “Switch to classic UNIX” in “Log out” menu should bring us back our favourite OS without any weird attachments like “/My Documents” directory. You say it is impossible? Well, I am not so sure about it, but even if it is, then it just means that Windows will remain most popular OS for a while. Bear with it or fight with it. Not by screaming “Microsoft sucks and is not fair!”, but by giving people what they are expecting, not what you are thinking they should expect. This is a reality, not your dreams.