add settings API

This commit is contained in:
Evgeny
2021-08-31 19:43:38 +03:00
parent 7d03496bfc
commit 74d101c673
11 changed files with 92 additions and 72 deletions

View File

@@ -97,11 +97,6 @@ The result of executing a shell command is sent to the `on_shell_result(string)`
* `aio:add_widget(string)` - adds an embedded widget, script widget or clone of an existing widget to the screen; * `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: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: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.
# Application management # Application management
@@ -152,6 +147,18 @@ Calendar table format:
* `name` - name of the calendar; * `name` - name of the calendar;
* `color` - color of the calendar in the format #XXXXXXXX. * `color` - color of the calendar in the format #XXXXXXXX.
# Settings
* `settings:get()` - returns the settings table in an array of words format;
* `settings:set(table)` - saves the settings table in an array of words format;
* `settings:get_kv()` - returns the settings table in `key=value` format;
* `settings:set_kv(table)` - saves settings table in the format `key=value`;
* `settings:show_dialog()` - show settings change dialog.
User can change settings through the dialog, which is available by clicking on the "gear" in the edit menu of the widget. If in the widget metadata there is a field `arguments_help`, its value will be shown in the edit dialog. If there is a field `arguments_default` - it will be used to get default arguments.
The standard edit dialog can be replaced by your own if you implement the `on_settings()` function.
# Data processing # 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. * `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.

View File

@@ -91,19 +91,14 @@ ui:show_context_menu({
Результат выполнения shell-команды приходит в колбек `on_shell_result(string)`. Результат выполнения shell-команды приходит в колбек `on_shell_result(string)`.
# Функции управления лаунчером # Управление лаунчером
* `aio:do_action(string)` - выполняет действие AIO ([подробнее](https://aiolauncher.app/api.html)); * `aio:do_action(string)` - выполняет действие AIO ([подробнее](https://aiolauncher.app/api.html));
* `aio:add_widget(string)` - добавляет на экран встроенный виджет, виджет-скрипт или клон существующего виджета; * `aio:add_widget(string)` - добавляет на экран встроенный виджет, виджет-скрипт или клон существующего виджета;
* `aio:remove_widget(string)` - удаляет с экрана встроенный виджет или виджет-скрипт (внимание: доп. виджеты тоже будут удалены); * `aio:remove_widget(string)` - удаляет с экрана встроенный виджет или виджет-скрипт (внимание: доп. виджеты тоже будут удалены);
* `aio:is_widget_added(string)` - проверяет, добавлен ли виджет на экран; * `aio:is_widget_added(string)` - проверяет, добавлен ли виджет на экран;
* `aio:get_args()` - возвращает таблицу аргументов, которые пользователь указал нажав на иконку настроек в режиме редактирования виджета;
* `aio:set_args(table)` - принудительно устанавливает аргументы скрипта (можно использовать для сохранения настроек скрипта - аргументы не стираются при отключении скрипта);
* `aio:show_args_dialog()` - показать диалог изменения аргументов;
Если в метаданных виджета есть поле `arguments_help`, его значение будет выведено при редактировании аргументов виджета. Если есть поле `arguments_default` - оно будет использовано для получения дефолтовых аргументов. # Управление приложениями
# Функции управления приложениями
* `apps:get_list([sort_by], [no_hidden])` - возвращает таблицу пакетов всех установленных приложений, `sort_by` - вариант сортировки (см. ниже), `no_hidden` - true, если скрытые приложения не нужны; * `apps:get_list([sort_by], [no_hidden])` - возвращает таблицу пакетов всех установленных приложений, `sort_by` - вариант сортировки (см. ниже), `no_hidden` - true, если скрытые приложения не нужны;
* `apps:get_name(package)` - возвращает имя приложения; * `apps:get_name(package)` - возвращает имя приложения;
@@ -152,6 +147,18 @@ ui:show_context_menu({
* `name` - название календаря; * `name` - название календаря;
* `color` - цвет календаря в фолрмате #XXXXXX. * `color` - цвет календаря в фолрмате #XXXXXX.
# Настройки
* `settings:get()` - возвращает таблицу настроек в формате массива слов;
* `settings:set(table)` - сохраняет таблицу настроек в форме массива слов;
* `settings:get_kv()` - возвращает таблицу настроек в формате `ключ=значение`;
* `settings:set_kv(table)` - сохраняет таблицу настроек в формате `ключ=значение`;
* `settings:show_dialog()` - показать диалог изменения настроек.
Пользователь может изменять настройки через диалог, доступный по нажатию на "шестеренку" в меню редактирования виджета. Если в метаданных виджета есть поле `arguments_help`, его значение будет выведено в диалоге редактирования. Если есть поле `arguments_default` - оно будет использовано для получения дефолтовых аргументов.
Стандартный диалог редактирования можно заменить на свой если реализовать функцию `on_settings()`.
# Функции обработки данных # Функции обработки данных
* `ajson:get_value(string, string)` - получает указанное значение из JSON; первый аргумент - JSON-строка, второй - инструкция для получения значения. * `ajson:get_value(string, string)` - получает указанное значение из JSON; первый аргумент - JSON-строка, второй - инструкция для получения значения.

View File

@@ -1,7 +1,7 @@
-- name = "Network file" -- name = "Network file"
function on_resume() function on_resume()
local args = aio:get_args() local args = settings:get()
if next(args) == nil then if next(args) == nil then
ui:show_text("Tap to enter text file URL") ui:show_text("Tap to enter text file URL")

View File

@@ -1,34 +1,34 @@
-- name = "Period progress" -- name = "Period progress"
-- description = "Shows period progress" -- description = "Shows period progress"
-- type = "widget" -- type = "widget"
-- author = "Nikolai Galashev" -- author = "Nikolai Galashev"
-- version = "1.0" -- version = "1.0"
-- arguments_help = "Enter the title and the start and end date in this format: Title 2021 01 31 2021 09 25" -- arguments_help = "Enter the title and the start and end date in this format: Title 2021 01 31 2021 09 25"
function on_resume() function on_resume()
if (next(aio:get_args()) == nil) then if (next(settings:get()) == nil) then
ui:show_text("Tap to enter date") ui:show_text("Tap to enter date")
return return
end end
local params = aio:get_args() local params = settings:get()
start_period = get_time(params[2], params[3], params[4]); start_period = get_time(params[2], params[3], params[4]);
end_period = get_time(params[5], params[6], params[7]); end_period = get_time(params[5], params[6], params[7]);
name_period = params[1] name_period = params[1]
current_time = os.time() current_time = os.time()
init_progressbar() init_progressbar()
end end
function on_click() function on_click()
aio:show_args_dialog() aio:show_args_dialog()
end end
function get_time(y,m,d) function get_time(y,m,d)
return os.time{day=d,month=m,year=y} return os.time{day=d,month=m,year=y}
end end
function init_progressbar() function init_progressbar()
percent = math.floor((current_time - start_period) / ((end_period - start_period) / 100)) percent = math.floor((current_time - start_period) / ((end_period - start_period) / 100))
ui:show_progress_bar(name_period..": "..percent.."%", current_time - start_period, end_period - start_period, "#7069f0ae") ui:show_progress_bar(name_period..": "..percent.."%", current_time - start_period, end_period - start_period, "#7069f0ae")
end end

View File

@@ -14,17 +14,17 @@ local month = 30.43
local milestones = { local milestones = {
1, 3, 7, 14, 1, 3, 7, 14,
month, month * 3, month * 6, month, month * 3, month * 6,
year, year * 3, year * 5, year * 10, year * 20 year, year * 3, year * 5, year * 10, year * 20, year * 100
} }
local milestones_formatted = { local milestones_formatted = {
"1 day", "3 days", "1 week", "2 weeks", "1 day", "3 days", "1 week", "2 weeks",
"1 months", "3 months", "6 months", "1 months", "3 months", "6 months",
"1 year", "3 years", "5 years", "10 years", "20 years" "1 year", "3 years", "5 years", "10 years", "20 years", "100 years"
} }
function on_resume() function on_resume()
local args = aio:get_args() local args = settings:get()
if next(args) == nil then if next(args) == nil then
ui:show_text("Tap to enter date") ui:show_text("Tap to enter date")
@@ -39,7 +39,7 @@ function on_resume()
local passed_days = math.floor(passed:spandays()) local passed_days = math.floor(passed:spandays())
local idx = get_milestone_idx(passed) local idx = get_milestone_idx(passed)
ui:show_progress_bar(passed_days.." days / "..milestones_formatted[idx], ui:show_progress_bar(passed_days.." days / "..milestones_formatted[idx],
passed_days, milestones[idx]) passed_days, milestones[idx])
end end

View File

@@ -34,7 +34,7 @@ end
function on_network_result_curr(result) function on_network_result_curr(result)
result_curr = result result_curr = result
local t = json.decode(result) local t = json.decode(result)
local dat = t.date local dat = t.date
local prev_date = prev_date(dat) local prev_date = prev_date(dat)
@@ -63,18 +63,18 @@ function prev_date(dat)
end end
function create_tab(result) function create_tab(result)
local curs = aio:get_args() local curs = settings:get()
local tab = {} local tab = {}
local t_c = json.decode(result_curr) local t_c = json.decode(result_curr)
local t_p = json.decode(result) local t_p = json.decode(result)
-- set title -- set title
local dat = t_c.date local dat = t_c.date
ui:set_title(ui:get_default_title().." "..dat:gsub("-", ".")) ui:set_title(ui:get_default_title().." "..dat:gsub("-", "."))
for idx = 1, #curs, 1 do for idx = 1, #curs, 1 do
local cur = curs[idx]:split(":") local cur = curs[idx]:split(":")
local rate_curr1 = t_c.usd[cur[1]] local rate_curr1 = t_c.usd[cur[1]]
local rate_curr2 = t_c.usd[cur[2]] local rate_curr2 = t_c.usd[cur[2]]
local rate_prev1 = t_p.usd[cur[1]] local rate_prev1 = t_p.usd[cur[1]]

View File

@@ -29,7 +29,7 @@ local url = nil
local curr_idx = nil local curr_idx = nil
function on_resume() function on_resume()
if next(aio:get_args()) == nil then if next(settings:get()) == nil then
ui:show_text("Tap to enter Kodi address") ui:show_text("Tap to enter Kodi address")
return return
end end
@@ -41,7 +41,7 @@ function on_resume()
end end
function on_click(idx) function on_click(idx)
if next(aio:get_args()) == nil then if next(settings:get()) == nil then
aio:show_args_dialog() aio:show_args_dialog()
return return
end end
@@ -78,7 +78,7 @@ end
function on_network_result_cmd(result) function on_network_result_cmd(result)
local parsed = json.decode(result) local parsed = json.decode(result)
if parsed.error ~= nil then if parsed.error ~= nil then
show_error(parsed) show_error(parsed)
end end
@@ -87,7 +87,7 @@ end
-- utils -- utils
function init_url_from_args() function init_url_from_args()
local ip_port = aio:get_args()[1]:split(":") local ip_port = settings:get()[1]:split(":")
url = "http://"..ip_port[1]..":"..ip_port[2].."/jsonrpc" url = "http://"..ip_port[1]..":"..ip_port[2].."/jsonrpc"
end end

View File

@@ -15,19 +15,19 @@ local click_url = "https://uptimerobot.com/dashboard#mainDashboard"
local media_type = "application/x-www-form-urlencoded" local media_type = "application/x-www-form-urlencoded"
function on_alarm() function on_alarm()
if (next(aio:get_args()) == nil) then if (next(settings:get()) == nil) then
ui:show_text("Tap to enter API key") ui:show_text("Tap to enter API key")
return return
end end
local key = aio:get_args()[1] local key = settings:get()[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 end
function on_click() function on_click()
if (next(aio:get_args()) == nil) then if (next(settings:get()) == nil) then
aio:show_args_dialog() aio:show_args_dialog()
else else
system:open_browser(click_url) system:open_browser(click_url)

View File

@@ -20,7 +20,7 @@ local dialog_id = ""
local item_idx = 0 local item_idx = 0
function on_resume() function on_resume()
if next(aio:get_args()) == nil then if next(settings:get()) == nil then
set_default_args() set_default_args()
end end
@@ -78,11 +78,11 @@ function on_dialog_action(data)
local radio_idx = get_radio_idx() local radio_idx = get_radio_idx()
local args = data local args = data
table.insert(args, radio_idx) table.insert(args, radio_idx)
aio:set_args(args) settings:set(args)
elseif dialog_id == "style" then elseif dialog_id == "style" then
local args = get_checkbox_idx() local args = get_checkbox_idx()
table.insert(args, data) table.insert(args, data)
aio:set_args(args) settings:set(args)
end end
on_resume() on_resume()
@@ -96,11 +96,11 @@ function set_default_args()
table.insert(args, i) table.insert(args, i)
end end
table.insert(args, 1) table.insert(args, 1)
aio:set_args(args) settings:set(args)
end end
function get_checkbox_idx() function get_checkbox_idx()
local tab = aio:get_args() local tab = settings:get()
table.remove(tab, #tab) table.remove(tab, #tab)
for i = 1, #tab do for i = 1, #tab do
tab[i] = tonumber(tab[i]) tab[i] = tonumber(tab[i])
@@ -109,7 +109,7 @@ function get_checkbox_idx()
end end
function get_radio_idx() function get_radio_idx()
local tab = aio:get_args() local tab = settings:get()
return tonumber(tab[#tab]) return tonumber(tab[#tab])
end end

View File

@@ -1,12 +0,0 @@
-- arguments_help = "The word recorded here will be displayed on the screen."
-- arguments_default = "Word"
function on_resume()
local args = aio:get_args()
if args == nil then
ui:show_text("args is empty")
else
ui:show_text("arg1: "..args[1])
end
end

18
samples/settings-test.lua Normal file
View File

@@ -0,0 +1,18 @@
function on_resume()
local s1 = {
key1 = "value1",
key2 = "value2",
}
settings:set_kv(s1)
local s2 = settings:get_kv()
ui:show_text("key1="..s2.key1.." ".."key2="..s2.key2)
end
function on_settings()
local s = settings:get_kv()
ui:show_dialog("Settings", "key1="..s.key1.." ".."key2="..s.key2)
end