From fd5b0ffad39f79a5fddec55ce99fb0ba6aa8b8ca Mon Sep 17 00:00:00 2001 From: ezobnin Date: Sun, 15 Aug 2021 08:47:50 +0300 Subject: [PATCH 01/12] change http:post and http:get methods --- README_ru.md | 4 +-- main/updatimerobot-widget.lua | 53 +++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) create mode 100644 main/updatimerobot-widget.lua diff --git a/README_ru.md b/README_ru.md index c576ee8..8bcf899 100644 --- a/README_ru.md +++ b/README_ru.md @@ -100,8 +100,8 @@ ui:prepare_context_menu({ # Сетевые функции * `http:get(url, [id])` - выполняет запрос HTTP GET, id - строка-идентификатор запрос (см. ниже); -* `http:post(url, string, [id])` - выполняет запрос HTTP POST, второй аргумент - JSON-строка; -* `http:put(url, [id])` - выполняет запрос HTTP PUT; +* `http:post(url, body, media_type, [id])` - выполняет запрос HTTP POST; +* `http:put(url, body, media_type, [id])` - выполняет запрос HTTP; * `http:delete(url, [id])` - выполняет запрос HTTP DELETE. Эти функции не возвращают никакого значения, а вместо этого вызывают колбек `on_network_result(string, [code])`. Первый аргумент: тело ответа, второй (опциональный) - код (200, 404 и т.д.). diff --git a/main/updatimerobot-widget.lua b/main/updatimerobot-widget.lua new file mode 100644 index 0000000..b0071ac --- /dev/null +++ b/main/updatimerobot-widget.lua @@ -0,0 +1,53 @@ +-- name = "Uptimerobot" +-- description = "Shows uptime information from uptimerobot.com. Needs api key." +-- data_source = "https://uptimerobot.com" +-- type = "widget" +-- author = "Evgeny Zobnin (zobnin@gmail.com) +-- version = "1.0" +-- arguments_help = "Enter your API key" + +local json = require "json" +local md_colors = require "md_colors" + +-- constants +local api_url = "https://api.uptimerobot.com/v2/" +local media_type = "application/x-www-form-urlencoded" + +function on_alarm() + if (next(aio:get_args()) == nil) then + ui:show_text("Enter API key in the settings") + return + end + + local key = aio:get_args()[1] + local body = "api_key="..key.."&format=json" + + http:post(api_url.."getMonitors", body, media_type) +end + +function on_network_result(result) + local parsed = json.decode(result) + + if (parsed.stat ~= "ok") then + ui:show_text("Error: "..parsed.error.message) + return + end + + local strings_tab = {} + + for k,v in ipairs(parsed.monitors) do + strings_tab[k] = v.friendly_name..": "..format_status(v.status) + end + + ui:show_lines(strings_tab) +end + +-- utils + +function format_status(status) + local statuses = { "down", "up" } + local status_colors = { "red_500", "green_500" } + + return ""..statuses[status].."" +end + From eed6bebabe19e5afe4aadd58c2cabee216992f84 Mon Sep 17 00:00:00 2001 From: ezobnin Date: Sun, 15 Aug 2021 10:07:33 +0300 Subject: [PATCH 02/12] add aio:show_args_dialog function --- README_ru.md | 1 + main/updatimerobot-widget.lua | 13 +++++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/README_ru.md b/README_ru.md index 8bcf899..26a57f7 100644 --- a/README_ru.md +++ b/README_ru.md @@ -94,6 +94,7 @@ ui:prepare_context_menu({ * `aio:is_widget_added(string)` - проверяет, добавлен ли виджет на экран; * `aio:get_args()` - возвращает таблицу аргументов, которые пользователь указал нажав на иконку настроек в режиме редактирования виджета; * `aio:set_args(table)` - принудительно устанавливает аргументы скрипта (можно использовать для сохранения настроек скрипта - аргументы не стираются при отключении скрипта); +* `aio:show_args_dialog()` - показать диалог изменения аргументов; Если в метаданных виджета есть поле `arguments_help`, его значение будет выведено при редактировании аргументов виджета. Если есть поле `arguments_default` - оно будет использовано для получения дефолтовых аргументов. diff --git a/main/updatimerobot-widget.lua b/main/updatimerobot-widget.lua index b0071ac..18c8bdf 100644 --- a/main/updatimerobot-widget.lua +++ b/main/updatimerobot-widget.lua @@ -1,5 +1,5 @@ -- name = "Uptimerobot" --- description = "Shows uptime information from uptimerobot.com. Needs api key." +-- description = "Shows uptime information from uptimerobot.com. Needs API key." -- data_source = "https://uptimerobot.com" -- type = "widget" -- author = "Evgeny Zobnin (zobnin@gmail.com) @@ -11,11 +11,12 @@ local md_colors = require "md_colors" -- constants local api_url = "https://api.uptimerobot.com/v2/" +local click_url = "https://uptimerobot.com/dashboard#mainDashboard" local media_type = "application/x-www-form-urlencoded" function on_alarm() if (next(aio:get_args()) == nil) then - ui:show_text("Enter API key in the settings") + ui:show_text("Tap to enter API key") return end @@ -25,6 +26,14 @@ function on_alarm() http:post(api_url.."getMonitors", body, media_type) end +function on_click() + if (next(aio:get_args()) == nil) then + aio:show_args_dialog() + else + system:open_browser(click_url) + end +end + function on_network_result(result) local parsed = json.decode(result) From 839bcab019e9b7cf6e56595114f4179b21ffce00 Mon Sep 17 00:00:00 2001 From: ezobnin Date: Sun, 15 Aug 2021 10:17:04 +0300 Subject: [PATCH 03/12] small fix --- main/{updatimerobot-widget.lua => uptimerobot-widget.lua} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename main/{updatimerobot-widget.lua => uptimerobot-widget.lua} (100%) diff --git a/main/updatimerobot-widget.lua b/main/uptimerobot-widget.lua similarity index 100% rename from main/updatimerobot-widget.lua rename to main/uptimerobot-widget.lua From 8776e17f91a70aa524e12255d028d33b3ddacb4c Mon Sep 17 00:00:00 2001 From: ezobnin Date: Sun, 15 Aug 2021 10:20:54 +0300 Subject: [PATCH 04/12] small fix --- main/uptimerobot-widget.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/main/uptimerobot-widget.lua b/main/uptimerobot-widget.lua index 18c8bdf..b59f124 100644 --- a/main/uptimerobot-widget.lua +++ b/main/uptimerobot-widget.lua @@ -21,9 +21,9 @@ function on_alarm() end local key = aio:get_args()[1] - local body = "api_key="..key.."&format=json" + local body = "api_key="..key.."&format=json" - http:post(api_url.."getMonitors", body, media_type) + http:post(api_url.."getMonitors", body, media_type) end function on_click() @@ -35,7 +35,7 @@ function on_click() end function on_network_result(result) - local parsed = json.decode(result) + local parsed = json.decode(result) if (parsed.stat ~= "ok") then ui:show_text("Error: "..parsed.error.message) @@ -43,7 +43,7 @@ function on_network_result(result) end local strings_tab = {} - + for k,v in ipairs(parsed.monitors) do strings_tab[k] = v.friendly_name..": "..format_status(v.status) end From 4d03f1a79d42a9dd0fbcdb7a27211eb6ba9707dd Mon Sep 17 00:00:00 2001 From: ezobnin Date: Tue, 17 Aug 2021 15:42:36 +0300 Subject: [PATCH 05/12] add ui:show_table --- README_ru.md | 1 + main/uptimerobot-widget.lua | 16 +++++++++++++++- samples/table-sample.lua | 9 +++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 samples/table-sample.lua diff --git a/README_ru.md b/README_ru.md index 26a57f7..132f6a3 100644 --- a/README_ru.md +++ b/README_ru.md @@ -18,6 +18,7 @@ * `ui:show_text(string)` - выводит в виджет обычный текст; повторный вызов стирает предыдущий текст; * `ui:show_lines(table, [table])` - выводит список строк с отправителем (на манер почтового виджета), второй аргумент (необязательный) - соответствующие им отправители (форматирование в стиле почтового виджета); +* `ui:show_table(table, [centering])` - аналог `show_lines` для вывода строк в виде таблицы, первый аргумент - таблиц тбалиц, второй - булево значение, указывающее, нужно ли центрировать ячейки таблицы; * `ui:show_buttons(names, [colors])` - выводит список кнопок, первый аргумент - таблица строк, второй опциональный аргумент, таблица цветов в формате #XXXXXX; * `ui:show_progress_bar(text, current_value, max_value)` - показывает прогресс бар; * `ui:show_chart(points, [format], [title], [show_grid], [folded_string], [copyright])` - показывает график, points - таблица таблиц координат, format - формат данных (см. ниже), title - название графика, show\_grid - флага показа сетки, folded\_string - строка для свернутого состояния (иначе будет показано название), copyright - строка, отображаемая в правом нижнем углу; diff --git a/main/uptimerobot-widget.lua b/main/uptimerobot-widget.lua index b59f124..6ea850f 100644 --- a/main/uptimerobot-widget.lua +++ b/main/uptimerobot-widget.lua @@ -48,7 +48,7 @@ function on_network_result(result) strings_tab[k] = v.friendly_name..": "..format_status(v.status) end - ui:show_lines(strings_tab) + ui:show_table(table_to_tables(strings_tab, 2)) end -- utils @@ -60,3 +60,17 @@ function format_status(status) return ""..statuses[status].."" end +function table_to_tables(tab, num) + local out_tab = {} + local row = {} + + for k,v in ipairs(tab) do + table.insert(row, v) + if k % num == 0 then + table.insert(out_tab, row) + row = {} + end + end + + return out_tab +end diff --git a/samples/table-sample.lua b/samples/table-sample.lua new file mode 100644 index 0000000..6b50b54 --- /dev/null +++ b/samples/table-sample.lua @@ -0,0 +1,9 @@ +function on_resume() + local table = { + {"1", "2", "3"}, + {"4", "5", "6"}, + {"7", "8", "9"}, + } + + ui:show_table(table, true) +end From ddbf4a72e8f2bd868a44490a60f161d18cf008ee Mon Sep 17 00:00:00 2001 From: ezobnin Date: Tue, 17 Aug 2021 20:44:21 +0300 Subject: [PATCH 06/12] fixes --- README_ru.md | 2 +- main/uptimerobot-widget.lua | 17 +---------------- samples/table-sample.lua | 13 +++++++++---- 3 files changed, 11 insertions(+), 21 deletions(-) diff --git a/README_ru.md b/README_ru.md index 132f6a3..d470389 100644 --- a/README_ru.md +++ b/README_ru.md @@ -18,7 +18,7 @@ * `ui:show_text(string)` - выводит в виджет обычный текст; повторный вызов стирает предыдущий текст; * `ui:show_lines(table, [table])` - выводит список строк с отправителем (на манер почтового виджета), второй аргумент (необязательный) - соответствующие им отправители (форматирование в стиле почтового виджета); -* `ui:show_table(table, [centering])` - аналог `show_lines` для вывода строк в виде таблицы, первый аргумент - таблиц тбалиц, второй - булево значение, указывающее, нужно ли центрировать ячейки таблицы; +* `ui:show_table(table, [centering])` - аналог `show_lines` для вывода строк в виде таблицы, первый аргумент - таблица значений, второй - количество столбцов в таблице, третий - булево значение, указывающее, нужно ли центрировать ячейки таблицы; * `ui:show_buttons(names, [colors])` - выводит список кнопок, первый аргумент - таблица строк, второй опциональный аргумент, таблица цветов в формате #XXXXXX; * `ui:show_progress_bar(text, current_value, max_value)` - показывает прогресс бар; * `ui:show_chart(points, [format], [title], [show_grid], [folded_string], [copyright])` - показывает график, points - таблица таблиц координат, format - формат данных (см. ниже), title - название графика, show\_grid - флага показа сетки, folded\_string - строка для свернутого состояния (иначе будет показано название), copyright - строка, отображаемая в правом нижнем углу; diff --git a/main/uptimerobot-widget.lua b/main/uptimerobot-widget.lua index 6ea850f..ade55ed 100644 --- a/main/uptimerobot-widget.lua +++ b/main/uptimerobot-widget.lua @@ -48,7 +48,7 @@ function on_network_result(result) strings_tab[k] = v.friendly_name..": "..format_status(v.status) end - ui:show_table(table_to_tables(strings_tab, 2)) + ui:show_table(strings_tab, 2) end -- utils @@ -59,18 +59,3 @@ function format_status(status) return ""..statuses[status].."" end - -function table_to_tables(tab, num) - local out_tab = {} - local row = {} - - for k,v in ipairs(tab) do - table.insert(row, v) - if k % num == 0 then - table.insert(out_tab, row) - row = {} - end - end - - return out_tab -end diff --git a/samples/table-sample.lua b/samples/table-sample.lua index 6b50b54..9db099d 100644 --- a/samples/table-sample.lua +++ b/samples/table-sample.lua @@ -1,9 +1,14 @@ function on_resume() local table = { - {"1", "2", "3"}, - {"4", "5", "6"}, - {"7", "8", "9"}, + "1", "20", "30", + "40", "5", "66", + "07", "28", "9", } - ui:show_table(table, true) + ui:show_table(table, 3, true) end + +function on_click(idx) + ui:show_toast("Cell: "..idx) +end + From 04d68bf9007c5cbc18da2b08a9cc495f6ca2f373 Mon Sep 17 00:00:00 2001 From: ezobnin Date: Wed, 18 Aug 2021 08:26:57 +0300 Subject: [PATCH 07/12] remove clipboard widget from main widgets --- {main => samples}/clipboard-widget.lua | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {main => samples}/clipboard-widget.lua (100%) diff --git a/main/clipboard-widget.lua b/samples/clipboard-widget.lua similarity index 100% rename from main/clipboard-widget.lua rename to samples/clipboard-widget.lua From 513f6f7b17c911dd42d16d6154931f28bb01ef1e Mon Sep 17 00:00:00 2001 From: Evgeny Date: Wed, 18 Aug 2021 14:16:06 +0300 Subject: [PATCH 08/12] ui:show_table fixes --- README_ru.md | 2 +- samples/table-sample.lua | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README_ru.md b/README_ru.md index d470389..85a9b2d 100644 --- a/README_ru.md +++ b/README_ru.md @@ -18,7 +18,7 @@ * `ui:show_text(string)` - выводит в виджет обычный текст; повторный вызов стирает предыдущий текст; * `ui:show_lines(table, [table])` - выводит список строк с отправителем (на манер почтового виджета), второй аргумент (необязательный) - соответствующие им отправители (форматирование в стиле почтового виджета); -* `ui:show_table(table, [centering])` - аналог `show_lines` для вывода строк в виде таблицы, первый аргумент - таблица значений, второй - количество столбцов в таблице, третий - булево значение, указывающее, нужно ли центрировать ячейки таблицы; +* `ui:show_table(table, column_count, [centering], [folded_string])` - аналог `show_lines` для вывода строк в виде таблицы, первый аргумент - таблица значений, второй - количество столбцов в таблице, третий - булево значение, указывающее, нужно ли центрировать ячейки таблицы, четвертый - строка, которая будет показана в свернутом режиме; * `ui:show_buttons(names, [colors])` - выводит список кнопок, первый аргумент - таблица строк, второй опциональный аргумент, таблица цветов в формате #XXXXXX; * `ui:show_progress_bar(text, current_value, max_value)` - показывает прогресс бар; * `ui:show_chart(points, [format], [title], [show_grid], [folded_string], [copyright])` - показывает график, points - таблица таблиц координат, format - формат данных (см. ниже), title - название графика, show\_grid - флага показа сетки, folded\_string - строка для свернутого состояния (иначе будет показано название), copyright - строка, отображаемая в правом нижнем углу; diff --git a/samples/table-sample.lua b/samples/table-sample.lua index 9db099d..f4a92af 100644 --- a/samples/table-sample.lua +++ b/samples/table-sample.lua @@ -5,7 +5,7 @@ function on_resume() "07", "28", "9", } - ui:show_table(table, 3, true) + ui:show_table(table, 3, true, "Nothing there") end function on_click(idx) From ece4b3ecdc518fba170dbd2e5d3ee04c12c61977 Mon Sep 17 00:00:00 2001 From: Evgeny Date: Wed, 18 Aug 2021 20:12:46 +0300 Subject: [PATCH 09/12] add english readme --- README.md | 195 +++++++++++++++++++++++++++++++++++++++++++++++++++ README_ru.md | 6 +- 2 files changed, 198 insertions(+), 3 deletions(-) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..12cc5e7 --- /dev/null +++ b/README.md @@ -0,0 +1,195 @@ +# Introduction + +Starting from version 4.0, AIO Launcher supports scripts, or rather special widgets written in the [Lua scripting language ](https://en.wikipedia.org/wiki/Lua_(programming_language)). Such widgets should be placed in the directory `/sdcard/ Android/data/ru.execbit.aiolauncher/files/`. They can then be added to the screen using the "Scripts" section of the settings or using the side menu. + +The possibilities of scripts are limited, but they can be used to expand the functionality of the application almost limitlessly (see examples in this repository). + +# Functions (callbacks) of the life cycle + +The work of any script begins with one of the three described functions. Main work should be done in one of them. + +* `on_resume()` - called every time you return to the desktop; +* `on_alarm()` - called when returning to the desktop, provided that more than 30 minutes have passed since the last call; +* `on_tick()` - called every second while the launcher is on the screen. + +For most network scripts `on_alarm()` should be used. + +# Data display functions + +* `ui:show_text(string)` - displays plain text in the widget; repeated call erases the previous text; +* `ui:show_lines(table, [table])` - displays a list of lines with the sender (in the manner of a mail widget), the second argument (optional) - the corresponding senders (formatting in the style of a mail widget); +* `ui:show_table(table, column_count, [centering], [folded_string])` - analogue of `show_lines` for displaying rows as a table, the first argument is a table of values, the second is the number of columns in the table, the third is a boolean value indicating whether it is necessary to center the table cells, the fourth is the row that will be shown in collapsed mode; +* `ui:show_buttons(names, [colors])` - displays a list of buttons, the first argument is a table of strings, the second is an optional argument, a table of colors in the format #XXXXXX; +* `ui:show_progress_bar(text, current_value, max_value)` - shows the progress bar; +* `ui:show_chart(points, [format], [title], [show_grid], [folded_string], [copyright])` - shows the chart, points - table of coordinate tables, format - data format (see below), title - chart name, show\_grid - grid display flag, folded\_string - string for the folded state (otherwise the name will be shown), copyright - string displayed in the lower right corner; +* `ui:show_toast(string)` - shows informational message in Android style; +* `ui:get_default_title()` - returns the standard widget title (set in the `name` metadata); +* `ui:set_title()` - changes the title of the widget, should be called before the data display function (empty line - reset to the standard title); +* `ui:get_primary_text_color()` - returns the color of the theme text in #XXXXXX format; +* `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. + +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: + +* `number` - an ordinary number with group separation; +* `float` - the same, but with two decimal places; +* `date` - date in day.month format; +* `time` - time in hours: minutes format. + +The functions `ui:show_text()` and `ui:show_lines()` support many HTML tags. For example: + +``` +First line
Second line + Bold Line
Oblique Line + Red text + Text on green background +``` + +# Dialogues + +* `ui:show_dialog(title, text, [button1_text], [button2_text])` - show dialog, the first argument is the title, the second is the text, button1\_text is the name of the first button, button2\_text is the name of the second button; +* `ui:show_edit_dialog(title, [text], [default_value])` - show the dialog with the input field: title - title, text - signature, default\_value - standard value of the input field; +* `ui:show_checkbox_dialog (title, lines, [index])` - show a dialog with a choice: title - title, lines - table of lines, index - index of the default value; + +Dialog button clicks should be processed in the `on_dialog_action(number)` callback, where 1 is the first button, 2 is the second, and -1 is the "closed" button if no buttons were specified. `ui:show_edit_dialog()` returns the text in the `on_dialog_action(text)` callback. + +# 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: prepare_context_menu ({ + {"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/). + +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. + +# System functions + +* `system:open_app(package_name)` - opens the application by package name; +* `system:open_browser(url)` - opens the specified URL in a browser or application that can handle this type of URL; +* `system:exec(string)` - executes a shell command; +* `system:su(string)` - executes a shell command as root; +* `system:get_location()` - returns the location in the table with two values (location request is NOT executed, the value previously saved by the system is used); +* `system:copy_to_clipboard(string)` - copies the string to the clipboard; +* `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; + +The result of executing a shell command is sent to the `on_shell_result(string)` callback. + +# Launcher control functions + +* `aio:do_action(string)` - performs an AIO action ([more](https://aiolauncher.app/api.html)); +* `aio:add_widget(string)` - adds an embedded widget, script widget or clone of an existing widget to the screen; +* `aio:remove_widget(string)` - removes the built-in widget or script widget from the screen (note: additional widgets will also be removed); +* `aio:is_widget_added(string)` - checks if the widget is added to the screen; +* `aio:get_args()` - returns a table of arguments that the user specified by clicking on the settings icon in the widget editing mode; +* `aio:set_args(table)` - forcibly sets script arguments (can be used to save script settings - arguments are not erased when the script is disabled); +* `aio:show_args_dialog()` - show the dialog for changing arguments; + +If there is a `arguments_help` field in the widget's metadata, its value will be displayed when editing the widget's arguments. If there is a `arguments_default` field, it will be used to get the default arguments. + +# Network functions + +* `http:get(url, [id])` - executes an HTTP GET request, id - the request identifier string (see below); +* `http:post(url, body, media_type, [id])` - executes an HTTP POST request; +* `http:put(url, body, media_type, [id])` - executes an HTTP request; +* `http:delete(url, [id])` - executes an HTTP DELETE request. + +These functions do not return any value, but instead call the `on_network_result (string, [code])` callback. The first argument is the body of the response, the second (optional) is the code (200, 404, etc.). + +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])`. + +# Data processing functions + +* `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. + +Unlike classic JSON parsers, this function is not intended for parsing, but for retrieving single values. For example, there is the following JSON: + +``` +{ + "type": "success", + "value": { + "id": 344, + "joke": "Aliens DO indeed exist. They just know better than to visit a planet that Chuck Norris is on.", + "categories": [] + } +} +``` + +We need to extract string "joke" from it. From the JSON text, you can see that this string is contained within the "value" object, and this object itself is inside the main JSON object. In other words, to retrieve the required string, we need to "open" the main JSON object, then "open" the "value" object and find the string "joke" in it. In code, it will look like this: + +``` +joke = ajson:get_value(result, "object object:value string:joke") +``` + +The full text of the script may look like this: + +``` +function on_alarm() + net:get_text("http://api.icndb.com/jokes/random") +end + +function on_network_result(result) + local joke = ajson:get_value(result, "object object:value string:joke") + aio:show_text(joke) +end +``` + +Please note that the last element of the line should always be an instruction for extracting primitive data types: + +* `string:name` +* `int:name` +* `double:name` +* `boolean:name` + +Also, instead of `object`, you can use `array` if the JSON contains an array. + +To summarize: ajson works well (and very fast) when you need to retrieve one or two values. If you need to get a large amount of data (or all data) from JSON, then it is better to use the json.lua library (see below). It turns JSON into a set of easy-to-use nested Lua tables. + +# Other functions + +AIO Launcher includes the LuaJ 3.0.1 interpreter (compatible with Lua 5.2) with a standard set of modules: `bit32`, `coroutine`, `math`, `os`, `string`,` table`. + +The modules `io` and` package` are excluded from the distribution for security reasons, the module `os` has been cut in functionality. Only the following functions are available: `os.clock()`, `os.date()`, `os.difftime()` and `os.time()`. + +The standard Lua API is extended with the following features: + +* `string:split(delimeter)` - splits the string using the specified delimiter and returns a table; +* `string:replace(regexp, string)` - replaces the text found by the regular expression with another text; +* `get_index(table, value)` - returns the index of the table element; +* `get_key(table, value)` - returns the key of the table element; +* `round(x, n)` - rounds the number; + +The kit also includes: + +* `md_colors` - Material Design color table module (source is in this repository, [help] (https://materialui.co/colors)); +* `url` - a module with functions for encoding / decoding a string in a URL from the Lua Penlight library; +* [luaDate] (https://github.com/Tieske/date) - functions for working with time; +* [json.lua] (https://github.com/rxi/json.lua) - JSON parser; +* [SLAXDOM] (https://github.com/Phrogz/SLAXML) - XML parser. + +# Metadata + +In order for AIO Launcher to correctly display information about the script in the script directory and correctly display the title, you must add metadata to the beginning of the script. For example: + +``` +- name = "Covid info" +- description = "Cases of illness and death from covid" +- data_source = "https://covid19api.com" +- arguments_help = "Specify the country code" +- arguments_default = "RU" +- type = "widget" +- author = "Evgeny Zobnin (zobnin@gmail.com)" +- version = "1.0" +``` diff --git a/README_ru.md b/README_ru.md index 85a9b2d..32539c7 100644 --- a/README_ru.md +++ b/README_ru.md @@ -71,12 +71,12 @@ ui:prepare_context_menu({ Здесь `share`, `copy` и `trash` - это названия иконок, которое можно узнать на сайте [Fontawesome](https://fontawesome.com/). -При нажатии на любой элемент меню будет вызван колбек `function on_context_menu_click(item_idx, menu_idx)`, первый аргумент которого это индекс элемента, для которого было вызвано меню, а второй - индекса элемента самого меню. +При нажатии на любой элемент меню будет вызван колбек `on_context_menu_click(item_idx, menu_idx)`, первый аргумент которого это индекс элемента, для которого было вызвано меню, а второй - индекса элемента самого меню. # Системные функции -* `system:open_app(string)` - открывает приложение, имя пакета которого указано в аргументе; -* `system:open_browser(string)` - открывает указанный URL в браузере или в приложении, умеющем обрабатывать данный тип URL; +* `system:open_app(package)` - открывает приложение, имя пакета которого указано в аргументе; +* `system:open_browser(url)` - открывает указанный URL в браузере или в приложении, умеющем обрабатывать данный тип URL; * `system:exec(string)` - выполняет shell-команду; * `system:su(string)` - выполняет shell-команду от имени root; * `system:get_location()` - возвращает местоположение в таблице с двумя значениями (запрос местоположения НЕ выполняется, используется значение, сохраненное системой ранее); From 9cd1f8969885b8cc31ee5912042679ee484d0b70 Mon Sep 17 00:00:00 2001 From: Evgeny Date: Wed, 18 Aug 2021 20:17:39 +0300 Subject: [PATCH 10/12] add english readme (fix) --- README.md | 18 +++++++++--------- README_ru.md | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 12cc5e7..f695fc0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Introduction -Starting from version 4.0, AIO Launcher supports scripts, or rather special widgets written in the [Lua scripting language ](https://en.wikipedia.org/wiki/Lua_(programming_language)). Such widgets should be placed in the directory `/sdcard/ Android/data/ru.execbit.aiolauncher/files/`. They can then be added to the screen using the "Scripts" section of the settings or using the side menu. +Starting from version 4.0, AIO Launcher supports scripts, or rather special widgets written in the [Lua scripting language ](https://en.wikipedia.org/wiki/Lua_(programming_language)). Such widgets should be placed in the directory `/sdcard/Android/data/ru.execbit.aiolauncher/files/`. They can then be added to the screen using the "Scripts" section of the settings or using the side menu. The possibilities of scripts are limited, but they can be used to expand the functionality of the application almost limitlessly (see examples in this repository). @@ -41,10 +41,10 @@ The `ui:show_chart()` function takes a string as its third argument to format th The functions `ui:show_text()` and `ui:show_lines()` support many HTML tags. For example: ``` -First line
Second line - Bold Line
Oblique Line - Red text - Text on green background +First line
Second line +Bold Line
Oblique Line +Red text +Text on green background ``` # Dialogues @@ -161,7 +161,7 @@ To summarize: ajson works well (and very fast) when you need to retrieve one or AIO Launcher includes the LuaJ 3.0.1 interpreter (compatible with Lua 5.2) with a standard set of modules: `bit32`, `coroutine`, `math`, `os`, `string`,` table`. -The modules `io` and` package` are excluded from the distribution for security reasons, the module `os` has been cut in functionality. Only the following functions are available: `os.clock()`, `os.date()`, `os.difftime()` and `os.time()`. +The modules `io` and `package` are excluded from the distribution for security reasons, the module `os` has been cut in functionality. Only the following functions are available: `os.clock()`, `os.date()`, `os.difftime()` and `os.time()`. The standard Lua API is extended with the following features: @@ -175,9 +175,9 @@ The kit also includes: * `md_colors` - Material Design color table module (source is in this repository, [help] (https://materialui.co/colors)); * `url` - a module with functions for encoding / decoding a string in a URL from the Lua Penlight library; -* [luaDate] (https://github.com/Tieske/date) - functions for working with time; -* [json.lua] (https://github.com/rxi/json.lua) - JSON parser; -* [SLAXDOM] (https://github.com/Phrogz/SLAXML) - XML parser. +* [luaDate](https://github.com/Tieske/date) - functions for working with time; +* [json.lua](https://github.com/rxi/json.lua) - JSON parser; +* [SLAXDOM](https://github.com/Phrogz/SLAXML) - XML parser. # Metadata diff --git a/README_ru.md b/README_ru.md index 32539c7..dc52f07 100644 --- a/README_ru.md +++ b/README_ru.md @@ -75,7 +75,7 @@ ui:prepare_context_menu({ # Системные функции -* `system:open_app(package)` - открывает приложение, имя пакета которого указано в аргументе; +* `system:open_app(package_name)` - открывает приложение, имя пакета которого указано в аргументе; * `system:open_browser(url)` - открывает указанный URL в браузере или в приложении, умеющем обрабатывать данный тип URL; * `system:exec(string)` - выполняет shell-команду; * `system:su(string)` - выполняет shell-команду от имени root; From 5a7717d4d8517aedf1ef823348e7294c62c04be6 Mon Sep 17 00:00:00 2001 From: Evgeny Date: Wed, 18 Aug 2021 20:18:32 +0300 Subject: [PATCH 11/12] add english readme (fix) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f695fc0..96e2c91 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,7 @@ The standard Lua API is extended with the following features: The kit also includes: -* `md_colors` - Material Design color table module (source is in this repository, [help] (https://materialui.co/colors)); +* `md_colors` - Material Design color table module (source is in this repository, [help](https://materialui.co/colors)); * `url` - a module with functions for encoding / decoding a string in a URL from the Lua Penlight library; * [luaDate](https://github.com/Tieske/date) - functions for working with time; * [json.lua](https://github.com/rxi/json.lua) - JSON parser; From 27b3cf6aaee1cba0ade7378f8dd0fbed1fba919b Mon Sep 17 00:00:00 2001 From: Evgeny Date: Thu, 19 Aug 2021 08:24:18 +0300 Subject: [PATCH 12/12] add subtitiles to dialogs --- README.md | 2 + README_ru.md | 2 + main/shell-widget.lua | 2 +- ru/calendar-ru-widget.lua | 170 ++++++++++++++++++++++++++++++++++++++ samples/dialog_sample.lua | 2 +- 5 files changed, 176 insertions(+), 2 deletions(-) create mode 100644 ru/calendar-ru-widget.lua diff --git a/README.md b/README.md index 96e2c91..0c97759 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,8 @@ First line
Second line Dialog button clicks should be processed in the `on_dialog_action(number)` callback, where 1 is the first button, 2 is the second, and -1 is the "closed" button if no buttons were specified. `ui:show_edit_dialog()` returns the text in the `on_dialog_action(text)` callback. +If the first argument of the dialog contains two lines separated by `\n`, the second line becomes a subheading. + # 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. diff --git a/README_ru.md b/README_ru.md index dc52f07..e7c2a9f 100644 --- a/README_ru.md +++ b/README_ru.md @@ -55,6 +55,8 @@ First line
Second line Нажатия на кнопки диалога должны обрабатываться в колбеке `on_dialog_action(number)`, где 1 - это первая кнопка, 2 - вторая, а -1 - нажатие кнопки "закрыть", если никакие кнопки не были указаны. `ui:show_edit_dialog()` возвращает текст в колбек `on_dialog_action(text)`. +Если первый аргумент диалога содержит две строки, разделенных знаком `\n`, вторая строка станет подзаголовком. + # Контекстное меню * `ui:prepare_context_menu(table)` - функция подготавливает контекстное меню, которое будет автоматически показано при долгом удержании элемента на экране. diff --git a/main/shell-widget.lua b/main/shell-widget.lua index d4cd858..e71c5c3 100644 --- a/main/shell-widget.lua +++ b/main/shell-widget.lua @@ -15,7 +15,7 @@ function redraw() end function on_click(idx) - ui:show_edit_dialog("Enter command") + ui:show_edit_dialog("Enter command\nAAAA") end function on_dialog_action(text) diff --git a/ru/calendar-ru-widget.lua b/ru/calendar-ru-widget.lua new file mode 100644 index 0000000..4d58802 --- /dev/null +++ b/ru/calendar-ru-widget.lua @@ -0,0 +1,170 @@ +-- name = "Календарь" +-- description = "Производственный календарь" +-- data_source = "https://isdayoff.ru/" +-- type = "widget" +-- author = "Andrey Gavrilov" +-- version = "1.0" + +local color = require "md_colors" + +local days = {} +local tab = {} + +local pr_text_color = ui:get_primary_text_color() +local sec_text_color = ui:get_secondary_text_color() +local year = os.date("*t").year +local month = os.date("*t").month + +function on_alarm() + is_days_off(year,month) +end + +function is_days_off(y,m) + http:get("https://isdayoff.ru/api/getdata?year="..y.."&month="..m.."&pre=1&delimeter=-&covid=1") +end + +function on_network_result(result) + days = result:split("-") + tab = get_cal(year,month) + ui:show_table(tab,8, true) + ui:set_title(ui:get_default_title().." ("..string.format("%02d.%04d",month,year)..")") +end + +function on_click(i) + if i == 1 then + local time = get_time(begin_month(year,month))-24*60*60 + local y,m,d = get_day(time) + year = y + month = m + elseif i == 8 then + local time = get_time(end_month(year,month))+24*60*60 + local y,m,d = get_day(time) + year = y + month = m + elseif i > 1 and i < 8 then + ui:show_edit_dialog("Введите месяц и год", "Формат - 12.2020. Пустое значение - текущий месяц", string.format("%02d.%04d", month, year)) + elseif (i-1)%8 ~= 0 and tab[i] ~= " " then + ui:show_toast(os.date("*t", get_time(year,month,tab[i]:match(">(%d+)<"))).yday) + return + else + return + end + is_days_off(year,month) +end + +function on_dialog_action(data) + if data == -1 then + return + elseif data == "" then + local date = os.date("*t") + if year == date.year and month == date.month then + return + end + year = date.year + month = date.month + is_days_off(year,month) + return + elseif not check_date(data) then + return + else + local m,y = data:match("(%d+)%.(%d+)") + if year == tonumber(y) and month == tonumber(m) then + return + end + end + local m,y = data:match("(%d+)%.(%d+)") + year = tonumber(y) + month = tonumber(m) + is_days_off(year,month) +end + +function get_cal(y,m) + local from = get_time(begin_month(y,m)) + local tab = { + "< #", + "Пн", + "Вт", + "Ср", + "Чт", + "Пт", + "Сб", + "Вс >" + } + table.insert(tab,""..weeknumber(get_day(from)).."") + for i =1, weekday(get_day(from))-1,1 do + table.insert(tab," ") + end + local to = get_time(end_month(y,m)) + local k=0 + for time = from,to,24*60*60 do + k=k+1 + local y,m,d = get_day(time) + table.insert(tab, format_day(d,k)) + if weekday(get_day(time))==7 and time ~= to then + table.insert(tab, ""..weeknumber(get_day(time+24*60*60)).."") + end + end + for i = weekday(get_day(to))+1,7,1 do + table.insert(tab," ") + end + return tab +end + +function weeknumber(y,m,d) + local yday = os.date("*t",os.time{day=d,month=m,year=y}).yday + local wday = weekday(y,m,1) + return math.floor((yday+10-wday)/7) +end + +function weekday(y,m,d) + local wday = os.date("*t",os.time{day=d,month=m,year=y}).wday-1 + if wday == 0 then wday = 7 end + return wday +end + +function begin_month(y,m) + local time = os.time{day=1,month=m,year=y} + local date = os.date("*t",time) + return date.year,date.month,date.day +end + +function end_month(y,m) + local time = os.time{day=1,month=m,year=y}+31*24*60*60 + local date = os.date("*t",time) + local time = os.time{day=1,month=date.month,year=date.year}-24*60*60 + local date = os.date("*t",time) + return date.year,date.month,date.day +end + +function get_day(t) + local date = os.date("*t",t) + return date.year,date.month,date.day +end + +function get_time(y,m,d) + return os.time{day=d,month=m,year=y} +end + +function format_day(d,k) + local day = d + if days[k] == "2" then + day = ""..day.."" + elseif days[k] == "1" then + day = ""..day.."" + elseif days[k] == "4" then + day = ""..day.."" + else + day = ""..day.."" + end + if year == os.date("*t").year and month == os.date("*t").month and d == os.date("*t").day then + day = ""..day.."" + end + return day + end + +function check_date(date) + local m, Y = date:match("(%d+).(%d+)") + local time = os.time{day=1, month=m or 0, year=Y or 0} + local str = string.format("%02d.%04d", m or 0, Y or 0) + return str == os.date("%m.%Y", time) +end diff --git a/samples/dialog_sample.lua b/samples/dialog_sample.lua index 944b724..5f51ce9 100644 --- a/samples/dialog_sample.lua +++ b/samples/dialog_sample.lua @@ -8,7 +8,7 @@ end function on_click(idx) if idx == 1 then - ui:show_dialog("Dialog title", "This is dialog") + ui:show_dialog("Dialog title\nSubtitle", "This is dialog") elseif idx == 2 then ui:show_dialog("Dialog title", "This is dialog", "Button 1", "Button 2") elseif idx == 3 then