- Kdialog linux что это
- Shell Scripting with KDE Dialogs
- Introduction and Scope
- kdialog Usage
- Password Dialog
- Shell Script Return Values
- Shell Script Return Value with Error
- Password Dialog, with Return Value Check
- Password Dialog Showing Redirection
- Password Dialog Using a Shell Variable
- Password Dialog with Title
- kdialog Dialog Types
- Basic message boxes
- Information level message box
- Sorry level message box
- Error level message box
- Non-Interrupting Notifications
- –passivepopup dialog box
- More Message Boxes
- –yesno message box
- –warningyesno message box
- –warningcontinuecancel message box
- –yesnocancel message box
- –warningyesnocancel message box
- Suppressing the display of a dialog
- Information level message box, with –dontagain
- User Input dialogs
- –inputbox dialog box
- –inputbox dialog box with default parameter
- Displaying files
- –textbox dialog box
- –textbox dialog box with dimensions
- Menu and Selection Dialogs
- –menu dialog box
- –checklist dialog box
- –radiolist dialog box
- –combobox dialog box
- File Selection Dialogs
- –getopenfilename dialog box
- –getopenfilename dialog box with MIME filter
- –getopenfilename dialog box with wildcard filter
- –getsavefilename dialog box
- –getsavefilename dialog box with filter
- –getexistingdirectory dialog box
- Progress Dialogs
- –progressbar dialog box example
- –progressbar dialog box example, with Cancel
Kdialog linux что это
Bash — замечательная штука! В подавляющем большинстве случаев намного удобнее произвести настройки системы в командной строке, чем тыкать по кнопочкам и путешествовать по множеству окон, а самое приятное то, что любые настройки можно автоматизировать написав скрипт. Но иногда возникают такие ситуации, что к вашим замечательным скриптам необходимо дать доступ людям, которые не имеют навыков использования командной строки. В таком случае возникает необходимость создания простого примитивного подобия графического интерфейса, причем обычно достаточно функционала диалоговых окон.
В KDE можно легко создавать диалоговые окна в bash-скриптах, используя программу Kdialog. Причем окна могут быть самые разнообразные от обычных yes-no-cancel, до диалогов открытия/сохранения файла и отображения полосы прогресса. Использование продемонстрирую на своем реальном примере.
У меня на домашнем компьютере возможны две конфигурации сети: первая — это настройка по умолчанию на использование Интернета от провайдера и вторая — виртуальное соединение vtund с работой и использование рабочего Интернет-соединения. Между этими конфигурациями мне периодически надо переключаться. Для всего этого у меня, конечно же, есть различные скрипты. На эти скрипты я и навесил немного гуйчика.
Итак, у меня есть 5 скриптов:
- enetconf — служит для запуска net_conf_choise.sh с правами пользователя root
- net_conf_choise.sh — скрипт отвечающий за выбор конфигурации
- network_default.sh — настраивает сеть по умолчанию
- vtund.run — поднимает vtund-соединение и запускает set_local_routes.sh
- set_local_routes.sh — устанавливает прямые маршруты для локальных сетей провайдера, чтобы не ходить на эти ресурсы через рабочее Интернет-соединение.
Скрипт enetconf содержит следующие строки:
Первые две строки понятны — это переход в каталог со скриптами, а вот последняя строка выводит диалоговое окно для ввода пароля root и в случае правильного пароля выполняет команду, указанную после параметра «-c» с правами суперпользователя, которые необходимы для выполнения команд содержащихся в других скриптах.
В скрипте net_conf_choise.sh показан пример использования окна выбора. В переменную CHOISE будет сохранен символ «a», если будет выбран пункт «vtund» и «b», если выбран «default». В зависимости от выбора будет запущен соответствующий скрипт настройки сети.
При выборе в окне пункта default будет запущен скрипт network_default.sh:
В этом скрипте показано использование окна с полосой прогресса. Сначала запускается сама программа kdialog, которая отображает окно. Для взаимодействия скрипта с программой kdialog используется программа qdbus. qdbus — это консольная программа, которая позволяет «общаться» с приложениями через систему D-Bus.
Другие два скрипта я описывать не буду, потому что в vtund.run программа kdialog используется таким же образом, как и в network_default.sh, а set_local_routes.sh вообще не содержит вызовов окон.
Приведенные примеры демонстрируют, как можно украсить или сделать более доступными ваши скрипты, не прибегая по сути к настоящему программированию. Больше примеров использования kdialog можно посмотреть тут, а здесь есть примеры использования других графических программ в bash-скриптах. Маленькие интересные примеры использования qdbus можно глянуть тут.
Замечание! В KDE3 вместо qdbus надо использовать dcop.
Если у вас не работает kdesu в KDE 4, то посмотрите мое сообщение о баге, на который я наткнулся в openSUSE 11.4, вдруг поможет.
Источник
Shell Scripting with KDE Dialogs
Introduction and Scope
There are some misconceptions that Plasma is only a graphical environment. While it is true that Plasma is an outstanding desktop environment, the Unix heritage of command line and scripting is also well supported by Plasma. In particular, KDE applications can be controlled from the command line, and shell scripts can make use of some of the KDE widget set.
To use this tutorial, you’ll need to have some basic familiarity with command line fundamentals, and be at least aware of shell scripting. Like any other programming environment, effective shell scripting requires solid knowledge of the environment. However, you should be able to make sense of the examples with only basic understanding. The downside to this is that if you are very familiar with shell scripting, some of the explanation is likely to be redundant.
This tutorial assumes that you are using the GNU bash shell, or something directly compatible. Users of other shells (especially fish and variants) may need to modify the examples.
Shell scripting techniques and usage varies a lot. Sometimes a script is only meant to be run by the system (e.g. as cron job), and other times scripts are really applications intended to be run by users. Plasma includes features that allow you to use some KDE functionality from a shell script, which can save work, and can also make your script feel like it is part of a nicely integrated application set.
As an example, consider something like a password dialog. If you need a user to enter a password, you can easily generate a dialog from your script that looks like the following:
kdialog Usage
Password Dialog
The key to using KDE dialogs in shell scripts is an application named kdialog . To generate a password dialog as shown in above, you could use the following command line.
Let’s look at the code in a bit more detail. The arguments to kdialog are used to control the type of dialog that is produced and the parameter or parameters of that dialog box. In the case of the password dialog, you use —password to specify the dialog type, and then follow that with the parameter, which is the text that appears in the dialog box.
Shell Script Return Values
Each time you run kdialog (or any other application), there is a return value that indicates whether the application ran as expected, or failed in some way. You can access this return value as $? , as shown in the following example.
In this example, the return value is zero. It would be one if the Cancel button had been selected instead of the OK button.
Shell Script Return Value with Error
The convention is that negative numbers indicate failure, however the shell normally subtracts them from 256. This means that if you fail to specify a required argument, the system returns -2, and $? returns 254.
Password Dialog, with Return Value Check
In a shell script, you might choose to test the return value after each invocation.
In addition to the return value, you also get the password itself (assuming that you selected OK). After all, what is the point of a password dialog unless you can use the result?
Password Dialog Showing Redirection
For the password dialog, and other kdialog dialogs that provide input capabilities, the output is sent to standard output. This allows you to redirect the input to a file, or pipe it to another program. In the case of the password dialog, the text that is entered will be echoed as shown in
Password Dialog Using a Shell Variable
Instead of saving the result in a file, you can also use a shell variable. Note that you need to use the “backtick” notation — this key is normally found on the top left of English (British or American) layout keyboards, above the “7” key on French layout keyboards, and on the top right of German layout keyboards.
Password Dialog with Title
While not shown in the previous examples, you can also use the –title option to specify the title of the dialog box, as shown in the following example.
Which results in:
kdialog Dialog Types
The password dialog is just one of the many dialogs that kdialog can provide. This section provides an overview of each type, and describes the arguments you need to provide for each dialog type.
Basic message boxes
Basic message boxes are intended to provide status type information. There are variations to indicate the importance of the information (information, warnings, or errors). In each case, the argument is the text to provide, as shown in the following examples.
Information level message box
Sorry level message box
Error level message box
The return value for these basic message boxes is zero.
While not used in these examples, you can use the —title to set the window title as well. This option can be used with any of the dialog types.
Non-Interrupting Notifications
kdialog supports the concept of a popup dialog that does not grab focus, called a passive popup.
–passivepopup dialog box
—passivepopup takes a text label to display, and a timeout. The display will be automatically removed when the timeout (which is in seconds) has elapsed, or when the user clicks on the popup.
More Message Boxes
Sometimes you need more than the basic message box allows. Perhaps you have a potentially dangerous action, and you need to give the user a second chance. Or perhaps you just need a decision based on some information. kdialog provides some of the tools you might need.
–yesno message box
A —yesno type dialog is probably the simplest of this type, as shown below. Like the simple message boxes previously, it requires a text string, which is shown in the message box.
–warningyesno message box
A variation on the —yesno dialog type is the —warningyesno , which modifies the dialog box appearance a bit.
–warningcontinuecancel message box
A further variation is to use a —warningcontinuecancel dialog type, which has the same usage, but has different button labels, and may fit some situations better.
–yesnocancel message box
Another variation on the —yesno dialog type is to add a third option, as shown in the —yesnocancel dialog type.
–warningyesnocancel message box
There is also a —warningyesnocancel variation, as shown below.
Suppressing the display of a dialog
Sometimes you will be using kdialog in a loop, or other situation where a message may be repeated. For example, you might be iterating through a list of files, and you raise an error for each file you cannot open because of permission problems. This can produce a really bad user experience because the error is repeated over and over.
The normal KDE way to deal with this is to allow the user to suppress the display of a message in the future by selecting a checkbox, and kdialog allows you to do this with the —dontagain option. This option takes a file name and an entry name, and if the user selects the checkbox, then an entry is written to the specified file, with the specified entry name.
Information level message box, with –dontagain
As an example, consider an information level message box for display of a file missing message.
As noted above, an entry is written to a file when the user selects the checkbox.
The effect of this entry is to suppress future display of dialogs using that filename. In the example above, this means myscript:nofilemsg. This will take effect across all KDE applications, so be careful of the filename you use.
User Input dialogs
There are two basic free-form user input dialog types — the —inputbox type and the —password type. The password dialog was covered in depth in a previous section — see the Section called kdialog Usage.
–inputbox dialog box
The —inputbox dialog type requires at least one parameter, which is used as the text in the dialog box.
–inputbox dialog box with default parameter
The return value depends on the button used. OK returns 0. Cancel returns 1.
The string that is entered (or modified / accepted if default text is used) is returned on standard output. If the user chooses Cancel, no output is sent.
Displaying files
–textbox dialog box
A common requirement for shell scripts is the ability to display a file. kdialog supports this with the —textbox dialog type. This dialog type has one mandatory parameter, which is the name of the file to be displayed. There are also two optional parameters which specify the width and height of the dialog box in pixels. If these are not specified, 100 pixels by 100 pixels is used.
–textbox dialog box with dimensions
Menu and Selection Dialogs
–menu dialog box
This section covers simple menus, checklists, radio buttons and combo-boxes. These are typically used for providing a choice of options. The menu is used to select one of a range of options. Each option is defined using two arguments, which you might like to think of as a key and a label. An example of the usage is shown below.
If you select the first option (in this case American English and press OK, then kdialog will send the associated key (in this case the letter a) to standard output. Note that the keys do not need to be lower case letters — you can equally use numbers, upper case letters, strings or the contents of shell variables.
As with the other examples we’ve seen, the return value depends on the button used. OK returns 0. Cancel returns 1.
–checklist dialog box
A checklist is similar to a menu, except that the user can select more than one option. In addition, a reasonable set of default selections can be provided. To do this, each option is defined using three arguments, which you might like to think of as a key, a label and a default state. An example of the usage is shown below.
Clearly the result can contain more than one string, since the user can select more than one label. By default, the results are returned on a single line, however you can use the —separate-output to get a carriage return between each result. These two cases are shown in the example below, where all of the options were selected in each case.
As for the menu example, the return value depends on the button used. OK returns 0. Cancel returns 1.
–radiolist dialog box
The radiolist is very similar to the checklist, except that the user can only select one of the options. An example is shown below:
Note that if you try to turn on more than one option by default, only the last option turned on will be selected. If you don’t turn on any of the options, and the user doesn’t select any, kdialog will raise an assertion, so don’t do this.
–combobox dialog box
A combo-box is slightly different to the previous menu options, in that it doesn’t use keys, but instead just returns the selected text. An example is shown below:
File Selection Dialogs
This section covers dialogs to select files to open and save. These dialogs access the power of the underlying KDE dialogs, including advanced filtering techniques and can provide either paths or URLs.
–getopenfilename dialog box
The dialog to select a file to open is invoked with —getopenfilename or —getopenurl . These two commands are used in the same way — only the format of the result changes, so every example shown here can be applied for either format. You have to specify a starting directory, and can optionally provide a filter. Here is a simple example that doesn’t provide any filtering, and accesses the current directory:
As for previous examples, the return value depends on the button used. OK returns 0. Cancel returns 1.
As mentioned previously, the result format varies between the two variations. This is shown below, in each case selecting the same file:
Note that the user can only select an existing file with these options. When you doing a lot of opening of files, it can be useful to open the dialog in the directory that was navigated to last time. While you can potentially do this by extracting the directory from the filename, you can use a special KDE feature based on labels, as shown below:
Each time you use the same label (with the colon notation), the last used directory will be used as the starting directory. This will normally improve the user experience. If that label hasn’t been used before, the user’s home directory will be used.
Note that the colon notation selects the last used directory for that label for the kdialog application. If you use two colons instead of one, the labeling scope becomes global and applies to all applications. This global scope is rarely what you want, and is mentioned only for completeness. Since not all files are applicable, it can be useful to restrict the files displayed. This is done using the optional filter argument. The best way to do this is with MIME types, as shown below:
–getopenfilename dialog box with MIME filter
–getopenfilename dialog box with wildcard filter
If it isn’t possible to use MIME types, you can specify a range of wildcards and an optional label, as shown below:
–getsavefilename dialog box
The —getsavefilename and —getsaveurl commands are directly analogous to the file opening dialogs. A simple example is shown below:
Unlike the file opening dialogs, the file saving dialogs allow to user to specify a filename that doesn’t yet exist.
–getsavefilename dialog box with filter
As for the file opening dialogs, the file saving dialogs allow use of the colon notation, and also allow filtering using MIME types and wildcards, as shown below:
–getexistingdirectory dialog box
Sometimes you don’t want to specify a filename, but instead need a directory. While you can specify a “inode/directory” filter to a file open dialog, it is sometimes better to use the —getexistingdirectory type, as shown below:
—getexistingdirectory does not provide any filtering, but it does provide the same starting directory options, including the colon notation.
Progress Dialogs
A progress bar dialog is a useful GUI element when you have a process that will take a long time, and you want to reassure the user that things are happening correctly, rather than having the user believe that the machine may have locked up. If you ever find yourself thinking about writing an information dialog that says something like “…, this may take a while”, it may be appropriate to use a progress bar dialog.
Because you need to make the progress bar change, you can’t use kdialog in the normal way. Instead, you set up the dialog, and use the qdbus tool to make the required changes.
–progressbar dialog box example
A simple use of the –progressbar command is shown below.
Line 1 runs kdialog, with an initial label of Initialising, and a progress bar with four elements. We capture the return value in a variable (which can be named just about anything — I chose dbusRef) for later use with the qdbus command. Line 2 sets the bar to one stage along, and line 3 changes the label to Thinking really hard. Line 4 is just a delay (which would be when your script would perform the first part of the lengthy task in a real application). Line 5 then increases the progress bar, followed by another delay (representing more processing) in line 6. Line 7 changes the label, while lines 8 through 11 further increase the progress bar over a few seconds. Line 12 closes the progress bar dialog — without this, it will remain displayed. If you’d prefer that the progress bar dialog closed as soon as the bar gets to 100%, you can use the setAutoClose true argument to qdbus. If a task is taking a very long time, the user may decide that it is better cancelled. kdialog can assist with this too, as shown in the example below.
–progressbar dialog box example, with Cancel
As in the previous example, the first line executes kdialog with some initial text, this time with 10 segments; and again we capture the return value in a variable for later use with DBus. Line 2 turns on the display of the Cancel button, which is off by default.
Lines 3 through 7 are a loop. Line three runs qdbus to check if the Cancel button has been pressed, and if it hasn’t been pressed yet, runs line 4 through 6. Line 4 is again a delay, representing processing in a real application. Line 5 runs qdbus to get the current progress bar setting, and adds one to the count (I could have just kept a counter variable, but this approach shows another qdbus usage). Line 6 then sets the progress bar to the incremented value. Line 8 closes the progress bar dialog if the Cancel button has been pressed.
Источник