diff --git a/_posts/2016-06-05-aw-formatters-and-macros.md b/_posts/2016-06-05-aw-formatters-and-macros.md new file mode 100644 index 0000000..a1885e9 --- /dev/null +++ b/_posts/2016-06-05-aw-formatters-and-macros.md @@ -0,0 +1,123 @@ +--- +category: en +type: paper +hastr: true +layout: paper +tags: awesome-widgets, pytextmonitor +title: Awesome Widgets - Introducing custom formatters and macros +short: aw-formatters-and-macros +--- +This paper describes new major features of Awesome Widgets 3.2.0. + + + +# Formatters + +Actually it has own graphical interface for configuration, but let me describe +how to configure it by using your editor. + +To apply formatters use `$HOME/.local/share/awesomewidgets/formatters/formatters.ini` +file. It has only one section named `[Formatters]` in which keys are AW keys, +values are related formatter names. For example, + +```ini +[Formatters] +cpu=myformatter +``` + +means that formatter `myformatter` will be used for key `cpu`. + +All formatters are stored in the same directory, one formatter per file, files +should have `.desktop` extension. Each formatter has the following configuration +fields inside `[Desktop Entry]` section: + +| Field | Required | Value | Default | +| -------------------|----------|----------------------------------|------------| +| Name | yes | formatter name | none | +| Comment | no | comment | empty | +| X-AW-Type | no | formatter type. The following types are supported: `NoFormat`, `DateTime`, `Float`, `List`, `Script` | NoFormat | + +Each formatter type has own behaviour and own settings and they are described +below. Also there are system-wide settings which are stored in `/usr/share/awesomewidgets/formatters/`, system formatters will be overwritten by +user defined ones, but formatter settings (i.e. `formatters.ini`) will be appended. + +## `NoFormat` formatter + +Just puts value as string directly. It has no any special settings. + +## `DateTime` formatter + +Converts `QDateTime` object to string. + +| Field | Required | Value | Default | +| -------------------|----------|----------------------------------|------------| +| X-AW-Format | yes | Qt specific format string | (empty) | + +Actually it is the same as `$ctime` tag and has the same configuration. + +## `Float` formatter + +Converts any number to string. + +| Field | Required | Value | Default | +| -------------------|----------|----------------------------------|------------| +| X-AW-FillChar | no | char to fill number to `X-AW-Width` | (space) | +| X-AW-Format | no | Qt specific number format, supported values are `e`, `E`, `f`, `g`, `G` | `f` | +| X-AW-Multiplier | no | float to which value will be multiplied | 1.0 | +| X-AW-Precision | no | show this count of symbols after dot | -1 (as expected) | +| X-AW-Summand | no | float to which value will be increased | 0.0 | +| X-AW-Width | no | width of the field | 0 (do not limit) | + +Please note that actual formula is `X-AW-Multiplier * value + X-AW-Summand`. + +## `List` formatter + +Coverts list of string objects to string. + +| Field | Required | Value | Default | +| -------------------|----------|----------------------------------|------------| +| X-AW-Filter | no | filter by this regular expression | (empty) | +| X-AW-Separator | no | use this separator to join strings | (empty | +| X-AW-Sort | no | boolean, sort or not list | false | + +## `Script` formatter + +Uses javascript code to convert value to string. Value will be passed as argument +to fuction. + +| Field | Required | Value | Default | +| -------------------|----------|----------------------------------|------------| +| X-AW-AppendCode | no | prepend code by `(function(value) {` and append `})` | true | +| X-AW-Code | no | code for use | | +| X-AW-HasReturn | no | if false will append your code by `return output;`. Only works if `X-AW-AppendCode` is `true` | false | + +Actually for example to covert download speed to kibibits on the fly you may use +the following: + +```ini +X-AW-AppendCode=true +X-AW-Code="output=value/8.0;" +X-AW-HasReturn=false +``` + +The code will be expanded to: + +```javascript +(function(value) { + output = value / 8.0; + return output; +}) +``` + +# Macros + +Another new feature is macros. User may define any own function by using the following +construction `$aw_macro{{macro body here with $some_arg}}`. + +The first argument is macros name, which is required. Another ones describe arguments +which will be passed to the macro call. Macro body may have any text (including templates, +lambdas, etc) and arguments which are defined by using `$`. + +To put defined macro to your code use the following construction: +`$aw_macro_my_macro_name<$cpu,$cpucl>{{}}` (body will be ignored here). In this +example macro will be expanded to `macro body here with $cpu`. diff --git a/projects/_posts/2013-02-21-awesome-widgets.md b/projects/_posts/2013-02-21-awesome-widgets.md index dcd1097..ebbbce4 100644 --- a/projects/_posts/2013-02-21-awesome-widgets.md +++ b/projects/_posts/2013-02-21-awesome-widgets.md @@ -24,6 +24,7 @@ links: - Ubuntu package - Migration to version 2.0 - Extensions + - Formatters and macros --- @@ -321,15 +322,18 @@ To allow some features with lambdas and templates with 3.1.0 has been introduced several internal functions. They have the same syntax: `$aw_function{% raw %}{{{% endraw %}body{% raw %}}}{% endraw %}`. where args may be optional. If there are several args they should be comma -separated. If you want to pass comma as arg use `$,`. Functions will be called +separated. If you want to pass comma as arg use `$,`. If you want to use double +brackets inside body screen them by using `$`, e.g. `${`. Functions will be called once and before any actions. | Function | Description | Args | Body | |----------|-------------|------|------| -| `aw_all` | was introduced for debug purposes, return all keys by regexp in pretty format | (none) | regexp for search | +| `aw_all` | was introduced for debug purposes, return all keys by regexp in pretty format | separator | regexp for search | | `aw_count` | return count of keys by given regexp | (none) | regexp for search | | `aw_keys` | return keys by given regexp joined by separator | separator | regexp for search | | `aw_names` | return key names (i.e. without `$`) by given regexp joined by separator | separator | regexp for search | +| `aw_macro` | define user macro | macro name, macro arguments if any | macro body | +| `aw_macro_*` | (* is macro name) call of user defined macro | macro arguments in the same order | ignored | ### Advanced settings diff --git a/ru/_posts/2016-06-05-aw-formatters-and-macros.md b/ru/_posts/2016-06-05-aw-formatters-and-macros.md new file mode 100644 index 0000000..ba319ed --- /dev/null +++ b/ru/_posts/2016-06-05-aw-formatters-and-macros.md @@ -0,0 +1,124 @@ +--- +category: ru +type: paper +hastr: true +layout: paper +tags: awesome-widgets, pytextmonitor +title: Awesome Widgets - Произвольные форматеры и макросы +short: aw-formatters-and-macros +--- +Данная статья описывает два основных изменения в версии 3.2.0. + + + +# Форматеры + +На самом деле, форматеры имеют графический интерфейс для настройки, но здесь +я опишу, как их можно настроить, используя текстовый редактор. + +Чтобы включить форматер, используйте файл `$HOME/.local/share/awesomewidgets/formatters/formatters.ini`. +Данный файл имеет только одну секцию `[Formatters]`, в которой ключи - это +соответствующие ключи в виджете, а значения - имена соответствующих форматеров. +Например: + +```ini +[Formatters] +cpu=myformatter +``` + +означает, что форматер `myformatter` будет использован для ключа `cpu`. + +Все форматеры хранятся в той же директории, один форматер на файл, файлы должны +иметь расширение `.desktop`. Каждый форматер имееет следующие настройки внутри +секции `[Desktop Entry]`: + +| Поле | Обязательное | Значение | По-умолчанию | +| -------------------|--------------|----------------------------------|--------------| +| Name | да | имя форматера | none | +| Comment | нет | комментарий | empty | +| X-AW-Type | нет | тип форматера. Поддерживаются следующие типы: `NoFormat`, `DateTime`, `Float`, `List`, `Script` | NoFormat | + +Каждый тип форматера имеет свое поведение и свои настройки, которые описаны ниже. +Также существуют системные настройки, которые хранятся в `/usr/share/awesomewidgets/formatters/`, +системные форматеры будут перезаписаны пользовательскими, но настройки (то есть +`formatters.ini`) будут просто дополнены. + +## `NoFormat` форматер + +Просто значение конвертирует в строку. Не имеет никаких особых настроек. + +## `DateTime` форматер + +Конвертирует `QDateTime` объект в строку. + +| Поле | Обязательное | Значение | По-умолчанию | +| -------------------|--------------|----------------------------------|--------------| +| X-AW-Format | да | Qt специфичный формат времени | (пусто) | + +Действует аналогично `$ctime` и имеет аналогичную конфигурацию. + +## `Float` форматер + +Конвертирует любое число в строку. + +| Поле | Обязательное | Значение | По-умолчанию | +| -------------------|--------------|----------------------------------|--------------| +| X-AW-FillChar | нет | символ для заполнения до `X-AW-Width` | (space) | +| X-AW-Format | нет | Qt специфичный формат числа, поддерживаются: `e`, `E`, `f`, `g`, `G` | `f` | +| X-AW-Multiplier | нет | число, на которое значение будет умножено | 1.0 | +| X-AW-Precision | нет | число знаков после запятой | -1 (как получится) | +| X-AW-Summand | нет | число, которое будет добавлено к значению | 0.0 | +| X-AW-Width | нет | ширина числового поля | 0 (не ограничивать) | + +Конечное значение будет получено по формуле `X-AW-Multiplier * value + X-AW-Summand`. + +## `List` форматер + +Конвертирует список строк в строку + +| Поле | Обязательное | Значение | По-умолчанию | +| -------------------|--------------|----------------------------------|--------------| +| X-AW-Filter | нет | фильтровать список по заданному регулярному выражению | (пусто) | +| X-AW-Separator | нет | использовать разделитель для объединения | (пусто) | +| X-AW-Sort | нет | сортировать или нет список | false | + +## `Script` форматер + +Использует javascript код для конвертации значения в строку. Значение будет +передано как аргумент в функцию. + +| Поле | Обязательное | Значение | По-умолчанию | +| -------------------|--------------|----------------------------------|--------------| +| X-AW-AppendCode | нет | вставить код между `(function(value) {` и `})` | true | +| X-AW-Code | нет | код для использования | (пусто) | +| X-AW-HasReturn | нет | если false, то дополнить код `return output;`. Работает только если `X-AW-AppendCode` - `true` | false | + +Например, для конвертации скорости загрузки в кибибиты на лету, вы можете использовать +следующее: + +```ini +X-AW-AppendCode=true +X-AW-Code="output=value/8.0;" +X-AW-HasReturn=false +``` + +Код будет развернут в следующее: + +```javascript +(function(value) { + output = value / 8.0; + return output; +}) +``` + +# Макросы + +Другая особенность - макросы. Пользователь может определить свою функцию, используя +следующую конструкцию `$aw_macro{{macro body here with $some_arg}}`. + +Первый аргумент - имя макроса - обязателен. Другие описывают аргументы, которые +будут переданы при вызове макроса. Тело макроса может иметь любой текст (включая +шаблоны, лямбды и прочее) и аргументы, определенные используя `$`. + +Чтобы вызвать макрос в коде нужно использовать следующую конструкцию: `$aw_macro_my_macro_name<$cpu,$cpucl>{{}}` (тело функции будет проигнорировано +здесь). В данном примере, макрос будет развернут в `macro body here with $cpu`. diff --git a/ru/projects/_posts/2013-02-21-awesome-widgets.md b/ru/projects/_posts/2013-02-21-awesome-widgets.md index 2697828..3ff0db2 100644 --- a/ru/projects/_posts/2013-02-21-awesome-widgets.md +++ b/ru/projects/_posts/2013-02-21-awesome-widgets.md @@ -25,6 +25,7 @@ links: - Пакеты для Ubuntu - Миграция на версию 2.0 - Расширения + - Форматеры и макросы --- @@ -244,7 +245,7 @@ html код. Смотри [вопрос](//github.com/arcan1s/awesome-widgets/is Начиная с версии 3.0.0 основной виджет поддерживает лямбда выражения, которые рассчитываются в рантайме. Они объявляются использованием конструкции -`${% raw %}${{{% endraw %} {% raw %}}}{% endraw %}`: +`{% raw %}${{{% endraw %} {% raw %}}}{% endraw %}`: ```javascript {% raw %}${{{% endraw %} @@ -328,15 +329,18 @@ three() `$aw_function{% raw %}{{{% endraw %}body{% raw %}}}{% endraw %}`, где аргументы могут быть опциональными. Если вы хотите передать несколько аргументов, они должны быть разделены запятыми. Если вы хотите передать запятую, как -аргумент, используйте `$,`. Функции будут вызваны один раз при запуске перед все -остальным. +аргумент, используйте `$,`. Чтобы использовать сдвоенные скобки внутри тела, их +нужно экранировать, используя `$`, например `${`. Функции будут вызваны один раз +при запуске перед всем остальным. | Функция | Описание | Аргументы | Тело | |---------|----------|-----------|------| -| `aw_all` | была введена для отладки, возвращает все ключи по регекспу | (нет) | регексп для поиска | +| `aw_all` | была введена для отладки, возвращает все ключи по регекспу | разделитель | регексп для поиска | | `aw_count` | возвращает количество ключей по заданному регекспу | (нет) | регексп для поиска | | `aw_keys` | возвращает ключи по заданному регекспу, объединенные разделителем | разделитель | регексп для поиска | | `aw_names` | возвращает имена ключей (т.е. без `$`) по заданному регекспу, объединенные разделителем | разделитель | регексп для поиска | +| `aw_macro` | определяет пользовательский макрос | имя макроса, аргументы | тело макроса | +| `aw_macro_*` | (* - имя макроса) вызов пользовательского макроса | аргументы макроса в аналогичном порядке | игнорируется | ### Расширенные настройки