mirror of
https://github.com/arcan1s/arcanis.me.git
synced 2025-04-24 23:37:19 +00:00
add page for new features, update aw pages for release
This commit is contained in:
parent
3ee2b178e3
commit
34acd94e7b
123
_posts/2016-06-05-aw-formatters-and-macros.md
Normal file
123
_posts/2016-06-05-aw-formatters-and-macros.md
Normal file
@ -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.
|
||||
|
||||
<!--more-->
|
||||
|
||||
# <a href="#formatters" class="anchor" id="formatters"><span class="octicon octicon-link"></span></a>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.
|
||||
|
||||
## <a href="#formatter-noformat" class="anchor" id="formatter-noformat"><span class="octicon octicon-link"></span></a>`NoFormat` formatter
|
||||
|
||||
Just puts value as string directly. It has no any special settings.
|
||||
|
||||
## <a href="#formatter-datetime" class="anchor" id="formatter-datetime"><span class="octicon octicon-link"></span></a>`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.
|
||||
|
||||
## <a href="#formatter-float" class="anchor" id="formatter-float"><span class="octicon octicon-link"></span></a>`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`.
|
||||
|
||||
## <a href="#formatter-list" class="anchor" id="formatter-list"><span class="octicon octicon-link"></span></a>`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 |
|
||||
|
||||
## <a href="#formatter-script" class="anchor" id="formatter-script"><span class="octicon octicon-link"></span></a>`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;
|
||||
})
|
||||
```
|
||||
|
||||
# <a href="#macros" class="anchor" id="macros"><span class="octicon octicon-link"></span></a>Macros
|
||||
|
||||
Another new feature is macros. User may define any own function by using the following
|
||||
construction `$aw_macro<my_macro_name,some_arg,another_arg>{{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`.
|
@ -24,6 +24,7 @@ links:
|
||||
- <a href="//github.com/arcan1s/awesome-widgets/releases" title="Ubuntu">Ubuntu package</a>
|
||||
- <a href="/en/2014/09/04/migration-to-v2/" title="Migration">Migration to version 2.0</a>
|
||||
- <a href="/en/2014/12/19/aw-v21-bells-and-whistles/" title="ExtItems">Extensions</a>
|
||||
- <a href="/en/2016/06/05/aw-formatters-and-macros/" title="Formatters and macros">Formatters and macros</a>
|
||||
---
|
||||
<!-- info block -->
|
||||
|
||||
@ -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<args>{% 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 |
|
||||
|
||||
### <a href="#advanced" class="anchor" id="advanced"><span class="octicon octicon-link"></span></a>Advanced settings
|
||||
|
||||
|
124
ru/_posts/2016-06-05-aw-formatters-and-macros.md
Normal file
124
ru/_posts/2016-06-05-aw-formatters-and-macros.md
Normal file
@ -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.
|
||||
|
||||
<!--more-->
|
||||
|
||||
# <a href="#formatters" class="anchor" id="formatters"><span class="octicon octicon-link"></span></a>Форматеры
|
||||
|
||||
На самом деле, форматеры имеют графический интерфейс для настройки, но здесь
|
||||
я опишу, как их можно настроить, используя текстовый редактор.
|
||||
|
||||
Чтобы включить форматер, используйте файл `$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`) будут просто дополнены.
|
||||
|
||||
## <a href="#formatter-noformat" class="anchor" id="formatter-noformat"><span class="octicon octicon-link"></span></a>`NoFormat` форматер
|
||||
|
||||
Просто значение конвертирует в строку. Не имеет никаких особых настроек.
|
||||
|
||||
## <a href="#formatter-datetime" class="anchor" id="formatter-datetime"><span class="octicon octicon-link"></span></a>`DateTime` форматер
|
||||
|
||||
Конвертирует `QDateTime` объект в строку.
|
||||
|
||||
| Поле | Обязательное | Значение | По-умолчанию |
|
||||
| -------------------|--------------|----------------------------------|--------------|
|
||||
| X-AW-Format | да | Qt специфичный формат времени | (пусто) |
|
||||
|
||||
Действует аналогично `$ctime` и имеет аналогичную конфигурацию.
|
||||
|
||||
## <a href="#formatter-float" class="anchor" id="formatter-float"><span class="octicon octicon-link"></span></a>`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`.
|
||||
|
||||
## <a href="#formatter-list" class="anchor" id="formatter-list"><span class="octicon octicon-link"></span></a>`List` форматер
|
||||
|
||||
Конвертирует список строк в строку
|
||||
|
||||
| Поле | Обязательное | Значение | По-умолчанию |
|
||||
| -------------------|--------------|----------------------------------|--------------|
|
||||
| X-AW-Filter | нет | фильтровать список по заданному регулярному выражению | (пусто) |
|
||||
| X-AW-Separator | нет | использовать разделитель для объединения | (пусто) |
|
||||
| X-AW-Sort | нет | сортировать или нет список | false |
|
||||
|
||||
## <a href="#formatter-script" class="anchor" id="formatter-script"><span class="octicon octicon-link"></span></a>`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;
|
||||
})
|
||||
```
|
||||
|
||||
# <a href="#macros" class="anchor" id="macros"><span class="octicon octicon-link"></span></a>Макросы
|
||||
|
||||
Другая особенность - макросы. Пользователь может определить свою функцию, используя
|
||||
следующую конструкцию `$aw_macro<my_macro_name,some_arg,another_arg>{{macro body here with $some_arg}}`.
|
||||
|
||||
Первый аргумент - имя макроса - обязателен. Другие описывают аргументы, которые
|
||||
будут переданы при вызове макроса. Тело макроса может иметь любой текст (включая
|
||||
шаблоны, лямбды и прочее) и аргументы, определенные используя `$`.
|
||||
|
||||
Чтобы вызвать макрос в коде нужно использовать следующую конструкцию: `$aw_macro_my_macro_name<$cpu,$cpucl>{{}}` (тело функции будет проигнорировано
|
||||
здесь). В данном примере, макрос будет развернут в `macro body here with $cpu`.
|
@ -25,6 +25,7 @@ links:
|
||||
- Пакеты для <a href="//github.com/arcan1s/awesome-widgets/releases" title="Ubuntu">Ubuntu</a>
|
||||
- <a href="/ru/2014/09/04/migration-to-v2/" title="Миграция">Миграция на версию 2.0</a>
|
||||
- <a href="/ru/2014/12/19/aw-v21-bells-and-whistles/" title="Расширения">Расширения</a>
|
||||
- <a href="/en/2016/06/05/aw-formatters-and-macros/" title="Форматеры и макросы">Форматеры и макросы</a>
|
||||
---
|
||||
<!-- info block -->
|
||||
|
||||
@ -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<args>{% raw %}{{{% endraw %}body{% raw %}}}{% endraw %}`, где
|
||||
аргументы могут быть опциональными. Если вы хотите передать несколько аргументов,
|
||||
они должны быть разделены запятыми. Если вы хотите передать запятую, как
|
||||
аргумент, используйте `$,`. Функции будут вызваны один раз при запуске перед все
|
||||
остальным.
|
||||
аргумент, используйте `$,`. Чтобы использовать сдвоенные скобки внутри тела, их
|
||||
нужно экранировать, используя `$`, например `${`. Функции будут вызваны один раз
|
||||
при запуске перед всем остальным.
|
||||
|
||||
| Функция | Описание | Аргументы | Тело |
|
||||
|---------|----------|-----------|------|
|
||||
| `aw_all` | была введена для отладки, возвращает все ключи по регекспу | (нет) | регексп для поиска |
|
||||
| `aw_all` | была введена для отладки, возвращает все ключи по регекспу | разделитель | регексп для поиска |
|
||||
| `aw_count` | возвращает количество ключей по заданному регекспу | (нет) | регексп для поиска |
|
||||
| `aw_keys` | возвращает ключи по заданному регекспу, объединенные разделителем | разделитель | регексп для поиска |
|
||||
| `aw_names` | возвращает имена ключей (т.е. без `$`) по заданному регекспу, объединенные разделителем | разделитель | регексп для поиска |
|
||||
| `aw_macro` | определяет пользовательский макрос | имя макроса, аргументы | тело макроса |
|
||||
| `aw_macro_*` | (* - имя макроса) вызов пользовательского макроса | аргументы макроса в аналогичном порядке | игнорируется |
|
||||
|
||||
### <a href="#advanced" class="anchor" id="advanced"><span class="octicon octicon-link"></span></a>Расширенные настройки
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user