diff --git a/README.md b/README.md index bea6bbe..b751e8a 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ The possibilities of scripts are limited, but they can be used to expand the fun * 4.0.0 - first version with scripts support; * 4.1.0 - added `weather` and `cloud` modules; +* 4.1.3 - added `notify`, `files` and `utils` modules. # Lifecycle callbacks @@ -196,6 +197,39 @@ Function returns the weather data in the `on_weather_result(result)` callback, w All data are returned in `on_cloud_result(meta, content)`. The first argument is the metadata, either a metadata table (in the case of `list_dir()`) or an error message string. The second argument is the contents of the file (in the case of `get_file()`). +# Notifications + +* `notify:get_current()` - requests current notifications from the launcher; +* `notify:open(key)` - opens notification with specified key; +* `notify:close(key)` - removes the notification with the specified key; + +The `notify:get_current()` function asks for all current notifications. The Launcher returns them one by one to the `on_notify_posted(table)` callback, where table is the table representing the notification. The same callback will be called when a new notification appears. When the notification is closed, the `on_notify_removed(table)` colbeck will be called. + +Notification table format: + +* `key` - a key uniquely identifying the notification; +* `time` - time of notification publication in seconds; +* `package` - name of the application package that sent the notification; +* `number` - the number on the notification badge, if any; +* `importance` - notification importance level: from 1 (low) to 4 (high), 3 - standard; +* `category` - notification category, for example `email`; +* `title` - notification title; +* `text` - notification text; +* `sub_text` - additional notification text; +* `big_text` - extended notification text; +* `is_clearable` - true, if the notification is clearable; +* `group_id` - notification group ID. + +Keep in mind that the standard AIO Notifications widget also calls `get_current()` every time you return to the launcher, which means that if the Notifications widget is present, all scripts will also get notification information in the `on_notify_posted()` callback every time you return to the desktop. + +# Files + +* `files:read(file)` - returns file contents or `nil` if file does not exist; +* `files:write(file, string)` - writes `string` to file (creates file if file does not exist); +* `files:delete(file)` - deletes the file; + +Note that the AIO Launcher does not allow you to read and write any files. Instead, all files are created in the subdirectory `/sdcard/Android/data/ru.execbit.aiolauncher/files/scripts` without ability to create subdirectories. + # Settings * `settings:get()` - returns the settings table in an array of words format; @@ -208,6 +242,13 @@ User can change settings through the dialog, which is available by clicking on t The standard edit dialog can be replaced by your own if you implement the `on_settings()` function. +# Functions + +* `utils:md5(string)` - returns md5-hash of string (array of bytes); +* `utils:sha256(string)` - returns sha256-hash of string (array of bytes); +* `utils:base64encode(string)` - returns base64 representation of string (array of bytes); +* `utils:base64decode(string)` - decodes base64 string; + # 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 75133c1..3fbec41 100644 --- a/README_ru.md +++ b/README_ru.md @@ -2,12 +2,13 @@ Начиная с версии 4.0, AIO Launcher поддерживает скрипты, а точнее специальные виджеты, написанные на скриптовом языке [Lua](https://en.wikipedia.org/wiki/Lua_(programming_language)). Такие виджеты следует размещать в каталоге `/sdcard/Android/data/ru.execbit.aiolauncher/files/`. Затем их можно добавить на экран используя раздел настроек "Скрипты" или с помощью бокового меню. -Возможности скриптов ограничены, но с их помощью можно практически безгранично расширять функциональность приложения (посмотрите примеры в этом репозитории). +С помощью скриптов можно практически безгранично расширять функциональность приложения (смотрите примеры в этом репозитории). # Изменения * 4.0.0 - первая версия с поддержкой скриптов; * 4.1.0 - добавлены модули `weather` и `cloud`; +* 4.1.3 - добавлены модули `notify`, `files` и `utils`. # Функции (колбеки) жизненного цикла @@ -79,7 +80,7 @@ ui:show_context_menu({ Здесь `share`, `copy` и `trash` - это названия иконок, которое можно узнать на сайте [Fontawesome](https://fontawesome.com/). -При нажатии на любой элемент меню будет вызван колбек `on_context_menu_click(item_idx)`, где `item\_idx` - это индекс элемента меню. +При нажатии на любой элемент меню будет вызван колбек `on_context_menu_click(item_idx)`, где `item_idx` - это индекс элемента меню. # Системные функции @@ -196,6 +197,39 @@ ui:show_context_menu({ Все данные возвращаются в `on_cloud_result(meta, content)`. Первый аргумент - это метаданные, либо таблица метаданных (в случае с `list_dir()`), либо строка с сообщением об ошибке. Второй аргумент - содержимое файла (в случае `get_file()`). +# Уведомления + +* `notify:get_current()` - запрашивает у лаунчера текущие уведомления; +* `notify:open(key)` - открывает уведомление с указанным key; +* `notify:close(key)` - смахивает уведомление с указанным key; + +Функция `notify:get_current()` запрашивает все текущие уведомления. Лаунчер возвращает их поочередно в колбек `on_notify_posted(table)`, где table - это таблица, олицетворяющая уведомление. Тот же колбек будет вызван когда появится новое уведомление. При закрытии уведомления будет вызван колбек `on_notify_removed(table)`. + +Формат таблицы-уведомления: + +* `key` - уникальный ключ, однозначно идентифицирующий уведомление; +* `time` - время публикации уведомления в секундах; +* `package` - имя пакета приложения, отправившего уведомление; +* `number` - цифра на бейдже уведомления, если есть; +* `importance` - уровень важности уведомления: от 1 (низкий) до 4 (высокий), 3 - стандартный; +* `category` - категория уведомления, например `email`; +* `title` - заголовок уведомления; +* `text` - текст уведомления; +* `sub_text` - дополнительный текст уведомления; +* `big_text` - текст развернутого уведомления; +* `is_clearable` - true, если уведомление смахиваемое; +* `group_id` - ID группы уведомлений. + +Имейте ввиду, что стандартный виджет уведомлений AIO также делает вызов `get_current()` при каждом возврате на рабочий стол, а это значит, что при наличии виджета уведомлений все скрипты также будут получать информацию об уведомлениях в колбек `on_notify_posted()` при каждом возврате на рабочий стол. + +# Файлы + +* `files:read(file)` - возвращает содержимое файла или `nil` если файла не существует; +* `files:write(file, string)` - записывает строку `string` в файл (создает файл если его не существует); +* `files:delete(file)` - удаляет файл; + +Обратите внимание, что лаунчер не позволяет читать и писать любые файлы. Вместо этого все файлы создаются в подкаталоге `/sdcard/Android/data/ru.execbit.aiolauncher/files/scripts` без возможности создавать подкаталоги. + # Настройки * `settings:get()` - возвращает таблицу настроек в формате массива слов; @@ -208,6 +242,13 @@ ui:show_context_menu({ Стандартный диалог редактирования можно заменить на свой если реализовать функцию `on_settings()`. +# Подсобные функции + +* `utils:md5(string)` - возвращает md5-хэш строки (массива байт); +* `utils:sha256(string)` - возвращает sha256-хэш строки (массива байт); +* `utils:base64encode(string)` - возвращает base64-представление строки (массива байт); +* `utils:base64decode(string)` - декодирует base64-строку; + # Функции обработки данных * `ajson:get_value(string, string)` - получает указанное значение из JSON; первый аргумент - JSON-строка, второй - инструкция для получения значения. diff --git a/samples/files_sample.lua b/samples/files_sample.lua new file mode 100644 index 0000000..78ed5f5 --- /dev/null +++ b/samples/files_sample.lua @@ -0,0 +1,6 @@ +function on_resume() + files:delete("abc.txt") + files:write_text("abc.txt", "This is text") + local string = files:read_text("abc.txt") + ui:show_text(string) +end diff --git a/samples/notify_sample.lua b/samples/notify_sample.lua new file mode 100644 index 0000000..bb7d68e --- /dev/null +++ b/samples/notify_sample.lua @@ -0,0 +1,38 @@ + +local curr_notab = {} +local curr_titletab = {} +local curr_keystab = {} + +function on_resume() + notify:get_current() +end + +function on_notify_posted(n) + curr_notab[n.key] = n + redraw() +end + +function on_notify_removed(n) + curr_notab[n.key] = nil + redraw() + ui:show_toast("Notify from "..n.package.." removed") +end + +function redraw() + fill_tabs(curr_notab) + ui:show_lines(curr_titletab) +end + +function on_click(i) + notify:open(curr_keystab[i]) +end + +function fill_tabs(tab) + curr_titletab = {} + curr_keystab = {} + + for k,v in pairs(tab) do + table.insert(curr_titletab, v.title) + table.insert(curr_keystab, v.key) + end +end