Tcl linux ��� ���

Tcl/Tk. Альтернативный файловый проводник для платформ Linux и Android

Чем дольше я пишу различные программы на tcl/tk, тем больше восхищаюсь его возможностями и продуманностью. Но была одна вещь, которая не давала мне покою до последнего времени. При разработке GUI часто приходится пользоваться файловым проводником (tk_getSaveFile, tk_getOpenFile или tk_chooseDirectory). И если на платформах Windows или OS X, загружается нативный файловый проводник этих платформ, то на платформах Linux загружается проводник от tcl/tk (ну нет в Linux нативного проводника):

Что не устраивает в этом проводнике? Это отсутствие в нем элементарных операций с папками/файлами — создать, уничтожить, переименовать. Нет, не подумайте в самом tcl все эти механизмы, естественно, реализованы, их просто нет в GUI проводника. Но в Linux это не так заметно. А вот на платформе Android проводник от Tcl/Tk вызывает массу неудобств:

Когда мы говорим про платформу Android, то имеем ввиду разработку приложений на Androwish.

А тут такие времена настали, самоизоляция и т.д. В итоге, родилась балалайка (так еще называют пакеты/package для tcl) tkfe (tk file explorer).

При разработке пакета tkfe учитывалось не только то, что необходимы хотя бы элементарные операции с файлами/каталогами, то и было желание иметь проводник не только в отдельном окне, но и в отдельном фрейме, который пользователь сам разместить по своему желанию в своем GUI. В проекте имеется комплексный пример по использованию пакета. Итак, скачиваем проект, заходим в папку

//TkFileExplorer/samples и запускаем пример:

Собственно пример наглядно демонстрирует все возможности пакета. Например, запустим проводник для выбора папки в отдельном окне:

Сам проводник имеет интерфейс на двух языках: русском и английском. Перевод осуществляется на лету при нажатии кнопки с флагом:

Помимо кнопки с флагом, имеется кнопка с инструментами (tools), при нажатии на которую высвечивается контекстное меню, что можно делать в текущем каталоге (создать каталог/файл ) или с выделенным файлом/папкой (удалить/переименовать):

Любая из функций файлового проводника возвращает имя (подчеркиваю — ИМЯ) переменной (см. пример tkfe_samplefull.tcl), в которую будет записан путь к выбранному файлу или каталогу или которая будет пустая в случае отказа от выбора. После получения имени переменной остается ждать когда, будет получен какой-либо результат, например:

Если вы используете тип размещения проводника frame, то необходимо позаботиться о его размещении на вашей картинке. Размещение может быть любым способом (grid, pack или place). Предпочтительным способом является все же метод place. При нем не стоит заботиться о переформатировании картинки, так как place в отличии от grid и pack, позволяет наложить фрейм поверх имеющейся картинки:

Если внимательно посмотреть на картинку, то можно заметить, что правый скриншот отличается от левого появлением на нем скрытых папок (имена начинаются с точки). Для показа скрытых кнопок надо включить кнопку с иконкой в виде глаза. Папки и файлы можно также сортировать по алфавиту, а файлы по размеру:

Когда проводник размещается во фрейме то также стоит позаботиться о блокировании посторонних кнопок (когда проводник размещается в окне, то об этом заботится балалайка tkfe).

В пакет tkfe включены две функции, которые делают недоступными (all_disable) или доступными (all_enable) виджеты в пределах заданного виджета:

Однако я предпочитаю пользоваться функций tk busy. Это хорошо видно в примере:

Это теория. На практике пакет tkfe был использован в криптографическом АРМ на базе стандартов с открытым ключом cryptoarmpkcs. Теперь использование файлового проводника в этом приложении для платформы Linux выглядит следующим образом:

А вот проводник, размещенный во фрейме:

И, конечно, очень удобно стало работать с проводником на платформе Android:

Кто-то может спросить: А как же Windows или OS X? Да, все замечательно. Но как всегда на Windows — это проблема русификации, в нашем случае это использование кириллицы в именовании файлов и папок, а также использование обратной косой черты. Поэтому в код необходимо добавить следующие строки:

Читайте также:  Unity сборка проекта windows

Вот так выглядит проводник tkfe на платформе Windows:

Сам пакет и примеры его использования лежат здесь.

Источник

Tcl linux ��� ���

There are several options available for obtaining Tcl/Tk. These are listed below.

Operating System Packages

Most Unix / Linux operating system distributions, as well as Mac OS X, include Tcl/Tk. If not already installed, you can use your system’s package manager to install the appropriate packages. For example, on a Debian system, you can type

to install Tcl. Note than some components, even including Tk, man pages and C libraries may be separate packages and installed in a similar manner.

To check the version installed, start Tcl/Tk (usually via running «tclsh» or «wish» from a command line), and typing

This will tell you what version you’re running.

If you do not have privileges to install software or if you need a newer version than the one provided by the system, you may use one of the alternative means of obtaining Tcl as described below.

Binary Distributions

Pre-built Tcl distributions for many common platforms are available for download. These include both traditional installers as well as single file «download and run» executables. See Binary distributions.

Source Distributions

Finally, you always have the option of downloading the Tcl/Tk source distributions and building it yourself. See Source distributions for instructions on downloading and compiling.

A very large number of libraries and extensions are available for Tcl/Tk. The most popular and commonly used ones are catalogued in the Great Unified Tcl/Tk Extension Repository. (In other words, get them from the GUTTER.) The Tcler’s Wiki is an alternate, but uncategorized, resource for the same.

License Information

Tcl/Tk is open source (based on a BSD-style license), so you can use it and modify it virtually any way you want, including for commercial uses. Here is the Tcl source distribution license, but be sure to check the license for any particular distribution you use.

Источник

Tcl linux ��� ���

Tcl is a very simple programming language. If you have programmed before, you can learn enough to write interesting Tcl programs within a few hours. This page provides a quick overview of the main features of Tcl. After reading this you’ll probably be able to start writing simple Tcl scripts on your own; however, we recommend that you consult one of the many available Tcl books for more complete information.

Basic syntax

Tcl scripts are made up of commands separated by newlines or semicolons. Commands all have the same basic form illustrated by the following example:

This command computes the sum of 20 and 10 and returns the result, 30. You can try out this example and all the others in this page by typing them to a Tcl application such as tclsh ; after a command completes, tclsh prints its result.

Each Tcl command consists of one or more words separated by spaces. In this example there are four words: expr , 20 , + , and 10 . The first word is the name of a command and the other words are arguments to that command. All Tcl commands consist of words, but different commands treat their arguments differently. The expr command treats all of its arguments together as an arithmetic expression, computes the result of that expression, and returns the result as a string. In the expr command the division into words isn’t significant: you could just as easily have invoked the same command as

However, for most commands the word structure is important, with each word used for a distinct purpose.

All Tcl commands return results. If a command has no meaningful result then it returns an empty string as its result.

Variables

Tcl allows you to store values in variables and use the values later in commands. The set command is used to write and read variables. For example, the following command modifies the variable x to hold the value 32 :

Читайте также:  Sstp vpn client windows

The command returns the new value of the variable. You can read the value of a variable by invoking set with only a single argument:

You don’t need to declare variables in Tcl: a variable is created automatically the first time it is set. Tcl variables don’t have types: any variable can hold any value.

To use the value of a variable in a command, use variable substitution as in the following example:

When a $ appears in a command, Tcl treats the letters and digits following it as a variable name, and substitutes the value of the variable in place of the name. In this example, the actual argument received by the expr command will be 32*3 (assuming that variable x was set as in the previous example). You can use variable substitution in any word of any command, or even multiple times within a word:

Command substitution

You can also use the result of one command in an argument to another command. This is called command substitution:

When a [ appears in a command, Tcl treats everything between it and the matching ] as a nested Tcl command. Tcl evaluates the nested command and substitutes its result into the enclosing command in place of the bracketed text. In the example above the second argument of the second set command will be 176 .

Quotes and braces

Double-quotes allow you to specify words that contain spaces. For example, consider the following script:

After these three commands are evaluated variable z will have the value 24 + 18 is 42 . Everything between the quotes is passed to the set command as a single word. Note that (a) command and variable substitutions are performed on the text between the quotes, and (b) the quotes themselves are not passed to the command. If the quotes were not present, the set command would have received 6 arguments, which would have caused an error.

Curly braces provide another way of grouping information into words. They are different from quotes in that no substitutions are performed on the text between the curly braces:

This command sets variable z to the value » $x + $y is [expr $x + $y] «.

Control structures

Tcl provides a complete set of control structures including commands for conditional execution, looping, and procedures. Tcl control structures are just commands that take Tcl scripts as arguments. The example below creates a Tcl procedure called power , which raises a base to an integer power:

This script consists of a single command, proc . The proc command takes three arguments: the name of a procedure, a list of argument names, and the body of the procedure, which is a Tcl script. Note that everything between the curly brace at the end of the first line and the curly brace on the last line is passed verbatim to proc as a single argument. The proc command creates a new Tcl command named power that takes two arguments. You can then invoke power with commands like the following:

When power is invoked, the procedure body is evaluated. While the body is executing it can access its arguments as variables: base will hold the first argument and p will hold the second.

The body of the power procedure contains three Tcl commands: set , while , and return . The while command does most of the work of the procedure. It takes two arguments, an expression ( $p > 0 ) and a body, which is another Tcl script. The while command evaluates its expression argument using rules similar to those of the C programming language and if the result is true (nonzero) then it evaluates the body as a Tcl script. It repeats this process over and over until eventually the expression evaluates to false (zero). In this case the body of the while command multiplied the result value by base and then decrements p . When p reaches zero the result contains the desired power of base . The return command causes the procedure to exit with the value of variable result as the procedure’s result.

Читайте также:  Samsung ml1710 driver windows 10

Where do commands come from?

As you have seen, all of the interesting features in Tcl are represented by commands. Statements are commands, expressions are evaluated by executing commands, control structures are commands, and procedures are commands.

Tcl commands are created in three ways. One group of commands is provided by the Tcl interpreter itself. These commands are called builtin commands. They include all of the commands you have seen so far and many more (see below). The builtin commands are present in all Tcl applications.

The second group of commands is created using the Tcl extension mechanism. Tcl provides APIs that allow you to create a new command by writing a command procedure in C or C++ that implements the command. You then register the command procedure with the Tcl interpreter by telling Tcl the name of the command that the procedure implements. In the future, whenever that particular name is used for a Tcl command, Tcl will call your command procedure to execute the command. The builtin commands are also implemented using this same extension mechanism; their command procedures are simply part of the Tcl library.

When Tcl is used inside an application, the application incorporates its key features into Tcl using the extension mechanism. Thus the set of available Tcl commands varies from application to application. There are also numerous extension packages that can be incorporated into any Tcl application. One of the best known extensions is Tk, which provides powerful facilities for building graphical user interfaces. Other extensions provide object-oriented programming, database access, more graphical capabilities, and a variety of other features. One of Tcl’s greatest advantages for building integration applications is the ease with which it can be extended to incorporate new features or communicate with other resources.

The third group of commands consists of procedures created with the proc command, such as the power command created above. Typically, extensions are used for lower-level functions where C programming is convenient, and procedures are used for higher-level functions where it is easier to write in Tcl.

Other features

Tcl contains many other commands besides the ones used in the preceding examples. Here is a sampler of some of the features provided by the builtin Tcl commands:

  • More control structures, such as if , for , foreach , and switch .
  • String manipulation, including a powerful regular expression matching facility. Arbitrary-length strings can be passed around and manipulated just as easily as numbers.
  • I/O, including files on disk, network sockets, and devices such as serial ports. Tcl provides particularly simple facilities for socket communication over the Internet.
  • File management: Tcl provides several commands for manipulating file names, reading and writing file attributes, copying files, deleting files, creating directories, and so on.
  • Subprocess invocation: you can run other applications with the exec command and communicate with them while they run.
  • Lists: Tcl makes it easy to create collections of values (lists) and manipulate them in a variety of ways.
  • Arrays: you can create structured values consisting of name-value pairs with arbitrary string values for the names and values.
  • Time and date manipulation.
  • Events: Tcl allows scripts to wait for certain events to occur, such as an elapsed time or the availability of input data on a network socket.

Examples

Tutorial

Have some time to delve a bit further into the language? The Tcl Tutorial is a great way to learn more about Tcl’s various commands and language features.

Источник

Оцените статью