diff --git a/README.md b/README.md new file mode 100644 index 0000000..0c97759 --- /dev/null +++ b/README.md @@ -0,0 +1,197 @@ +# 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. + +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. + +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 c576ee8..e7c2a9f 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, 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 - строка, отображаемая в правом нижнем углу; @@ -54,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)` - функция подготавливает контекстное меню, которое будет автоматически показано при долгом удержании элемента на экране. @@ -70,12 +73,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_name)` - открывает приложение, имя пакета которого указано в аргументе; +* `system:open_browser(url)` - открывает указанный URL в браузере или в приложении, умеющем обрабатывать данный тип URL; * `system:exec(string)` - выполняет shell-команду; * `system:su(string)` - выполняет shell-команду от имени root; * `system:get_location()` - возвращает местоположение в таблице с двумя значениями (запрос местоположения НЕ выполняется, используется значение, сохраненное системой ранее); @@ -94,14 +97,15 @@ ui:prepare_context_menu({ * `aio:is_widget_added(string)` - проверяет, добавлен ли виджет на экран; * `aio:get_args()` - возвращает таблицу аргументов, которые пользователь указал нажав на иконку настроек в режиме редактирования виджета; * `aio:set_args(table)` - принудительно устанавливает аргументы скрипта (можно использовать для сохранения настроек скрипта - аргументы не стираются при отключении скрипта); +* `aio:show_args_dialog()` - показать диалог изменения аргументов; Если в метаданных виджета есть поле `arguments_help`, его значение будет выведено при редактировании аргументов виджета. Если есть поле `arguments_default` - оно будет использовано для получения дефолтовых аргументов. # Сетевые функции * `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/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/main/uptimerobot-widget.lua b/main/uptimerobot-widget.lua new file mode 100644 index 0000000..ade55ed --- /dev/null +++ b/main/uptimerobot-widget.lua @@ -0,0 +1,61 @@ +-- 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 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("Tap to enter API key") + 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_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) + + 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_table(strings_tab, 2) +end + +-- utils + +function format_status(status) + local statuses = { "down", "up" } + local status_colors = { "red_500", "green_500" } + + return ""..statuses[status].."" +end 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/main/clipboard-widget.lua b/samples/clipboard-widget.lua similarity index 100% rename from main/clipboard-widget.lua rename to samples/clipboard-widget.lua 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 diff --git a/samples/table-sample.lua b/samples/table-sample.lua new file mode 100644 index 0000000..f4a92af --- /dev/null +++ b/samples/table-sample.lua @@ -0,0 +1,14 @@ +function on_resume() + local table = { + "1", "20", "30", + "40", "5", "66", + "07", "28", "9", + } + + ui:show_table(table, 3, true, "Nothing there") +end + +function on_click(idx) + ui:show_toast("Cell: "..idx) +end +