From 54577f95d20290ddaf9ed1b5b015ca97a00cbe43 Mon Sep 17 00:00:00 2001 From: Evgeny Date: Tue, 31 Aug 2021 12:49:15 +0300 Subject: [PATCH] update readme to reflect latest api changes --- README.md | 42 +++++++++++++++++++++++++++++++---------- README_ru.md | 15 +++++++-------- samples/menu-sample.lua | 28 +++++++++++++++------------ 3 files changed, 55 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index e6f955e..02098cb 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ For most network scripts `on_alarm()` should be used. * `ui:get_secondary_text_color()` - returns the secondary text color (usually gray) in #XXXXXX format; * `ui:set_folding_flag(boolean)` - sets or clears the flag of the folded mode of the widget, the function should be called before the data display functions; -When you click on any element of the interface, the `on_click(number)` callback will be executed, where number is the ordinal number of the element. For example, if you use `ui:show_buttons` to show three buttons, then clicking the first button will call `on_click` with argument 1, the second with arguments 2, and so on. If there is only one element on the screen, the argument will always be equal to one and can be omitted. +When you click on any element of the interface, the `on_click(number)` callback will be executed, where number is the ordinal number of the element. A long click calls `on_long_click(number)`. For example, if you use `ui:show_buttons` to show three buttons, then clicking the first button will call `on_click` with argument 1, the second with arguments 2, and so on. If there is only one element on the screen, the argument will always be equal to one and can be omitted. The `ui:show_chart()` function takes a string as its third argument to format the x and y values on the screen. For example, the string `x: date y: number` means that the X-axis values should be formatted as dates, and the Y-values should be formatted as a regular number. There are four formats in total: @@ -62,21 +62,19 @@ If the first argument of the dialog contains two lines separated by `\n`, the se # Context menu -* `ui:prepare_context_menu(table)` - prepares the context menu, which will be automatically shown when the item is held on the screen for a long time. - -As an argument, the function takes a table of tables with icons and names of menu items. For example, the following code will prepare a context menu with three items: +* `ui:show_context_menu(table)` - function shows the context menu. Function takes a table of tables with icons and menu item names as its argument. For example, the following code will prepare a context menu of three items: ``` ui:prepare_context_menu({ - {"share", "Menu item 1"}, - {"copy", "Menu item 2"}, - {"trash", "Menu item 3"}, + { "share", "Menu item 1" } + { "copy", "Menu item 2" } + { "trash", "Menu item 3" }, }) ``` -`share`, `copy` and `trash` are the names of the icons, which can be found on the [Fontawesome site](https://fontawesome.com/). +Here `share`, `copy` and `trash` are the names of the icons, which can be found at [Fontawesome](https://fontawesome.com/). -When you click on any menu item, the callback `on_context_menu_click(item_idx, menu_idx)` will be called, the first argument of which is the index of the item for which the menu was called, and the second is the index of the item of the menu itself. +When you click on any menu item, the collab `on_context_menu_click(item_idx)` will be called, where `item\_idx` is the index of the menu item. # System @@ -88,7 +86,8 @@ When you click on any menu item, the callback `on_context_menu_click(item_idx, m * `system:get_from_clipboard()` - returns a string from the clipboard: * `system:share_text(string)` - opens the "Share" system dialog; * `system:get_lang()` - returns the language selected in the system; -* `system:get_tz_offset()` - get TimeZone offset in seconds. +* `system:get_tz_offset()` - returns TimeZone offset in seconds; +* `system:get_battery_info()` - return table with battery info. The result of executing a shell command is sent to the `on_shell_result(string)` callback. @@ -130,6 +129,29 @@ These functions do not return any value, but instead call the `on_network_result If `id` was specified in the request, then the function will call `on_network_result_$id(string, [code])` instead of the callback described above. That is, if the id is "server1", then the callback will look like `on_network_result_server1(string, [code])`. +# Calendar + +* `calendar:get_events([start_date], [end_date], [cal_table])` - returns table of event tables of all calendars, start\_date - event start date, end\_date - event end date, cal\_table - calendar ID table; +* `calendar:get_calendars()` - returns table of calendars tables; +* `calendar:open_event_dialog(id)` - opens an event in the system calendar. + +Event table format: + +* `id` - event ID; +* `calendar_id` - calendar ID; +* `title` - title of the event; +* `description` - description of the event; +* `location` - address of the event by string; +* `begin` - start time of the event (in seconds); +* `end` - time of the event end (in seconds); +* `all_day` - boolean value, which means that the event lasts all day. + +Calendar table format: + +* `id` - calendar identifier; +* `name` - name of the calendar; +* `color` - color of the calendar in the format #XXXXXXXX. + # Data processing * `ajson:get_value(string, string)` - gets the specified value from JSON; the first argument is a JSON string, the second is an instruction to get the value. diff --git a/README_ru.md b/README_ru.md index 72e6cd7..d808d4a 100644 --- a/README_ru.md +++ b/README_ru.md @@ -2,7 +2,7 @@ Начиная с версии 4.0, AIO Launcher поддерживает скрипты, а точнее специальные виджеты, написанные на скриптовом языке [Lua](https://en.wikipedia.org/wiki/Lua_(programming_language)). Такие виджеты следует размещать в каталоге `/sdcard/Android/data/ru.execbit.aiolauncher/files/`. Затем их можно добавить на экран используя раздел настроек "Скрипты" или с помощью бокового меню. -Возможности скриптов ограничены, но с их помощью можно практически безгранично расширять функциональность приложения (посмотрите примеры в этом репозитории). +Возможности скриптов ограничены, но с их помощью можно практически безгранично расширять функциональность приложения (посмотрите примеры в этом репозитории). # Функции (колбеки) жизненного цикла @@ -29,7 +29,7 @@ * `ui:get_secondary_text_color()` - возвращает цвет вторичного текста (обычно серый) в формате #XXXXXX; * `ui:set_folding_flag(boolean)` - устанавливает или снимает флаг свернутого режима виджета, функцию следует вызывать до функций отображения данных; -При нажатии на любой элемент интерфейса будет выполнен колбек `on_click(number)`, где number - это порядковый номер элемента. Например, если вы используете `ui:show_buttons` для показа трех кнопок, то при нажатии первой кнопки будет вызван `on_click` с аргументом 1, второй - с аргументов 2, и так далее. Если элемент на экране всего один - аргумент всегда будет равен единице и его можно будет опустить. +При нажатии на любой элемент интерфейса будет выполнен колбек `on_click(number)`, где number - это порядковый номер элемента. Долгое нажатие вызывает `on_long_click(number)`. Например, если вы используете `ui:show_buttons` для показа трех кнопок, то при нажатии первой кнопки будет вызван `on_click` с аргументом 1, второй - с аргументов 2, и так далее. Если элемент на экране всего один - аргумент всегда будет равен единице и его можно будет опустить. Функция `ui:show_chart()` в качестве третьего аргумента принимает строку, задающую форматирование значений x и y на экране. Например, строка `x:date y:number` означает, что значения по оси X необходимо отформатировать как даты, а значения по оси Y - как обычное число. Всего существует четыре формата: @@ -62,9 +62,7 @@ First line
Second line # Контекстное меню -* `ui:prepare_context_menu(table)` - функция подготавливает контекстное меню, которое будет автоматически показано при долгом удержании элемента на экране. - -В качестве аргумента функция принимает таблицу таблиц с иконками и названиями элементов меню. Например, следующий код подготовит контекстное меню из трех элементов: +* `ui:show_context_menu(table)` - функция показывает контекстное меню. В качестве аргумента функция принимает таблицу таблиц с иконками и названиями элементов меню. Например, следующий код подготовит контекстное меню из трех элементов: ``` ui:prepare_context_menu({ @@ -76,7 +74,7 @@ ui:prepare_context_menu({ Здесь `share`, `copy` и `trash` - это названия иконок, которое можно узнать на сайте [Fontawesome](https://fontawesome.com/). -При нажатии на любой элемент меню будет вызван колбек `on_context_menu_click(item_idx, menu_idx)`, первый аргумент которого это индекс элемента, для которого было вызвано меню, а второй - индекса элемента самого меню. +При нажатии на любой элемент меню будет вызван колбек `on_context_menu_click(item_idx)`, где `item\_idx` - это индекс элемента меню. # Системные функции @@ -89,6 +87,7 @@ ui:prepare_context_menu({ * `system:share_text(string)` - открывает системный диалог "Поделиться"; * `system:get_lang()` - возвращает выбранный в системе язык; * `system:get_tz_offset()` - возвращает time zone offset в секундах. +* `system:get_battery_info()` - возвращает таблицу с информацией о состоянии батареи. Результат выполнения shell-команды приходит в колбек `on_shell_result(string)`. @@ -132,7 +131,7 @@ ui:prepare_context_menu({ # Календарь -* `calendar:get_events([calendar_id])` - возвращает таблицу табдлиц событий всех календарей, опциональный аргумент - ID календаря; +* `calendar:get_events([start_date], [end_date], [cal_table])` - возвращает таблицу табдлиц событий всех календарей, start\_date - дата начала событий, end\_date - дата окончания событий, cal\_table - таблица идентификаторов календарей; * `calendar:get_calendars()` - возвращет таблицу таблиц календарей; * `calendar:open_event_dialog(id)` - открывает событие в системном календаре. @@ -204,7 +203,7 @@ end AIO Launcher включает в себя интерпретатор LuaJ 3.0.1 (совместимый с Lua 5.2) со стандартным набором модулей: `bit32`, `coroutine`, `math`, `os`, `string`, `table`. -Модули `io` и `package` в целях безопасности исключены из поставки, модуль `os` урезан в функциональности. Доступны только следующие функции: `os.clock()`, `os.date()`, `os.difftime()` и `os.time()`. +Модули `io` и `package` в целях безопасности исключены из поставки, модуль `os` урезан в функциональности. Доступны только следующие функции: `os.clock()`, `os.date()`, `os.difftime()` и `os.time()`. Стандартный API Lua расширен следующими функциями: diff --git a/samples/menu-sample.lua b/samples/menu-sample.lua index 32a0a3f..71ab158 100644 --- a/samples/menu-sample.lua +++ b/samples/menu-sample.lua @@ -1,18 +1,22 @@ function on_resume() - ui:show_lines({ - "1 item", "2 item", "3 item" - }) - - ui:prepare_context_menu({ - { "share", "Menu item 1" }, - { "copy", "Menu item 2" }, - { "trash", "Menu item 3" }, - { "share", "Menu item 4" }, - { "copy", "Menu item 5" }, - { "trash", "Menu item 6" }, + ui:show_lines({ + "1 item", "2 item", "3 item" }) end -function on_context_menu_click(item_idx, menu_idx) +function on_long_click(idx) + item_idx = idx + + ui:show_context_menu({ + { "share", "Menu item 1" }, + { "copy", "Menu item 2" }, + { "trash", "Menu item 3" }, + { "share", "Menu item 4" }, + { "copy", "Menu item 5" }, + { "trash", "Menu item 6" }, + }) +end + +function on_context_menu_click(menu_idx) ui:show_toast("Clicked "..menu_idx.." menu item on "..item_idx.." screen element") end