Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/awtk/tests
repos/awtk/tests/testdata/fixed.h
/** * File: apidoc_test.h * Author: AWTK Develop Team * Brief: 代码编辑器控件。 * * Copyright (c) 2023 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2023-03-03 Wang JunSheng <[email protected]> created * */ #ifndef TK_CODE_EDIT_H #define TK_CODE_EDIT_H #include "base/widget.h" #include "code_complete.h" BEGIN_C_DECLS /** * @class code_edit_t * @parent widget_t * @annotation ["scriptable","design","widget"] * 代码编辑器控件。 * * 在xml中使用"code\_edit"标签创建代码编辑器控件。如: * * ```xml * <!-- ui --> * <code_edit name="code_edit" x="10" y="10" w="200" h="200" tab_width="2"> * <scroll_bar_d name="scroll_bar" x="r" y="0" w="14" h="100%" value="0"/> * </code_edit> * ``` * * 可用通过style来设置控件的显示风格,如字体的大小和颜色等等。如: * * ```xml * <!-- style --> * <code_edit> * <style name="default" border_color="black" font_size="18"> * <normal text_color="black" /> * </style> * </code_edit> * ``` */ typedef struct _code_edit_t { widget_t widget; /** * @property {char*} lang * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 当前的代码的语言。 */ char* lang; /** * @property {const char*} code_theme * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 当前的代码的主题名称(在资源的xml目录必须有相应的xml文件存在,格式与nodepad++的一致)。 */ const char* code_theme; /** * @property {char*} filename * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 文件名。 */ char* filename; /** * @property {bool_t} show_line_number * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 是否显示行号,默认显示。 */ bool_t show_line_number; /** * @property {bool_t} readonly * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 是否只读。 */ bool_t readonly; /** * @property {bool_t} wrap_word * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 是否自动折行。 */ bool_t wrap_word; /** * @property {uint32_t} tab_width * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * tab的宽度。 */ uint32_t tab_width; /** * @property {int32_t} scroll_line * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 鼠标一次滚动行数。 */ int32_t scroll_line; /** * @property {int32_t} zoom * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 缩放等级。 */ int32_t zoom; /** * @property {int32_t} line_number_margin * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 行号边距(默认宽度32)。 */ int32_t line_number_margin; /** * @property {int32_t} symbol_margin * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 非折叠符号边距。 */ int32_t symbol_margin; /** * @property {bool_t} fold * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 是否启用折叠。 */ bool_t fold; /** * @property {int32_t} fold_symbol_margin * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 折叠符号边距。 */ int32_t fold_symbol_margin; /** * @property {bool_t} end_at_last_line * @annotation ["set_prop","get_prop","readable","persitent","design","scriptable"] * 是否只能滚动到最后一行。 */ bool_t end_at_last_line; /** * @property {bool_t} is_utf8_bom * @annotation ["get_prop","readable","persitent","design","scriptable"] * 当前文件是否 utf8_bom。 */ bool_t is_utf8_bom; /*private*/ int32_t lexer; void* impl; str_t text; ca_symbols_t* symbols; } code_edit_t; /** * @method code_edit_create * @annotation ["constructor", "scriptable"] * 创建code_edit对象 * @param {widget_t*} parent 父控件 * @param {xy_t} x x坐标 * @param {xy_t} y y坐标 * @param {wh_t} w 宽度 * @param {wh_t} h 高度 * * @return {widget_t*} code_edit对象。 */ static inline widget_t* code_edit_create(widget_t* parent, xy_t x, xy_t y, wh_t w, wh_t h); /** * @method code_edit_cast * 转换为code_edit对象(供脚本语言使用)。 * @annotation ["cast", "scriptable"] * @param {widget_t*} widget code_edit对象。 * * @return {widget_t*} code_edit对象。 */ widget_t* code_edit_cast(widget_t* widget); /** * @method code_edit_set_lang * 设置 当前的代码的语言。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {const char*} lang 当前的代码的语言。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_lang(widget_t* widget, const char* lang); /** * @method code_edit_set_code_theme * 设置 当前的代码的主题。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {const char*} code_theme 当前的代码的语言。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_code_theme(widget_t* widget, const char* code_theme); /** * @method code_edit_set_filename * 设置 文件名。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {const char*} filename 文件名。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_filename(widget_t* widget, const char* filename); /** * @method code_edit_set_show_line_number * 设置 是否显示行号。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {bool_t} show_line_number 是否显示行号。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_show_line_number(widget_t* widget, bool_t show_line_number); /** * @method code_edit_set_readonly * 设置 是否只读。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {bool_t} readonly 是否只读。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_readonly(widget_t* widget, bool_t readonly); /** * @method code_edit_set_tab_width * 设置 tab的宽度。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {uint32_t} tab_width tab的宽度。。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_tab_width(widget_t* widget, uint32_t tab_width); /** * @method code_edit_set_zoom * 设置 缩放等级。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int32_t} zoom 缩放等级。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_zoom(widget_t* widget, int32_t zoom); /** * @method code_edit_set_line_number_margin * 设置 行号边距。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int32_t} margin 行号边距。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_line_number_margin(widget_t* widget, int32_t margin); /** * @method code_edit_set_symbol_margin * 设置 非折叠符号边距。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int32_t} margin 边距。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_symbol_margin(widget_t* widget, int32_t margin); /** * @method code_edit_set_fold_symbol_margin * 设置 折叠符号边距。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int32_t} margin 边距。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_fold_symbol_margin(widget_t* widget, int32_t margin); /** * @method code_edit_set_fold * 启用/禁用折叠。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {bool_t} fold 字体大小。 * * @return {ret_t} 返回RET_OK表示成功。 */ ret_t code_edit_set_fold(widget_t* widget, bool_t fold); /** * @method code_edit_set_end_at_last_line * 设置 是否只能滚动到最后一行。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {bool_t} end_at_last_line 是否只能滚动到最后一行。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_end_at_last_line(widget_t* widget, bool_t end_at_last_line); /** * @method code_edit_set_wrap_word * 设置 是否自动折行。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {bool_t} wrap_word 是否自动折行。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_wrap_word(widget_t* widget, bool_t wrap_word); /** * @method code_edit_set_scroll_line * 设置 滚动速度。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int32_t} scroll_line 滚动行数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_scroll_line(widget_t* widget, int32_t scroll_line); /** * @method code_edit_insert_text * 插入一段文本。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int32_t} offset 插入的偏移位置。 * @param {const char*} text 待插入的文本。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_insert_text(widget_t* widget, int32_t offset, const char* text); /** * @method code_edit_replace_sel * 替换选中文本。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {const char*} text 待替换的文本。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_replace_sel(widget_t* widget, const char* text); /** * @method code_edit_set_sel * 设置选中位置。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} anchor 锚点位置。 * @param {int64_t} caret 光标位置。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_sel(widget_t* widget, int64_t anchor, int64_t caret); /** * @method code_edit_delete_range * 删除选中范围的文本。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} start 起始位置。 * @param {int64_t} length 文本长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_delete_range(widget_t* widget, int64_t start, int64_t length); /** * @method code_edit_redo * 重做。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_redo(widget_t* widget); /** * @method code_edit_undo * 撤销。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_undo(widget_t* widget); /** * @method code_edit_empty_undo_buffer * 清空undo缓存。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_empty_undo_buffer(widget_t* widget); /** * @method code_edit_set_save_point * 设置save point。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_save_point(widget_t* widget); /** * @method code_edit_copy * 拷贝选中的文本。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_copy(widget_t* widget); /** * @method code_edit_cut * 剪切。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_cut(widget_t* widget); /** * @method code_edit_paste * 粘贴。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_paste(widget_t* widget); /** * @method code_edit_clear * 清除内容。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_clear(widget_t* widget); /** * @method code_edit_clear_selection * 清除选中内容。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_clear_selection(widget_t* widget); /** * @method code_edit_clear_all * 清除所有内容。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_clear_all(widget_t* widget); /** * @method code_edit_select_none * 取消选择。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_select_none(widget_t* widget); /** * @method code_edit_select_all * 全选。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_select_all(widget_t* widget); /** * @method code_edit_can_redo * 检查是否可以重做。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {bool_t} 返回TRUE表示能,否则表示不能。 */ bool_t code_edit_can_redo(widget_t* widget); /** * @method code_edit_can_undo * 检查是否可以撤销。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {bool_t} 返回TRUE表示能,否则表示不能。 */ bool_t code_edit_can_undo(widget_t* widget); /** * @method code_edit_can_copy * 检查是否可以拷贝。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {bool_t} 返回TRUE表示能,否则表示不能。 */ bool_t code_edit_can_copy(widget_t* widget); /** * @method code_edit_can_cut * 检查是否可以剪切。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {bool_t} 返回TRUE表示能,否则表示不能。 */ bool_t code_edit_can_cut(widget_t* widget); /** * @method code_edit_can_paste * 检查是否可以粘贴。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {bool_t} 返回TRUE表示能,否则表示不能。 */ bool_t code_edit_can_paste(widget_t* widget); /** * @method code_edit_save * save * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {const char*} filename 文件名。 * @param {bool_t} with_utf8_bom bom * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_save(widget_t* widget, const char* filename, bool_t with_utf8_bom); /** * @method code_edit_load * load * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {const char*} filename 文件名。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_load(widget_t* widget, const char* filename); /** * @method code_edit_is_modified * 检查文档是否变化。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {bool_t} 返回TRUE表示是,否则表示否。 */ bool_t code_edit_is_modified(widget_t* widget); /** * @method code_edit_scroll_range * 检查文档是否变化。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} secondary 次位置。 * @param {int64_t} primary 主位置 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_scroll_range(widget_t* widget, int64_t secondary, int64_t primary); /** * @method code_edit_set_x_caret_policy * 设置x轴浮标策略。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int32_t} policy 策略 * @param {int32_t} slop * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_x_caret_policy(widget_t* widget, int32_t policy, int32_t slop); /** * @method code_edit_get_current_pos * 获取当前位置。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {int64_t} 返回当前位置。 */ int64_t code_edit_get_current_pos(widget_t* widget); /** * @method code_edit_word_start * 获取当前位置。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} pos 位置 * * @return {int64_t} 词的起始位置。 */ int64_t code_edit_word_start(widget_t* widget, int64_t pos); /** * @method code_edit_word_end * 获取当前位置。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {int64_t} 词的结束位置。 */ int64_t code_edit_word_end(widget_t* widget, int64_t pos); /** * @method code_edit_get_text_range * 获取指定区域的文本。 * @annotation ["scriptable1"] * @param {widget_t*} widget widget对象。 * @param {int64_t} start 起始位置 * @param {int64_t} end 结束位置 * @param {char*} buf 存放文本 * @param {int32_t} buf_capacity buf的容量 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_get_text_range(widget_t* widget, int64_t start, int64_t end, char* buf, int32_t buf_capacity); /** * @method code_edit_get_text_bom * 返回所有文本。 如果存在 utf8_bom, 返回的文本附带 bom 信息 * 使用后请调用 code_edit_free 释放 * * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t*} len 返回文本的长度。 * * @return {char*} 返回RET_OK表示成功,否则表示失败。 */ char* code_edit_get_text_bom(widget_t* widget, int64_t* len); /** * @method code_edit_free * 释放 s * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {void*} s 待释放的内容 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_free(void* s); /** * @method code_edit_get_word * 获取pos所在的单词 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} pos 位置偏移 * @param {char*} buf 存放文本 * @param {int32_t} buf_capacity buf的容量 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_get_word(widget_t* widget, int64_t pos, char* buf, int32_t buf_capacity); /** * @method code_edit_get_line * 获取pos所在行的内容 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} pos 位置偏移 * @param {char*} buf 存放文本 * @param {int32_t} buf_capacity buf的容量 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_get_line(widget_t* widget, int64_t pos, char* buf, int32_t buf_capacity); /** * @method code_edit_get_text_length * 获取文本的长度。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {int64_t} 返回文本的长度。 */ int64_t code_edit_get_text_length(widget_t* widget); /** * @method code_edit_set_current_pos * 设置当前位置。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} pos 位置 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_current_pos(widget_t* widget, int64_t pos); /** * @method code_edit_get_anchor * 获取当前位置。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {int64_t} 返回当前位置。 */ int64_t code_edit_get_anchor(widget_t* widget); /** * @method code_edit_set_anchor * 设置当前位置。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} pos 位置 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_anchor(widget_t* widget, int64_t pos); /** * @method code_edit_scroll_caret * 将视图滚动到浮标所在的位置(根据策略不同位置有所不同)。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_scroll_caret(widget_t* widget); /** * @method code_edit_get_first_visible_line * 获取当前第一个可见的行号。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {int64_t} 返回当前第一个可见的行号。 */ int64_t code_edit_get_first_visible_line(widget_t* widget); /** * @method code_edit_set_first_visible_line * 设置当前第一个可见的行号。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} line 行号 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_set_first_visible_line(widget_t* widget, int64_t line); /** * @method code_edit_is_line_visible * 指定行是否可见。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} line 行号 * * @return {bool_t} 返回line行是否可见。 */ bool_t code_edit_is_line_visible(widget_t* widget, int64_t line); /** * @method code_edit_goto_pos * 跳转到指定位置。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} pos 位置 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t code_edit_goto_pos(widget_t* widget, int64_t pos); /** * @method code_edit_get_line_from_position * 获取指定位置所在的行。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} pos 位置 * * @return {int64_t} 返回获取指定位置所在的行。 */ int64_t code_edit_get_line_from_position(widget_t* widget, int64_t pos); /** * @method code_edit_get_line_start * 获取指定行的起始偏移。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * 不可以的 * @param {int64_t} line 行号 * * @return {int64_t} 行的起始位置。 */ int64_t code_edit_get_line_start(widget_t* widget, int64_t line); /** * @method code_edit_get_line_end * 获取指定行的结束偏移。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} line 行号 * * @return {int64_t} 行的结束位置。 */ int64_t code_edit_get_line_end(widget_t* widget, int64_t line); /** * @method code_edit_get_lines_on_screen * 获取当前屏幕中可见的行数。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {int64_t} 返回当前屏幕中可见的行数。 */ int64_t code_edit_get_lines_on_screen(widget_t* widget); /** * @method code_edit_set_all_font_size * 设置代码编辑器的默认字体大小。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {uint32_t} size 字体大小。 * * @return {ret_t} 返回RET_OK表示成功。 */ ret_t code_edit_set_all_font_size(widget_t* widget, uint32_t size); /** * @method code_edit_set_reloaded_text * 设置代码编辑器文本作为reload的字符串。与setText的区别是不会回滚到第一行。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {const char*} text 文本。 * * @return {ret_t} 返回RET_OK表示成功。 */ ret_t code_edit_set_reloaded_text(widget_t* widget, const char* text); /** * @method code_edit_vertical_centre_caret * 光标位置垂直居中。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功。 */ ret_t code_edit_vertical_centre_caret(widget_t* widget); /** * @method code_edit_show_autoc * 显示补全。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {ca_symbols_t*} symbols 补全信息 * * @return {ret_t} 返回RET_OK表示成功。 */ ret_t code_edit_show_autoc(widget_t* widget, ca_symbols_t* symbols); /** * @method code_edit_cancel_autoc * 取消补全。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * * @return {ret_t} 返回RET_OK表示成功。 */ ret_t code_edit_cancel_autoc(widget_t* widget); /** * @method code_edit_set_autoc_visible_lines * 设置推荐列表最大可见行数。 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int32_t} lines 推荐列表可见的行数。 * * @return {ret_t} 返回RET_OK表示成功。 */ ret_t code_edit_set_autoc_visible_lines(widget_t* widget, int32_t lines); /** * @method code_edit_is_comment * 指定位置是否是注释 * @annotation ["scriptable"] * @param {widget_t*} widget widget对象。 * @param {int64_t} pos 文件的偏移。 * * @return {bool_t} 是注释返回TRUE,否则返回 FALSE */ bool_t code_edit_is_comment(widget_t* widget, int64_t pos); /** * @enum code_edit_prop_t * @annotation ["scriptable", "string1"] * @prefix CODE_EDIT_PROP_ * 控件的属性。 */ /** * @const CODE_EDIT_PROP_LANG * 语言。 */ #define CODE_EDIT_PROP_LANG "lang" /** * @const CODE_EDIT_PROP_FILENAME * 文件名称。 */ #define CODE_EDIT_PROP_FILENAME "filename" /** * @const CODE_EDIT_PROP_TAB_WIDTH * tab宽度。 */ #define CODE_EDIT_PROP_TAB_WIDTH "tab_width" /** * @const CODE_EDIT_PROP_CODE_THEME * 代码样式主题。 */ #define CODE_EDIT_PROP_CODE_THEME "code_theme" /** * @const CODE_EDIT_PROP_SHOW_LINE_NUMBER * 显示行号。 */ #define CODE_EDIT_PROP_SHOW_LINE_NUMBER "show_line_number" /** * @const CODE_EDIT_PROP_ZOOM * ZOOM。 */ #define CODE_EDIT_PROP_ZOOM "zoom" /** * @const CODE_EDIT_PROP_LINE_NUMBER_MARGIN * LINE_NUMBER_MARGIN。 */ #define CODE_EDIT_PROP_LINE_NUMBER_MARGIN "line_number_margin" /** * @const CODE_EDIT_PROP_SYMBOL_MARGIN * SYMBOL_MARGIN。 */ #define CODE_EDIT_PROP_SYMBOL_MARGIN "symbol_margin" /** * @const CODE_EDIT_PROP_FOLD * FOLD。 */ #define CODE_EDIT_PROP_FOLD "fold" /** * @const CODE_EDIT_PROP_FOLD_SYMBOL_MARGIN * FOLD_SYMBOL_MARGIN。 */ #define CODE_EDIT_PROP_FOLD_SYMBOL_MARGIN "fold_symbol_margin" /** * @const CODE_EDIT_PROP_WRAP_WORD * 是否折行。 */ #define CODE_EDIT_PROP_WRAP_WORD "wrap_word" /** * @const CODE_EDIT_PROP_SCROLL_LINE * 鼠标一次滚动行数。 */ #define CODE_EDIT_PROP_SCROLL_LINE "scroll_line" /** * @const CODE_EDIT_PROP_CURRENT_POSITION * 当前位置。 */ #define CODE_EDIT_PROP_CURRENT_POSITION "current_position" /** * @const CODE_EDIT_PROP_ANCHOR * 锚点位置。 */ #define CODE_EDIT_PROP_ANCHOR "anchor" /** * @const CODE_EDIT_PROP_CURSOR * 光标位置(同步锚点位置)。 */ #define CODE_EDIT_PROP_CURSOR "cursor" /** * @const CODE_EDIT_PROP_SELECTION_START * 选择的文本的起始位置。 */ #define CODE_EDIT_PROP_SELECTION_START "selection_start" /** * @const CODE_EDIT_PROP_SELECTION_END * 选择文本的结束位置。 */ #define CODE_EDIT_PROP_SELECTION_END "selection_end" /** * @enum widget_type_t * @annotation ["scriptable", "string"] * @prefix WIDGET_TYPE_ * 控件的类型。 */ /** * @const WIDGET_TYPE_CODE_EDIT * 代码编辑器。 */ #define WIDGET_TYPE_CODE_EDIT "code_edit" #define CODE_EDIT(widget) ((code_edit_t*)(code_edit_cast(WIDGET(widget)))) /**public for ScintillaAWTK*/ #define PROP_CODE_EDITOR_FONT_SIZE \ "CODE_EDITOR_FONT_SIZE" // designer设置了代码编辑器的字体大小后,要设置值为字号的此属性到wm。 #define EVT_GLOBAL_CODE_EDITOR_FONT_SIZE_CHANGED \ EVT_USER_START + 1 // designer设置了代码编辑器的字体大小后,要从wm派发这个事件。 #define _SC_MARGE_LINENUMBER 0 // 第0条marge为行号 #define _SC_MARGE_SYBOLE 1 // 第1条marge为断点等 #define _SC_MARGE_FOLDER 2 // 第2条marge为折叠符号 #define _CODE_EDIT_DEFAULT_LINE_NUMBER_WITH 32 /*public for subclass and runtime type check*/ TK_EXTERN_VTABLE(code_edit); /*public for vtable*/ ret_t code_edit_on_destroy(widget_t* widget); ret_t code_edit_on_event(widget_t* widget, event_t* e); ret_t code_edit_on_paint_self(widget_t* widget, canvas_t* c); ret_t code_edit_on_add_child(widget_t* widget, widget_t* child); ret_t code_edit_get_prop(widget_t* widget, const char* name, value_t* v); ret_t code_edit_set_prop(widget_t* widget, const char* name, const value_t* v); /** * @enum ret_t * @prefix RET_ * @annotation ["scriptable"] * 函数返回值常量定义。 */ typedef enum _ret_t { /** * @const RET_OK * 成功。 */ RET_OK = 0, /** * @const RET_OOM * Out of memory。 */ RET_OOM, } ret_t; /** * @enum kind_t * @annotation ["scriptable"] * @prefix KIND_ * 函数返回值常量定义。 */ typedef enum _kind_t { /** * @const KIND_OK * 成功。 */ KIND_OK = 0, /** * @const KIND_OOM * Out of memory。 */ KIND_OOM, } kind_t; END_C_DECLS #endif /*TK_CODE_EDIT_H*/
0
repos/awtk/tests
repos/awtk/tests/testdata/test_lines.txt
line2 line4 line5xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
0
repos/awtk
repos/awtk/dllexports/README.md
# 导出函数
0
repos/awtk
repos/awtk/scripts/release_common.py
import os import sys import copy import glob import shutil import platform import fnmatch BIN_DIR = 'bin' EXE_NAME = 'demoui' ASSETS_DIR = 'assets' OUTPUT_DIR = 'release' CWD = os.getcwd() OS_NAME = platform.system(); def getShareLibExt(): if OS_NAME == 'Darwin': return 'dylib' elif OS_NAME == 'Windows': return 'dll' else: return 'so' def init(exe, assets_root, bin_root): global BIN_DIR global EXE_NAME global ASSETS_DIR global OUTPUT_DIR EXE_NAME = exe BIN_DIR = joinPath(bin_root, 'bin') OUTPUT_DIR = joinPath(CWD, 'release') ASSETS_DIR = joinPath(assets_root, 'res/assets') if not os.path.exists(BIN_DIR): BIN_DIR = joinPath(bin_root, 'build/bin') if not os.path.exists(ASSETS_DIR): ASSETS_DIR = joinPath(assets_root, 'assets') if not os.path.exists(ASSETS_DIR): ASSETS_DIR = joinPath(assets_root, '../awtk/res/assets') if not os.path.exists(ASSETS_DIR): print(ASSETS_DIR + ' not exist.') sys.exit() if os.path.exists(OUTPUT_DIR): shutil.rmtree(OUTPUT_DIR) print('==================================================') print('EXE_NAME:' + EXE_NAME) print('ASSETS_DIR:' + ASSETS_DIR) print('OUTPUT_DIR:' + OUTPUT_DIR) print('BIN_DIR:' + BIN_DIR) print('==================================================') def joinPath(root, subdir): return os.path.normpath(os.path.join(root, subdir)) def copyFile(src_root_dir, src, dst_root_dir, dst): s = joinPath(src_root_dir, src) d = joinPath(dst_root_dir, dst) print(s + '->' + d) if os.path.exists(s): dir = os.path.dirname(d) if os.path.exists(dir): shutil.copyfile(s, d) else: os.makedirs(dir) shutil.copyfile(s, d) else: print('!!! copyFile src NOT EXISTS: ' + s) def ignore_patterns_list(patterns_list): def _ignore_patterns(path, names): ignored_names = [] for pattern in patterns_list: ignored_names.extend(fnmatch.filter(names, pattern)) return set(ignored_names) return _ignore_patterns def copyFiles(src_root_dir, src, dst_root_dir, dst, ignore_files=[]): s = joinPath(src_root_dir, src) d = joinPath(dst_root_dir, dst) print(s + '->' + d) if os.path.exists(s): shutil.rmtree(d, True) ignore_files.append('*.o') ignore_files.append('*.obj') ignore_files.append('*.res') ignore_files.append('*.xml') ignore_files.append('*.inc') shutil.copytree(s, d, ignore=ignore_patterns_list(ignore_files)) else: print('!!! copyFiles src NOT EXISTS: ' + s) def copySharedLib(src, dst): if not os.path.exists(src): print('copy shared lib: ' + src + ' is not exists.') else: files = os.listdir(src) for file in files: srcFilename = joinPath(src, file) dstFilename = joinPath(dst, file) if os.path.isdir(srcFilename): if not os.path.exists(dstFilename): os.makedirs(dstFilename) copySharedLib(srcFilename, dstFilename) else: ext = '.' + getShareLibExt() if file.endswith(ext): print('copy shared lib: ' + srcFilename + ' ==> ' + dstFilename) shutil.copy(srcFilename, dst) os.chmod(dstFilename, 0o755) def copyExe(): output_bin_dir = joinPath(OUTPUT_DIR, 'bin') copyFile(BIN_DIR, EXE_NAME, output_bin_dir, EXE_NAME) copySharedLib(BIN_DIR, output_bin_dir) os.chmod(joinPath(output_bin_dir, EXE_NAME), 0o755) def copyAssets(): copyFiles(ASSETS_DIR, '', OUTPUT_DIR, 'assets/') def cleanFiles(): d = joinPath(OUTPUT_DIR, 'assets/default/inc') shutil.rmtree(d, True) def release(): copyExe() copyAssets() cleanFiles()
0
repos/awtk
repos/awtk/scripts/update_res.py
import os, re import update_res_app as updater import update_res_common as common def have_file(filename, files): filename = filename.replace('\\', '/') for f in files: if (re.search(f, filename)): return True return False def is_demouiold_excluded_file(filename): excluded_files = [ '/fonts/ap.res', '/fonts/default_full.res', '/fonts/default_32.data', '/fonts/default_96.data', '/fonts/trado.res', '/images/bg_landscape_[1-3]', '/images/bg_portrait_[1-3]', '/images/bg[1-5]', '/images/bg[1-5]_s', '/images/repeat[1-4]', '/images/app[1-5]', '/images/logo_dynamic', '/images/debug_*_*', '/images/uiex_*', '/images/computer.bsvg', '/images/gradient.bsvg', '/images/windmill.bsvg', '/styles/uiex*', '/ui/uiex/*' ] return have_file(filename, excluded_files) def is_not_uiex_file(filename): uiex_file = [ '/fonts/default.res', '/strings/en_US', '/images/bg[1-5]', '/images/bg[1-5]_s', '/images/repeat[1-4]', '/images/app[1-5]', '/images/logo_dynamic', '/images/debug_*_*', '/images/ani[1-9]', '/images/gauge_pointer', '/images/uiex_*', '/images/computer.bsvg', '/images/gradient.bsvg', '/images/windmill.bsvg', '/styles/default', '/styles/dialog_toast', '/styles/uiex*', '/ui/uiex/*' ] return not have_file(filename, uiex_file) def is_null_file(filename): return False default_is_excluded_file_func = is_not_uiex_file def gen_res(name = 'assets', is_excluded_file_func = default_is_excluded_file_func): action = common.get_action() assets_root = common.get_assets_root() output_root = common.get_output_root() common.set_is_excluded_file_handler(is_excluded_file_func) subname = common.get_assets_subname() common.set_assets_subname('__'+ name +'_') asset_c = common.get_asset_c() common.set_asset_c(common.join_path(output_root, '../'+ name +'.inc')) if action == 'all' and assets_root == output_root: common.clean_res() common.gen_res_c() if isinstance(updater.get_theme(0), dict): common.gen_res_c(False) elif action == 'clean': common.clean_res() elif action == 'web': common.gen_res_c() elif action == 'json': common.gen_res_json() elif action != 'pinyin' and action != 'res': common.gen_res_c() if isinstance(updater.get_theme(0), dict): common.gen_res_c(False) common.set_asset_c(asset_c) common.set_assets_subname(subname) common.set_is_excluded_file_handler(default_is_excluded_file_func) AWTK_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) updater.run(AWTK_ROOT, default_is_excluded_file_func, True) gen_res('assets_old', is_demouiold_excluded_file) gen_res('assets_all', is_null_file)
0
repos/awtk
repos/awtk/scripts/create_assets_zip.sh
#!/bin/bash if [ "$1" == "" ] then SRC=res/assets else SRC="$1" fi echo "SRC=$SRC" if [ -e "$SRC" ] then echo "preparing..." else echo "res/assets not exists" exit 0 fi rm -rf temp rm -f assets.zip mkdir temp cp -rf "$SRC" temp cd temp/assets rm -fv *.inc for f in *; do if [ -d $f ] then echo "clean " $f; rm -rvf $f/inc rm -rvf $f/raw/ui/*.xml rm -rvf $f/raw/styles/*.xml rm -rvf $f/raw/strings/*.xml fi done cd .. zip -r ../assets.zip assets cd .. rm -rf temp echo "assets saved to assets.zip:" ls -l assets.zip
0
repos/awtk
repos/awtk/scripts/res_config.py
import os import io import sys import json def json_obj_load_file(file_path) : obj = None; if os.path.exists(file_path) : try : with io.open(file_path, 'r', encoding='utf-8') as file : obj = json.load(file); except Exception as e : print(e) return obj; def json_obj_save_file(obj, file_path) : dir = os.path.dirname(file_path); if os.path.exists(dir) : try : with io.open(file_path, 'w', encoding='utf-8') as file : if sys.version_info >= (3, 0): json.dump(obj, file, indent=4, ensure_ascii=False) else : file.write(json.dumps(obj, indent=4, ensure_ascii=False).decode('utf-8')) except Exception as e : print(e) else : print(dir + ' is not exists') def get_dict_value(dict, key, default_value) : if key in dict: return dict[key] else : return default_value def set_res_config_by_script(script_path, res_config_script_argv): script_path = os.path.abspath(script_path) if os.path.exists(script_path) : import importlib script_dir = os.path.dirname(script_path) file_name = os.path.basename(script_path) module_name, ext = os.path.splitext(file_name) sys.path.insert(0, script_dir) res_config_script = importlib.import_module(module_name) sys.path.remove(script_dir) if hasattr(res_config_script, "get_res_config") : return res_config_script.get_res_config(res_config_script_argv) else : sys.exit(script_path + ' script not found get_res_config function') else : sys.exit('res_config_file sopt not found :' + script_path) return None class res_multidict(dict) : def __getitem__(self, item) : try : return dict.__getitem__(self, item) except KeyError : value = self[item] = type(self)() return value def deep_copy_by_dict(self, src, dst) : for key in dst : if isinstance(dst[key], dict) : self.deep_copy_by_dict(src[key], dst[key]) elif isinstance(dst[key], list) : if not key in src : src[key] = list(); src[key] += list(dst[key]); else : src[key] = dst[key]; def deep_copy(self, dst) : self.deep_copy_by_dict(self, dst); class res_config: assets = None inc_res = True inc_bitmap = True inc_bitmap_font = True storage_dir = None def __init__(self) : self.assets = res_multidict(); def get_res_type_info_by_const_and_load_from(self, assets, inc_res, inc_bitmap, inc_bitmap_font) : const = get_dict_value(assets, 'const', None) loadFrom = get_dict_value(assets, 'loadFrom', None) if loadFrom != None and loadFrom == 'fs': inc_res = False inc_bitmap = False inc_bitmap_font = False elif const != None and const != 'all_data': if const == 'resource_data': inc_bitmap = False inc_bitmap_font = False else: inc_res = False return inc_res, inc_bitmap, inc_bitmap_font def has_themes(self) : if 'themes' in self.assets : return len(self.assets['themes']) > 0; return False def has_theme(self, theme_name) : if 'themes' in self.assets : return theme_name in self.assets['themes']; return False def has_lcd(self, theme_name) : if self.has_theme(theme_name) : return 'lcd' in self.assets['themes'][theme_name]; return False def has_font(self, theme_name, font_name) : if self.has_theme(theme_name) : if 'fonts' in self.assets['themes'][theme_name] : return font_name in self.assets['themes'][theme_name]['fonts'] return False def load_file(self, file_path) : obj = json_obj_load_file(file_path); if obj != None and 'assets' in obj : assets = obj['assets'] self.assets.deep_copy(assets) self.inc_res, self.inc_bitmap, self.inc_bitmap_font = self.get_res_type_info_by_const_and_load_from(assets, self.inc_res, self.inc_bitmap, self.inc_bitmap_font) else : print('not found or not parsered ' + file_path + ', so use default config') def save_file(self, file_path) : res_config_dict = { 'assets' : self.assets } json_obj_save_file(res_config_dict, file_path); def reset_default(self) : self.set_res_actived_theme() self.set_res_res_root() self.set_res_load_from() self.set_res_const() self.set_res_dpi() self.set_res_language() self.set_res_country() self.set_res_lcd_orientation() self.set_res_lcd_fast_rotation_mode() self.set_res_actived_system_bar() self.set_res_actived_bottom_system_bar() self.set_res_packaged() self.set_res_font_value() self.set_res_font_value(key='text') self.set_res_font_bpp() self.set_res_w() self.set_res_h() self.set_res_color_depth() self.set_res_color_format() def get_res_themes_key(self) : if self.has_themes() : return self.assets['themes'].keys() return list() def get_res_fonts_key(self, theme_name) : if self.has_themes() : return self.assets['themes'][theme_name]['fonts'].keys() return list() def get_res_font_size_key(self, theme_name, font_name) : key = [] if self.has_themes() : for name in self.assets['themes'][theme_name]['fonts'][font_name].keys() : if name != 'text' or name != 'bpp' : key.append(name) return key def set_res_lcd_value(self, theme_name, key, value) : self.assets['themes'][theme_name]['lcd'][key] = value def get_res_lcd_value(self, theme_name, key, default_value) : if self.has_lcd(theme_name) : return get_dict_value(self.assets['themes'][theme_name]['lcd'], key, default_value) return default_value; def set_res_theme_value(self, theme_name, key, value) : self.assets['themes'][theme_name][key] = value def get_res_theme_value(self, theme_name, key, default_value) : if self.has_theme(theme_name) : return get_dict_value(self.assets['themes'][theme_name], key, default_value) return default_value; def set_res_font_bpp(self, theme_name = 'default', font_name = 'default', value = '8bits') : self.assets['themes'][theme_name]['fonts'][font_name]['bpp'] = value def get_res_font_bpp(self, theme_name, font_name, default_value) : if self.has_font(theme_name, font_name) : return get_dict_value(self.assets['themes'][theme_name]['fonts'][font_name], 'bpp', default_value) return default_value; def set_res_font_value(self, theme_name = 'default', font_name = 'default', key = '18', value = '') : self.assets['themes'][theme_name]['fonts'][font_name][key] = value def get_res_font_value(self, theme_name, font_name, key, default_value) : if self.has_font(theme_name, font_name) : return get_dict_value(self.assets['themes'][theme_name]['fonts'][font_name], key, default_value) return default_value; def set_res_packaged(self, packaged = True, theme_name = 'default') : return self.set_res_theme_value(theme_name, 'packaged', packaged); def get_res_packaged(self, theme_name = 'default') : return self.get_res_theme_value(theme_name, 'packaged', True); def set_res_actived_bottom_system_bar(self, bottom_system_bar='', theme_name = 'default') : return self.set_res_theme_value(theme_name, 'activedBottomSystemBar', bottom_system_bar); def get_res_actived_bottom_system_bar(self, theme_name = 'default') : return self.get_res_theme_value(theme_name, 'activedBottomSystemBar', ''); def set_res_actived_system_bar(self, system_bar = '', theme_name = 'default') : return self.set_res_theme_value(theme_name, 'activedSystemBar', system_bar); def get_res_actived_system_bar(self, theme_name = 'default') : return self.get_res_theme_value(theme_name, 'activedSystemBar', ''); def set_res_color_depth(self, color_depth ='rgba', theme_name = 'default') : return self.set_res_lcd_value(theme_name, 'colorDepth', color_depth); def get_res_color_depth(self, theme_name = 'default') : return self.get_res_lcd_value(theme_name, 'colorDepth', 'rgba'); def set_res_color_format(self, color_format ='rgba', theme_name = 'default') : return self.set_res_lcd_value(theme_name, 'colorFormat', color_format); def get_res_color_format(self, theme_name = 'default') : return self.get_res_lcd_value(theme_name, 'colorFormat', 'rgba'); def set_res_w(self, w = '800', theme_name = 'default'): self.set_res_lcd_value(theme_name, 'width', w) def get_res_w(self, theme_name): return self.get_res_lcd_value(theme_name, 'width', '800'); def set_res_h(self, h = '480', theme_name = 'default'): self.set_res_lcd_value(theme_name, 'height', h) def get_res_h(self, theme_name): return self.get_res_lcd_value(theme_name, 'height', '480'); def set_res_lcd_fast_rotation_mode(self, lcd_fast_rotation_mode = False): self.assets['lcdFastRotationMode'] = lcd_fast_rotation_mode def get_res_lcd_fast_rotation_mode(self): return get_dict_value(self.assets, 'lcdFastRotationMode', False); def set_res_lcd_orientation(self, orientation = '0', theme_name = None): if theme_name == None : self.assets['lcdOrientation'] = orientation else : self.assets['themes'][theme_name]['lcd']['orientation'] = orientation def get_res_lcd_orientation(self, theme_name = ''): orientation = '0' if 'lcdOrientation' in self.assets : orientation = self.assets['lcdOrientation'] elif theme_name != '' and self.has_lcd(theme_name) and 'orientation' in self.assets['themes'][theme_name]['lcd'] : orientation = self.assets['themes'][theme_name]['lcd']['orientation'] return orientation def set_res_actived_theme(self, actived_theme = 'default'): self.assets['activedTheme'] = actived_theme def get_res_actived_theme(self): return get_dict_value(self.assets, 'activedTheme', 'default') def set_res_dpi(self, dpi = 'x1'): self.assets['screenDPR'] = dpi def get_res_dpi(self): return get_dict_value(self.assets, 'screenDPR', 'x1') def set_res_language(self, language = 'zh'): self.assets['defaultLanguage'] = language def get_res_language(self): return get_dict_value(self.assets, 'defaultLanguage', 'zh') def set_res_country(self, country = 'CN'): self.assets['defaultCountry'] = country def get_res_country(self): return get_dict_value(self.assets, 'defaultCountry', 'CN') def set_res_res_root(self, res_root = 'res'): self.assets['outputDir'] = res_root def get_res_res_root(self): res_root = get_dict_value(self.assets, 'outputDir', 'res') if os.path.isabs(res_root): return res_root else: return './' + res_root def set_res_load_from(self, load_from = 'any'): self.assets['loadFrom'] = load_from self.inc_res, self.inc_bitmap, self.inc_bitmap_font = self.get_res_type_info_by_const_and_load_from(self.assets, self.inc_res, self.inc_bitmap, self.inc_bitmap_font) def get_res_load_from(self): return get_dict_value(self.assets, 'loadFrom', 'any') def set_res_const(self, const = 'all_data'): self.assets['const'] = const self.inc_res, self.inc_bitmap, self.inc_bitmap_font = self.get_res_type_info_by_const_and_load_from(self.assets, self.inc_res, self.inc_bitmap, self.inc_bitmap_font) def get_res_load_from(self): return get_dict_value(self.assets, 'const', 'all_data') def get_inc_res(self) : return self.inc_res def get_inc_bitmap(self) : return self.inc_bitmap def get_inc_bitmap_font(self) : return self.inc_bitmap_font def get_storage_dir(self): return self.storage_dir
0
repos/awtk
repos/awtk/scripts/app_helper_base.py
import os import sys import json import atexit import shutil import platform import res_config import compile_config from SCons import Script, Environment PLATFORM = platform.system() SRT_SCONS_CONFIG_FUN = 'get_scons_config' SRT_SCONS_CONFIG_SCRIPT = 'SCONS_CONFIG_SCRIPT' SRT_SCONS_CONFIG_SCRIPT_ARGV = 'SCONS_CONFIG_SCRIPT_ARGV' COMPILE_CONFIG = { 'AWTK_ROOT' : { 'value' : None, 'type' : str.__name__, 'desc' : ['awtk root'], 'help_info' : 'set link awtk root, AWTK_ROOT=XXXXX'}, 'LINUX_FB' : { 'value' : False, 'type' : bool.__name__, 'desc' : ['use linux\'s building'], 'help_info' : 'use linux\'s compile tools prefix building, value is true or false'}, 'MVVM_ROOT' : { 'value' : None, 'type' : str.__name__, 'desc' : ['awtk\'s mvvm root'], 'help_info' : 'set link awtk\'s mvvm root, MVVM_ROOT=XXXXX'}, 'WITH_MVVM' : { 'value' : False, 'type' : bool.__name__, 'desc' : ['use mvvm'], 'help_info' : 'use mvvm\'s lib, value is true or false'}, 'WITH_JERRYSCRIPT' : { 'value' : False, 'type' : bool.__name__, 'desc' : ['use mvvm\'s js'], 'help_info' : 'use mvvm js\'s lib, value is true or false'}, 'WITH_IOTJS' : { 'value' : False, 'type' : bool.__name__, 'desc' : ['use mvvm\'s iotjs'], 'help_info' : 'use mvvm iotjs\'s lib, value is true or false'}, 'AWFLOW_ROOT' : { 'value' : None, 'type' : str.__name__, 'desc' : ['awtk\'s awflow root'], 'help_info' : 'set link awtk\'s awflow root, AWFLOW_ROOT=XXXXX'}, 'WITH_AWFLOW' : { 'value' : False, 'type' : bool.__name__, 'desc' : ['use awflow'], 'help_info' : 'use awflow\'s lib, value is true or false'}, SRT_SCONS_CONFIG_SCRIPT : { 'value' : None, 'type' : str.__name__, 'save_file' : False, 'desc' : ['set script file path, this is script has {0}(COMPILE_CONFIG, ARGUMENTS, argv) function'.format(SRT_SCONS_CONFIG_FUN)], 'help_info' : 'set res config file path, this is script must has {0}(COMPILE_CONFIG, ARGUMENTS, argv) function, {0}\'s function return compile_config\'s class, CONFIG_SCRIPT=XXXXX'.format(SRT_SCONS_CONFIG_FUN)}, SRT_SCONS_CONFIG_SCRIPT_ARGV : { 'value' : None, 'type' : str.__name__, 'save_file' : False, 'desc' : ['value is {0}\s argv for script file '.format(SRT_SCONS_CONFIG_FUN)], 'help_info' : 'value is {0}\s argv for script file\'s {0}, SCONS_CONFIG_SCRIPT_ARGV=XXXXX'.format(SRT_SCONS_CONFIG_FUN)}, 'BUILD_DIR' : { 'value' : None, 'type' : str.__name__, 'desc' : ['build dir, compile temp file dir'], 'help_info' : 'set build dir, save compile temp file dir or *.obj/.*o dir, BUILD_DIR=XXXXX'}, # 'APP_BIN_DIR' : { 'value' : None, 'type' : str.__name__, 'desc' : ['build bin dir'], 'help_info' : 'set build bin dir, APP_BIN_DIR=XXXXX'}, # 'APP_LIB_DIR' : { 'value' : None, 'type' : str.__name__, 'desc' : ['build lib dir'], 'help_info' : 'set build lib dir, APP_LIB_DIR=XXXXX'}, 'DEBUG' : { 'value' : None, 'type' : bool.__name__, 'desc' : ['awtk\'s compile is debug'], 'help_info' : 'awtk\'s compile is debug, value is true or false' }, 'PDB' : { 'value' : True, 'type' : bool.__name__, 'desc' : ['export pdb file'], 'help_info' : 'export pdb file, value is true or false' }, 'FLAGS' : { 'value' : None, 'type' : str.__name__, 'desc' : ['compile flags'], 'help_info' : 'set compile\'s flags, so care of system and compile tools'}, 'LIBS' : { 'value' : [], 'type' : list.__name__, 'desc' : ['compile libs'], 'help_info' : 'set compile\'s libs, so care of system and compile tools, use \',\' split muliple libraries '}, 'LIBPATH' : { 'value' : [], 'type' : list.__name__, 'desc' : ['compile lib paths'], 'help_info' : 'set compile\'s lib paths, so care of system and compile tools, use \',\' split muliple librarie\'s paths '}, 'CPPPATH' : { 'value' : [], 'type' : list.__name__, 'desc' : ['compile include paths'], 'help_info' : 'set compile\'s include paths, so care of system and compile tools, use \',\' split muliple include path '}, 'SHARED' : { 'value' : True, 'type' : bool.__name__, 'desc' : ['compile is SharedLibrary'], 'help_info' : 'app\'s compile is Shared Library, value is true or false' }, 'IDL_DEF' : { 'value' : True, 'type' : bool.__name__, 'desc' : ['compile build idl def file'], 'help_info' : 'app\'s compile build idl def file, value is true or false' }, 'LCD' : { 'value' : None, 'type' : str.__name__, 'save_file' : False, 'desc' : ['app\'s lcd\'s size'], 'help_info' : 'app\'s lcd\'s size, value is [lcd_width]_[lcd_height], example is LCD=320_480' }, 'LANGUAGE' : { 'value' : None, 'type' : str.__name__, 'save_file' : False, 'desc' : ['app\'s language'], 'help_info' : 'app\'s language, value is [country]_[language], example is LANGUAGE=zh_CH' }, 'FONT' : { 'value' : None, 'type' : str.__name__, 'save_file' : False, 'desc' : ['app\'s font\'s name'], 'help_info' : 'app\'s font\'s name, FONT=XXXXX ' }, 'THEME' : { 'value' : None, 'type' : str.__name__, 'save_file' : False, 'desc' : ['app\'s default\'s theme\'s name'], 'help_info' : 'app\'s default\'s theme\'s name, THEME=XXXXX ' }, 'RES_ROOT' : { 'value' : None, 'type' : str.__name__, 'save_file' : False, 'desc' : ['app\'s res root'], 'help_info' : 'app\'s res root, RES_ROOT=XXXXX ' }, 'WIN32_RES' : { 'value' : None, 'type' : str.__name__, 'desc' : ['app\'s win32 res path'], 'help_info' : 'app\'s win32 res path, WIN32_RES=XXXXX, value\'s default=\'awtk/win32_res/awtk.res\' ' }, } def set_compile_config(config) : global COMPILE_CONFIG COMPILE_CONFIG = config def getTkcOnly(): env = os.environ if 'TKC_ONLY' in env: return env['TKC_ONLY'] == 'True' else: return False def join_path(root, sub): return os.path.abspath(os.path.join(root, sub)) def mkdir_if_not_exist(fullpath): if os.path.exists(fullpath): print(fullpath+' exist.') else: os.makedirs(fullpath) def load_project_json(root, filename): content = None config_json = join_path(root, filename) if not os.path.exists(config_json) or filename == '': config_json = join_path(root, 'project.json') if not os.path.exists(config_json) : print(config_json + ' is not exists.') return content = res_config.res_config() content.load_file(config_json) return content class AppHelperBase: def set_deps(self, DEPENDS_LIBS): self.DEPENDS_LIBS = DEPENDS_LIBS return self def set_src_dir(self, SRC_DIR): self.SRC_DIR = SRC_DIR return self def set_tkc_only(self): self.AWTK_LIBS = ['tkc'] self.TKC_ONLY = True return self def set_libs(self, APP_LIBS): self.APP_LIBS = APP_LIBS return self def set_dll_def(self, DEF_FILE): self.DEF_FILE = DEF_FILE return self def set_dll_def_processor(self, processor): self.DEF_FILE_PROCESSOR = processor return self def set_ccflags(self, APP_CCFLAGS): self.APP_CCFLAGS = APP_CCFLAGS return self def set_cxxflags(self, APP_CXXFLAGS): self.APP_CXXFLAGS = APP_CXXFLAGS return self def add_deps(self, DEPENDS_LIBS): self.DEPENDS_LIBS += DEPENDS_LIBS return self def add_libs(self, APP_LIBS): self.APP_LIBS += APP_LIBS return self def add_platform_libs(self, plat, PLATFORM_LIBS): if plat == PLATFORM: self.PLATFORM_LIBS += PLATFORM_LIBS return self def add_libpath(self, APP_LIBPATH): self.APP_LIBPATH += APP_LIBPATH return self def add_platform_libpath(self, plat, APP_LIBPATH): if plat == PLATFORM: self.APP_LIBPATH += APP_LIBPATH return self def add_cpppath(self, APP_CPPPATH): self.APP_CPPPATH += APP_CPPPATH return self def add_platform_cpppath(self, plat, APP_CPPPATH): if plat == PLATFORM: self.APP_CPPPATH += APP_CPPPATH return self def add_ccflags(self, APP_CCFLAGS): self.APP_CCFLAGS += APP_CCFLAGS return self def add_cflags(self, APP_CFLAGS): self.APP_CFLAGS += APP_CFLAGS return self def add_platform_ccflags(self, plat, APP_CCFLAGS): if plat == PLATFORM: self.APP_CCFLAGS += APP_CCFLAGS return self def use_std_cxx(self, VERSION): if platform.system() == 'Windows': self.APP_CXXFLAGS += ' /std:c++'+str(VERSION)+' ' else: self.APP_CXXFLAGS += ' -std=c++'+str(VERSION)+' ' def add_cxxflags(self, APP_CXXFLAGS): self.APP_CXXFLAGS += APP_CXXFLAGS return self def add_platform_cxxflags(self, plat, APP_CXXFLAGS): if plat == PLATFORM: self.APP_CXXFLAGS += APP_CXXFLAGS return self def add_linkflags(self, APP_LINKFLAGS): self.APP_LINKFLAGS += APP_LINKFLAGS return self def add_platform_linkflags(self, plat, APP_LINKFLAGS): if plat == PLATFORM: self.APP_LINKFLAGS += APP_LINKFLAGS return self def root_get_scons_db_files(self, root): scons_db_files = [] scons_db_filename = ".sconsign.dblite" for f in os.listdir(root): full_path = join_path(root, f) if os.path.isfile(full_path) and f == scons_db_filename: scons_db_files.append(full_path) elif os.path.isdir(full_path) and f != "." and f != "..": self.root_get_scons_db_files(full_path) return scons_db_files def check_and_remove_scons_db(self, root): scons_db_files = [] scons_db_files = self.root_get_scons_db_files(root) if sys.version_info.major == 2: import cPickle as pickle else: import pickle for f in scons_db_files: try: with open(f, "rb") as fs: pickle.load(fs) fs.close() except Exception as e : fs.close() print(e) try: os.remove(f) except Exception as e : print(e) def SConscript(self, SConscriptFiles): if not self.BUILD_DIR: Script.SConscript(SConscriptFiles) else: env = Environment.Environment() env.Default(self.BUILD_DIR) for sc in SConscriptFiles: dir = os.path.dirname(sc) build_dir = os.path.join(self.BUILD_DIR, dir) Script.SConscript(sc, variant_dir=build_dir, duplicate=False) def get_curr_config(self) : return compile_config.get_curr_config() def get_complie_helper_by_script(self, ARGUMENTS, script_path, script_argv) : global COMPILE_CONFIG script_path = os.path.abspath(script_path) if os.path.exists(script_path) : import importlib script_dir = os.path.dirname(script_path) file_name = os.path.basename(script_path) module_name, ext = os.path.splitext(file_name) sys.path.insert(0, script_dir) script = importlib.import_module(module_name) sys.path.remove(script_dir) if hasattr(script, SRT_SCONS_CONFIG_FUN) : return script.get_scons_config(COMPILE_CONFIG, ARGUMENTS, script_argv) else : sys.exit(script_path + ' script not found get_res_config function') else : sys.exit('res_config_file sopt not found :' + script_path) def __init__(self, ARGUMENTS): global COMPILE_CONFIG global SRT_SCONS_CONFIG_SCRIPT global SRT_SCONS_CONFIG_SCRIPT_ARGV if SRT_SCONS_CONFIG_SCRIPT in ARGUMENTS : self.complie_helper = self.get_complie_helper_by_script(ARGUMENTS, ARGUMENTS[SRT_SCONS_CONFIG_SCRIPT], ARGUMENTS.get(SRT_SCONS_CONFIG_SCRIPT_ARGV, '')) else : self.complie_helper = compile_config.complie_helper() self.complie_helper.set_compile_config(COMPILE_CONFIG) self.complie_helper.scons_user_sopt(ARGUMENTS) compile_config.set_curr_config(self.complie_helper) APP_ROOT = compile_config.get_curr_app_root() if len(APP_ROOT) == 0: APP_ROOT = os.path.normpath(os.getcwd()) compile_config.set_curr_app_root(APP_ROOT) self.SRC_DIR = 'src' self.TKC_ONLY = getTkcOnly(); self.ARGUMENTS = ARGUMENTS self.DEF_FILE = None self.DEF_FILE_PROCESSOR = None self.DEPENDS_LIBS = [] self.GEN_IDL_DEF = True self.BUILD_SHARED = True self.LINUX_FB = self.complie_helper.get_value('LINUX_FB', False) self.AWTK_ROOT = self.getAwtkRoot() self.awtk = self.getAwtkConfig() self.AWTK_LIBS = self.awtk.LIBS self.AWTK_CFLAGS = self.awtk.CFLAGS self.AWTK_CCFLAGS = self.awtk.CCFLAGS self.APP_ROOT = APP_ROOT self.BUILD_DIR = self.complie_helper.get_value('BUILD_DIR', '') self.BIN_DIR = os.path.join(self.BUILD_DIR, 'bin') self.LIB_DIR = os.path.join(self.BUILD_DIR, 'lib') self.APP_BIN_DIR = os.path.join(APP_ROOT, self.BIN_DIR) self.APP_LIB_DIR = os.path.join(APP_ROOT, self.LIB_DIR) self.APP_SRC = os.path.join(APP_ROOT, 'src') self.APP_RES = os.path.join(APP_ROOT, 'res') self.APP_LIBS = self.complie_helper.get_value('LIBS', []) self.APP_LINKFLAGS = '' self.PLATFORM_LIBS = [] self.APP_TOOLS = ['default'] self.WITH_JERRYSCRIPT = False self.WITH_IOTJS = False self.MVVM_ROOT = None self.AWFLOW_ROOT = None if hasattr(self.awtk, 'OS_NAME') : self.OS_NAME = self.awtk.OS_NAME; else : self.OS_NAME = None; self.AWTK_OS_DEBUG = True if hasattr(self.awtk, 'OS_DEBUG') : self.AWTK_OS_DEBUG = self.awtk.OS_DEBUG else : self.AWTK_OS_DEBUG = self.DEBUG self.DEBUG = self.complie_helper.get_value('DEBUG', self.AWTK_OS_DEBUG) if isinstance(self.DEBUG, str) : try : from utils import strtobool self.DEBUG = strtobool(self.DEBUG) == 1 except : self.DEBUG == self.DEBUG.lower() == 'true'; self.parseArgs(self.awtk, ARGUMENTS) self.APP_CPPPATH = [self.APP_SRC, self.APP_RES] + self.complie_helper.get_value('CPPPATH', []) self.APP_LIBPATH = [self.APP_LIB_DIR, self.APP_BIN_DIR] + self.complie_helper.get_value('LIBPATH', []) mkdir_if_not_exist(self.APP_BIN_DIR) mkdir_if_not_exist(self.APP_LIB_DIR) os.environ['APP_SRC'] = self.APP_SRC os.environ['APP_ROOT'] = self.APP_ROOT os.environ['BIN_DIR'] = self.APP_BIN_DIR os.environ['LIB_DIR'] = self.APP_LIB_DIR os.environ['LINUX_FB'] = 'false' os.environ['BUILD_DIR'] = self.BUILD_DIR if self.LINUX_FB: os.environ['LINUX_FB'] = 'true' self.WITH_JERRYSCRIPT = self.complie_helper.get_value('WITH_JERRYSCRIPT', False) self.WITH_IOTJS = self.complie_helper.get_value('WITH_IOTJS', False) WITH_MVVM = self.complie_helper.get_value('WITH_MVVM', False) MVVM_ROOT = self.complie_helper.get_value('MVVM_ROOT', '') if WITH_MVVM or os.path.exists(MVVM_ROOT): os.environ['WITH_MVVM'] = 'true' if not os.path.exists(MVVM_ROOT): MVVM_ROOT = self.getMvvmRoot() self.MVVM_ROOT = MVVM_ROOT print("MVVM_ROOT: " + self.MVVM_ROOT) WITH_AWFLOW = self.complie_helper.get_value('WITH_AWFLOW', False) AWFLOW_ROOT = self.complie_helper.get_value('AWFLOW_ROOT', '') print(WITH_AWFLOW) if WITH_AWFLOW or os.path.exists(AWFLOW_ROOT): os.environ['WITH_AWFLOW'] = 'true' if not os.path.exists(AWFLOW_ROOT): AWFLOW_ROOT = self.getAwflowRoot() self.AWFLOW_ROOT = AWFLOW_ROOT print("AWFLOW_ROOT: " + self.AWFLOW_ROOT) if self.TKC_ONLY : self.set_tkc_only() print("AWTK_ROOT: " + self.AWTK_ROOT) print("TKC_ONLY: " + str(self.TKC_ONLY)) print(ARGUMENTS) def getAwtkConfig(self): sys.path.insert(0, self.AWTK_ROOT) os.chdir(self.AWTK_ROOT) tmp_complie_helper = compile_config.get_curr_config() compile_config.set_app_win32_res(tmp_complie_helper.get_value('WIN32_RES', None)) compile_config.set_curr_config(None) import awtk_config as awtk os.chdir(compile_config.get_curr_app_root()) compile_config.set_curr_config(tmp_complie_helper) return awtk def saveUsesSdkInfo(self): awtk = self.awtk release_id = '' filename = os.path.join(self.AWTK_ROOT, 'component.json') if os.path.exists(filename): with open(filename, 'r') as f: component_content = f.read() if len(component_content) > 0: component_json = json.loads(component_content) if 'release_id' in component_json: release_id = component_json['release_id'] if sys.version_info < (3, 0): release_id = release_id.encode('ascii') content = '{\n' content += ' "compileSDK": {\n' content += ' "awtk": {\n' content += ' "path": "' + \ self.AWTK_ROOT.replace('\\', '/') + '",\n' content += ' "release_id": "' + release_id + '",\n' content += ' "nanovg_backend": "' + awtk.NANOVG_BACKEND + '"\n' content += ' }\n' content += ' }\n' content += '}' filename = os.path.join(self.APP_BIN_DIR, 'uses_sdk.json') if sys.version_info < (3, 0): with open(filename, 'w') as f: f.write(content) else: with open(filename, 'w', encoding='utf8') as f: f.write(content) def isBuildShared(self): return self.BUILD_SHARED def copyAwtkSharedLib(self): if self.TKC_ONLY: self.awtk.copySharedLib(self.AWTK_ROOT, self.APP_BIN_DIR, 'tkc') else: self.awtk.copySharedLib(self.AWTK_ROOT, self.APP_BIN_DIR, 'awtk') for iter in self.DEPENDS_LIBS: for so in iter['shared_libs']: self.awtk.copySharedLib(join_path(iter['root'], self.BUILD_DIR), self.BIN_DIR, so) def cleanAwtkSharedLib(self): if self.TKC_ONLY: self.awtk.cleanSharedLib(self.APP_BIN_DIR, 'tkc') else: self.awtk.cleanSharedLib(self.APP_BIN_DIR, 'awtk') for iter in self.DEPENDS_LIBS: for so in iter['shared_libs']: self.awtk.cleanSharedLib(self.APP_BIN_DIR, so) shutil.rmtree(self.APP_BIN_DIR); shutil.rmtree(self.APP_LIB_DIR); def genIdlAndDef(self): if self.DEF_FILE: print(self.DEF_FILE) else: return defDirlist = '' if self.APP_ROOT != self.AWTK_ROOT: defDirlist += os.path.abspath(self.AWTK_ROOT + '/tools/idl_gen/idl.json') + ';' for defLib in self.DEPENDS_LIBS : tmp_filename = os.path.abspath(defLib["root"] + '/idl/idl.json') if not os.path.exists(tmp_filename) : tmp_filename = os.path.abspath(defLib["root"] + '/idl.json') defDirlist += tmp_filename + ';' idl_gen_tools = os.path.join(self.AWTK_ROOT, 'tools/idl_gen/index.js') dll_def_gen_tools = os.path.join( self.AWTK_ROOT, 'tools/dll_def_gen/index.js') cmd = 'node ' + '"' + idl_gen_tools + '"' + ' idl/idl.json ' + self.SRC_DIR if defDirlist != '' : cmd += ' "' + defDirlist + '" ' if os.system(cmd) != 0: print('exe cmd: ' + cmd + ' failed.') cmd = 'node ' + '"' + dll_def_gen_tools + '"' + \ ' idl/idl.json ' + self.DEF_FILE if os.system(cmd) != 0: print('exe cmd: ' + cmd + ' failed.') else: if self.DEF_FILE_PROCESSOR != None: self.DEF_FILE_PROCESSOR() def parseArgs(self, awtk, ARGUMENTS): APP_RES_ROOT = '../res' APP_THEME = 'default' LCD_WIDTH = '320' LCD_HEIGHT = '480' LCD_ORIENTATION = '0' APP_DEFAULT_FONT = 'default' APP_DEFAULT_LANGUAGE = 'zh' APP_DEFAULT_COUNTRY = 'CN' config = load_project_json(self.APP_ROOT, 'project.json') if config != None: APP_THEME = config.get_res_actived_theme() LCD_WIDTH = config.get_res_w(APP_THEME) LCD_HEIGHT = config.get_res_h(APP_THEME) APP_DEFAULT_LANGUAGE = config.get_res_language() APP_DEFAULT_COUNTRY = config.get_res_country() APP_RES_ROOT = config.get_res_res_root() LCD_ORIENTATION = config.get_res_lcd_orientation(APP_THEME) LCD = self.complie_helper.get_value('LCD', '') if len(LCD) > 0: wh = LCD.split('_') if len(wh) >= 1: LCD_WIDTH = wh[0] if len(wh) >= 2: LCD_HEIGHT = wh[1] FONT = self.complie_helper.get_value('FONT', '') if len(FONT) > 0: APP_DEFAULT_FONT = FONT APP_THEME = self.complie_helper.get_value('THEME', APP_THEME) LANGUAGE = self.complie_helper.get_value('LANGUAGE', '') if len(LANGUAGE) > 0: lan = LANGUAGE.split('_') if len(lan) >= 1: APP_DEFAULT_LANGUAGE = lan[0] if len(lan) >= 2: APP_DEFAULT_COUNTRY = lan[1] APP_RES_ROOT = self.complie_helper.get_value('RES_ROOT', APP_RES_ROOT) self.APP_RES = os.path.abspath(os.path.join(self.APP_BIN_DIR, APP_RES_ROOT)) self.BUILD_SHARED = self.complie_helper.get_value('SHARED', False) self.GEN_IDL_DEF = self.complie_helper.get_value('IDL_DEF', True) LCD_ORIENTATION = self.complie_helper.get_value('LCD_ORIENTATION', LCD_ORIENTATION) if not self.LINUX_FB : if LCD_ORIENTATION == '90' or LCD_ORIENTATION == '270' : tmp = LCD_WIDTH; LCD_WIDTH = LCD_HEIGHT; LCD_HEIGHT = tmp; APP_CCFLAGS = ' -DLCD_WIDTH=' + LCD_WIDTH + ' -DLCD_HEIGHT=' + LCD_HEIGHT + ' ' APP_CCFLAGS = APP_CCFLAGS + ' -DAPP_DEFAULT_FONT=\\\"' + APP_DEFAULT_FONT + '\\\" ' APP_CCFLAGS = APP_CCFLAGS + ' -DAPP_THEME=\\\"' + APP_THEME + '\\\" ' APP_CCFLAGS = APP_CCFLAGS + ' -DAPP_RES_ROOT=\"\\\"' + APP_RES_ROOT + '\\\"\" ' APP_CCFLAGS = APP_CCFLAGS + ' -DAPP_DEFAULT_LANGUAGE=\\\"' + \ APP_DEFAULT_LANGUAGE + '\\\" ' APP_CCFLAGS = APP_CCFLAGS + ' -DAPP_DEFAULT_COUNTRY=\\\"' + \ APP_DEFAULT_COUNTRY + '\\\" ' APP_CCFLAGS = APP_CCFLAGS + ' -DAPP_ROOT=\"\\\"' + \ self.APP_ROOT.replace('\\', '/') + '\\\"\" ' self.APP_CFLAGS = '' self.APP_CCFLAGS = APP_CCFLAGS + self.complie_helper.get_value('FLAGS', '') self.APP_CXXFLAGS = '' if PLATFORM == 'Linux': self.APP_LINKFLAGS += ' -Wl,-rpath=' + self.APP_BIN_DIR + ' ' if not self.isBuildShared() and hasattr(awtk, 'AWTK_CCFLAGS'): self.AWTK_CCFLAGS = awtk.AWTK_CCFLAGS if self.isBuildShared(): if not self.TKC_ONLY : self.AWTK_LIBS = awtk.SHARED_LIBS self.APP_LIBPATH = [self.APP_BIN_DIR, self.APP_LIB_DIR] if hasattr(awtk, 'TOOLS_NAME') : if awtk.TOOLS_NAME != '': if awtk.TOOLS_NAME == 'mingw': self.APP_TOOLS = ['mingw'] elif awtk.TOOLS_NAME == '' and PLATFORM == 'Windows': APP_TOOLS = ['msvc', 'masm', 'mslink', "mslib"] os.environ['BUILD_SHARED'] = str(self.isBuildShared()) if LCD_ORIENTATION == '90' or LCD_ORIENTATION == '270' : print(LCD_HEIGHT, LCD_WIDTH, "orentation_" + LCD_ORIENTATION) else : print(LCD_WIDTH, LCD_HEIGHT, "orentation_" + LCD_ORIENTATION) def prepare(self): if self.GEN_IDL_DEF and not self.LINUX_FB: self.genIdlAndDef() if self.isBuildShared(): self.copyAwtkSharedLib() self.saveUsesSdkInfo() def getAwtkRoot(self): AWTK_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if self.LINUX_FB: AWTK_ROOT = os.path.join(os.path.dirname(AWTK_ROOT), 'awtk-linux-fb') return AWTK_ROOT def getMvvmRoot(self): MVVM_ROOT = os.path.join(os.path.dirname(self.getAwtkRoot()), 'awtk-mvvm') return MVVM_ROOT def getAwflowRoot(self): AWFLOW_ROOT = os.path.join(os.path.dirname(self.getAwtkRoot()), 'aw-flow') return AWFLOW_ROOT def call(self, DefaultEnvironment): awtk = self.awtk CPPPATH = awtk.CPPPATH + self.APP_CPPPATH LINKFLAGS = awtk.LINKFLAGS + self.APP_LINKFLAGS LIBS = self.AWTK_LIBS + self.PLATFORM_LIBS LIBPATH = self.APP_LIBPATH + awtk.LIBPATH CFLAGS = self.APP_CFLAGS + self.AWTK_CFLAGS CCFLAGS = self.APP_CCFLAGS + self.AWTK_CCFLAGS TARGET_ARCH = awtk.TARGET_ARCH APP_TOOLS = self.APP_TOOLS CXXFLAGS = self.APP_CXXFLAGS DEPENDS_LIBS = [] if hasattr(awtk, 'BUILD_DEBUG_FLAG') : BUILD_DEBUG_FLAG = awtk.BUILD_DEBUG_FLAG else : BUILD_DEBUG_FLAG = ' ' self.APP_BIN_DIR = self.complie_helper.get_value('APP_BIN_DIR', os.path.join(self.APP_ROOT, self.BIN_DIR)) self.APP_LIB_DIR = self.complie_helper.get_value('APP_LIB_DIR', os.path.join(self.APP_ROOT, self.LIB_DIR)) if self.MVVM_ROOT: MVVM_3RD_ROOT = join_path(self.MVVM_ROOT, '3rd') if self.WITH_IOTJS: IOTJS_ROOT = os.path.join(MVVM_3RD_ROOT, 'iotjs') DEPENDS_LIBS += [{ 'cxxflags': '-DWITH_MVVM -DWITH_JERRYSCRIPT -DWITH_IOTJS', 'cflags': '-DWITH_MVVM -DWITH_JERRYSCRIPT -DWITH_IOTJS', 'ccflags': '-DWITH_MVVM -DWITH_JERRYSCRIPT -DWITH_IOTJS', 'root' : self.MVVM_ROOT, 'shared_libs': ['mvvm'], 'static_libs': [''] }] CPPPATH += [ join_path(IOTJS_ROOT, 'deps/jerry/jerry-ext/include'), join_path(IOTJS_ROOT, 'deps/jerry/jerry-core/include') ] elif self.WITH_JERRYSCRIPT: DEPENDS_LIBS += [{ 'cxxflags': '-DWITH_MVVM -DWITH_JERRYSCRIPT', 'cflags': '-DWITH_MVVM -DWITH_JERRYSCRIPT', 'ccflags': '-DWITH_MVVM -DWITH_JERRYSCRIPT', 'root' : self.MVVM_ROOT, 'shared_libs': ['mvvm'], 'static_libs': [''] }] CPPPATH += [ join_path(MVVM_3RD_ROOT, 'jerryscript/jerryscript/jerry-ext/include'), join_path(MVVM_3RD_ROOT, 'jerryscript/jerryscript/jerry-core/include') ] else: DEPENDS_LIBS += [{ 'cxxflags': '-DWITH_MVVM', 'cflags': '-DWITH_MVVM', 'ccflags': '-DWITH_MVVM', 'root' : self.MVVM_ROOT, 'shared_libs': ['mvvm'], 'static_libs': [] }] if self.AWFLOW_ROOT: DEPENDS_LIBS += [{ 'cxxflags': '-DWITH_AWFLOW', 'cflags': '-DWITH_AWFLOW', 'ccflags': '-DWITH_AWFLOW', 'root' : self.AWFLOW_ROOT, 'shared_libs': ['awflow'], 'static_libs': [] }] if self.isBuildShared(): src = join_path(self.AWFLOW_ROOT, 'bin/nodes') dst = join_path(self.APP_ROOT, 'bin/nodes') if os.path.exists(dst): shutil.rmtree(dst) print(src + '==>' + dst) shutil.copytree(src, dst) self.DEPENDS_LIBS = DEPENDS_LIBS + self.DEPENDS_LIBS for depend in self.DEPENDS_LIBS: self.check_and_remove_scons_db(depend['root']) self.check_and_remove_scons_db(self.APP_ROOT) if self.TKC_ONLY: CCFLAGS += ' -DTKC_ONLY=1 ' else: CCFLAGS += ' -DWITH_AWTK=1 ' for iter in self.DEPENDS_LIBS: if 'shared_libs' in iter: LIBS = iter['shared_libs'] + LIBS if 'static_libs' in iter: LIBS = iter['static_libs'] + LIBS if 'cxxflags' in iter: CXXFLAGS += " " + iter['cxxflags'] + " " if 'cflags' in iter: CFLAGS += " " + iter['cflags'] + " " if 'ccflags' in iter: CCFLAGS += " " + iter['ccflags'] + " " if 'cpppath' in iter: for f in iter['cpppath']: CPPPATH = CPPPATH + [join_path(iter['root'], f)] else: CPPPATH += [join_path(iter['root'], 'src')] if 'libpath' in iter: for f in iter['libpath']: LIBPATH = LIBPATH + [join_path(iter['root'], f)] else: if self.isBuildShared(): LIBPATH += [join_path(iter['root'], self.BIN_DIR)] LIBPATH += [join_path(iter['root'], self.LIB_DIR)] LIBS = self.APP_LIBS + LIBS if hasattr(awtk, 'CC'): if self.DEBUG : CCFLAGS += ' -g -O0 ' else : CCFLAGS += ' -Os ' if self.DEBUG == self.AWTK_OS_DEBUG: CCFLAGS += BUILD_DEBUG_FLAG env = DefaultEnvironment( ENV = os.environ, CC=awtk.CC, CXX=awtk.CXX, LD=awtk.LD, AR=awtk.AR, STRIP=awtk.STRIP, RANLIB=awtk.RANLIB, TOOLS=APP_TOOLS, CPPPATH=CPPPATH, LINKFLAGS=LINKFLAGS, LIBS=LIBS, LIBPATH=LIBPATH, CCFLAGS=CCFLAGS, CFLAGS=CFLAGS, CXXFLAGS=CXXFLAGS, TARGET_ARCH=TARGET_ARCH, OS_SUBSYSTEM_CONSOLE=awtk.OS_SUBSYSTEM_CONSOLE, OS_SUBSYSTEM_WINDOWS=awtk.OS_SUBSYSTEM_WINDOWS) else: is_msvc = True; if hasattr(awtk, 'TOOLS_NAME') : if awtk.TOOLS_NAME != '': is_msvc = False if self.DEBUG : if self.OS_NAME == 'Windows' and is_msvc: CCFLAGS += ' -D_DEBUG -DDEBUG /DEBUG /MDd /Od ' elif self.OS_NAME == 'Darwin' or self.OS_NAME == 'Linux' : CCFLAGS += ' -g -O0 ' else : if self.OS_NAME == 'Windows' and is_msvc: CCFLAGS += ' -DNDEBUG /MD /O2 /Oi ' elif self.OS_NAME == 'Darwin' or self.OS_NAME == 'Linux' : CCFLAGS += ' -Os ' if self.OS_NAME == 'Windows' and is_msvc and self.complie_helper.get_value('PDB', True) : LINKFLAGS += ' /DEBUG ' if self.DEBUG == self.AWTK_OS_DEBUG: CCFLAGS += BUILD_DEBUG_FLAG LINKFLAGS += awtk.BUILD_DEBUG_LINKFLAGS env = DefaultEnvironment( TOOLS=APP_TOOLS, CPPPATH=CPPPATH, LINKFLAGS=LINKFLAGS, LIBS=LIBS, LIBPATH=LIBPATH, CFLAGS=CFLAGS, CCFLAGS=CCFLAGS, CXXFLAGS=CXXFLAGS, TARGET_ARCH=TARGET_ARCH, OS_SUBSYSTEM_CONSOLE=awtk.OS_SUBSYSTEM_CONSOLE, OS_SUBSYSTEM_WINDOWS=awtk.OS_SUBSYSTEM_WINDOWS) def variant_SConscript(env, SConscriptFiles): self.SConscript(SConscriptFiles) env.AddMethod(variant_SConscript, "SConscript") if not Script.GetOption('clean'): self.prepare() else: self.cleanAwtkSharedLib() return env
0
repos/awtk
repos/awtk/scripts/update_res_common.py
import os import sys import stat import re import io import copy import glob import shutil import platform import subprocess ########################### DPI = 'x1' ACTION = 'all' ASSET_C = '' BIN_DIR = '' THEMES = ['default'] ASSETS_ROOT = '' AWTK_ROOT = '' OUTPUT_ROOT = None INPUT_DIR = '' OUTPUT_DIR = '' APP_THEME = 'default' THEME = 'default' THEME_PACKAGED = True IMAGEGEN_OPTIONS = 'bgra+bgr565' LCD_ORIENTATION = '0' LCD_FAST_ROTATION_MODE = False ON_GENERATE_RES_BEFORE = None ON_GENERATE_RES_AFTER = None EXEC_CMD_HANDLER = None IS_EXCLUDED_FILE_HANDLER = None IS_GENERATE_RAW = True IS_GENERATE_INC_RES = True IS_GENERATE_INC_BITMAP = True ASSETS_SUBNAME = '__assets_' STORAGE_DIR = None ########################### OS_NAME = platform.system() def get_action(): return ACTION def set_action(action): global ACTION ACTION = action def get_assets_subname(): return ASSETS_SUBNAME def set_assets_subname(subname): global ASSETS_SUBNAME ASSETS_SUBNAME = subname def get_asset_c(): return ASSET_C def set_asset_c(asset_c): global ASSET_C ASSET_C = asset_c def get_output_root(): return OUTPUT_ROOT def get_assets_root(): return ASSETS_ROOT def on_generate_res_before(handler): global ON_GENERATE_RES_BEFORE ON_GENERATE_RES_BEFORE = handler def on_generate_res_after(handler): global ON_GENERATE_RES_AFTER ON_GENERATE_RES_AFTER = handler def emit_generate_res_before(type): if ON_GENERATE_RES_BEFORE != None: ctx = { 'type': type, 'theme': THEME, 'imagegen_options': IMAGEGEN_OPTIONS, 'lcd_orientation' : LCD_ORIENTATION, 'lcd_fast_rotation_mode' : LCD_FAST_ROTATION_MODE, 'input': INPUT_DIR, 'output': OUTPUT_DIR, 'awtk_root': AWTK_ROOT } ON_GENERATE_RES_BEFORE(ctx) def emit_generate_res_after(type): if ON_GENERATE_RES_AFTER != None: ctx = { 'type': type, 'theme': THEME, 'imagegen_options': IMAGEGEN_OPTIONS, 'lcd_orientation' : LCD_ORIENTATION, 'lcd_fast_rotation_mode' : LCD_FAST_ROTATION_MODE, 'input': INPUT_DIR, 'output': OUTPUT_DIR, 'awtk_root': AWTK_ROOT } ON_GENERATE_RES_AFTER(ctx) def set_is_excluded_file_handler(handler): global IS_EXCLUDED_FILE_HANDLER IS_EXCLUDED_FILE_HANDLER = handler def set_exec_command_handler(handler): global EXEC_CMD_HANDLER EXEC_CMD_HANDLER = handler def set_tools_dir(dir): global BIN_DIR BIN_DIR = dir def set_lcd_rortrail_info(lcd_orientation, lcd_fast_rotation_mode): global LCD_ORIENTATION global LCD_FAST_ROTATION_MODE LCD_ORIENTATION = lcd_orientation LCD_FAST_ROTATION_MODE = lcd_fast_rotation_mode def set_dpi(dpi): global DPI DPI = dpi def set_enable_generate_raw(enable): global IS_GENERATE_RAW IS_GENERATE_RAW = enable def set_enable_generate_inc_res(enable): global IS_GENERATE_INC_RES IS_GENERATE_INC_RES = enable def set_enable_generate_inc_bitmap(enable): global IS_GENERATE_INC_BITMAP IS_GENERATE_INC_BITMAP = enable def set_app_theme(theme): global APP_THEME APP_THEME = theme def set_current_theme(index): global THEME global THEME_PACKAGED global IMAGEGEN_OPTIONS global INPUT_DIR global OUTPUT_DIR global STORAGE_DIR if index >= len(THEMES): return theme = THEMES[index] if isinstance(theme, str): THEME = theme elif isinstance(theme, dict): THEME = theme['name'] THEME_PACKAGED = True IMAGEGEN_OPTIONS = 'bgra+bgr565' if 'imagegen_options' in theme: IMAGEGEN_OPTIONS = theme['imagegen_options'] if 'packaged' in theme: THEME_PACKAGED = theme['packaged'] if 'storage_dir' in theme: STORAGE_DIR = theme['storage_dir'] INPUT_DIR = join_path(ASSETS_ROOT, THEME+'/raw') if not os.path.exists(INPUT_DIR): INPUT_DIR = join_path(ASSETS_ROOT, THEME) OUTPUT_DIR = join_path(OUTPUT_ROOT, THEME) def theme_foreach(visit, ctx = None): for i in range(len(THEMES)): set_current_theme(i) if ctx != None: visit(ctx) else: visit() def get_imagegen_options_of_default_theme(): opt = 'bgra+bgr565' if len(THEMES) > 0: if isinstance(THEMES[0], str): opt = IMAGEGEN_OPTIONS elif isinstance(THEMES[0], dict): for iter in THEMES: if iter['name'] == 'default': if 'imagegen_options' in iter: opt = iter['imagegen_options'] break return opt def is_packaged_of_default_theme(): packaged = True if len(THEMES) > 0: if isinstance(THEMES[0], str): packaged = THEME_PACKAGED elif isinstance(THEMES[0], dict): for iter in THEMES: if iter['name'] == 'default': if 'packaged' in iter: packaged = iter['packaged'] break return packaged def getcwd(): if sys.version_info >= (3, 0): return os.getcwd() else: return os.getcwdu() def to_file_system_coding(s): if sys.version_info >= (3, 0): return s coding = sys.getfilesystemencoding() return s.encode(coding) def join_path(root, subdir): return os.path.normpath(os.path.join(root, subdir)) def make_dirs(path): if not os.path.exists(path): os.makedirs(path) def copy_dir(src, dst): if not os.path.exists(src): print('copy directory: ' + src + ' is not exists.') else: print('copy directory: ' + src + ' ==> ' + dst) shutil.copytree(src, dst) def copy_file(src, dst): if not os.path.exists(src): print('copy file: ' + src + ' is not exists.') else: print('copy file: ' + src + ' ==> ' + dst) shutil.copy(src, dst) def remove_dir(dir): if os.path.isdir(dir): for root, dirs, files in os.walk(dir): for f in files: real_path = join_path(root, f) os.chmod(real_path, stat.S_IRWXU) shutil.rmtree(dir) elif os.path.isfile(dir): os.chmod(dir, stat.S_IRWXU) os.remove(dir) else: print('dir ' + dir + ' not exist') def get_appint_folder_ex(path, regex = '/', folder_list = [], parent = ''): if not os.path.exists(path) or not os.path.isdir(path): return folder_list for f in os.listdir(path): src = join_path(path, f) if os.path.isdir(src) and f != '.' and f != '..': file_path = os.path.join(parent, f) if regex == '/': folder_list.append(tuple((src, file_path))) folder_list = get_appint_folder_ex(src, regex, folder_list, file_path) elif (regex == os.path.splitext(f)[1]): file_path = os.path.join(parent, f) folder_list.append(tuple((src, file_path))) return folder_list def get_appint_folder(path, regex = '/', include_self = True): folder_list = [] regex_list = regex.split("|") if not os.path.exists(path) or not os.path.isdir(path): return folder_list for reg in regex_list: folder_list += get_appint_folder_ex(path, reg, [], '') if include_self == True: folder_list.append(tuple((path, ''))) return folder_list def to_exe(name): if OS_NAME == 'Windows': return join_path(BIN_DIR, name+'.exe') else: return join_path(BIN_DIR, name) def glob_asset_files(path): filename, ext_name = os.path.splitext(path) result = [] dir = os.path.dirname(path) if os.path.isdir(dir): for root, dirs, files in os.walk(dir): for f in files: filename, extname = os.path.splitext(f) if extname == ext_name: result.append(join_path(root, f)) return result def write_file(filename, s): if sys.version_info >= (3, 0): with open(filename, 'w', encoding='utf8') as f: f.write(s) else: with open(filename, 'w') as f: s = s.encode('utf8') f.write(s) def is_excluded_file(filename): return (IS_EXCLUDED_FILE_HANDLER and IS_EXCLUDED_FILE_HANDLER(filename)) def to_asset_const_name(filename, root): basename = '' with io.open(filename, 'r', encoding='utf-8') as file : head = 'TK_CONST_DATA_ALIGN(const unsigned char ' str_tmp = file.readline() basename = str_tmp[len(head):str_tmp.find('[')] return basename.strip() def build_all(): os.system('scons') def exec_cmd(cmd): if EXEC_CMD_HANDLER: EXEC_CMD_HANDLER(cmd) else: print(cmd) # 转为文件系统的编码格式,避免中文乱码 cmd = to_file_system_coding(cmd) # 启动子进程 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) exe_name = cmd.split(' ', 1)[0] out_str = p.communicate()[0] if out_str != None: out_str = out_str.decode('UTF-8') # 将输出信息重新打印到控制台 print(out_str) sys.stdout.flush() # 如果程序出现异常或某个资源打包失败则直接退出 if p.returncode != 0: sys.exit(exe_name + ' exit code:' + str(p.returncode)) if 'gen fail' in out_str: sys.exit(1) def themegen(raw, inc, theme): exec_cmd('\"' + to_exe('themegen') + '\" \"' + raw + '\" \"' + inc + '\" data ' + theme) def themegen_bin(raw, bin): exec_cmd('\"' + to_exe('themegen') + '\" \"' + raw + '\" \"' + bin + '\" bin') def strgen(raw, inc, theme): exec_cmd('\"' + to_exe('strgen') + '\" \"' + raw + '\" \"' + inc + '\" data ' + theme) def strgen_bin(raw, bin): exec_cmd('\"' + to_exe('strgen') + '\" \"' + raw + '\" \"' + bin + '\" bin') def resgen(raw, inc, theme, outExtname): exec_cmd('\"' + to_exe('resgen') + '\" \"' + raw + '\" \"' + inc + '\" ' + theme + ' ' + outExtname) def fontgen(raw, text, inc, size, options, theme): fontgenName = 'fontgen' if options == 'mono' and os.path.exists(to_exe('fontgen_ft')): fontgenName = 'fontgen_ft' exec_cmd('\"' + to_exe(fontgenName) + '\" \"' + raw + '\" \"' + text + '\" \"' + inc + '\" ' + str(size) + ' ' + options + ' ' + theme) def imagegen(raw, inc, options, theme, lcd_orientation, lcd_fast_rotation_mode): if not lcd_fast_rotation_mode : lcd_orientation = '0' exec_cmd('\"' + to_exe('imagegen') + '\" \"' + raw + '\" \"' + inc + '\" ' + options + ' ' + theme + ' ' + lcd_orientation) def svggen(raw, inc, theme): exec_cmd('\"' + to_exe('bsvggen') + '\" \"' + raw + '\" \"' + inc + '\" data ' + theme) def svggen_bin(raw, bin): exec_cmd('\"' + to_exe('bsvggen') + '\" \"' + raw + '\" \"' + bin + '\" bin') def xml_to_ui(raw, inc, theme): exec_cmd('\"' + to_exe('xml_to_ui') + '\" \"' + raw + '\" \"' + inc + '\" data \"\" ' + theme) def xml_to_ui_bin(raw, bin): exec_cmd('\"' + to_exe('xml_to_ui') + '\" \"' + raw + '\" \"' + bin + '\" bin') def gen_res_all_style(): if not THEME_PACKAGED and THEME != 'default': return raw = join_path(INPUT_DIR, 'styles') if not os.path.exists(raw): return emit_generate_res_before('style') if IS_GENERATE_RAW: bin = join_path(OUTPUT_DIR, 'raw/styles') make_dirs(bin) themegen_bin(raw, bin) if IS_GENERATE_INC_RES or IS_GENERATE_INC_BITMAP: inc = join_path(OUTPUT_DIR, 'inc/styles') make_dirs(inc) themegen(raw, inc, THEME) emit_generate_res_after('style') def gen_res_svg(): raw = join_path(INPUT_DIR, 'images/svg') if not os.path.exists(raw): return if IS_GENERATE_RAW: bin = join_path(OUTPUT_DIR, 'raw/images/svg') make_dirs(bin) svggen_bin(raw, bin) if IS_GENERATE_INC_RES or IS_GENERATE_INC_BITMAP: inc = join_path(OUTPUT_DIR, 'inc/images') make_dirs(inc) svggen(raw, inc, THEME) def gen_res_png_jpg(): if IS_GENERATE_RAW: if INPUT_DIR != join_path(OUTPUT_DIR, 'raw'): dirs = ['xx', 'x1', 'x2', 'x3'] for d in dirs: raw = join_path(INPUT_DIR, 'images/'+d) if os.path.exists(raw): dst = join_path(OUTPUT_DIR, 'raw/images/'+d) if os.path.exists(dst): remove_dir(dst) copy_dir(raw, dst) if IS_GENERATE_INC_RES or IS_GENERATE_INC_BITMAP: inc = join_path(OUTPUT_DIR, 'inc/images') dirs = [DPI, 'xx'] for d in dirs: raw = join_path(INPUT_DIR, 'images/'+d) if os.path.exists(raw): make_dirs(inc) if IS_GENERATE_INC_RES: resgen(raw, inc, THEME, '.res') if IS_GENERATE_INC_BITMAP: imagegen(raw, inc, IMAGEGEN_OPTIONS, THEME, LCD_ORIENTATION, LCD_FAST_ROTATION_MODE) # 如果当前主题的gen选项与default主题不一致,则按新的gen选项重新生成图片的位图数据 if IS_GENERATE_INC_BITMAP and THEME != 'default': if get_imagegen_options_of_default_theme() != IMAGEGEN_OPTIONS: for d in dirs: raw = join_path(ASSETS_ROOT, 'default/raw') if not os.path.exists(raw): raw = join_path(ASSETS_ROOT, 'default') raw = join_path(raw, 'images/'+d) if os.path.exists(raw): make_dirs(inc) imagegen(raw, inc, IMAGEGEN_OPTIONS, THEME, LCD_ORIENTATION, LCD_FAST_ROTATION_MODE) def gen_res_all_image(): if not THEME_PACKAGED and THEME != 'default': return emit_generate_res_before('image') gen_res_png_jpg() gen_res_svg() emit_generate_res_after('image') def gen_res_all_ui(): if not THEME_PACKAGED and THEME != 'default': return raw = join_path(INPUT_DIR, 'ui') if not os.path.exists(raw): return emit_generate_res_before('ui') if IS_GENERATE_RAW: bin = join_path(OUTPUT_DIR, 'raw/ui') make_dirs(bin) xml_to_ui_bin(raw, bin) if IS_GENERATE_INC_RES or IS_GENERATE_INC_BITMAP: inc = join_path(OUTPUT_DIR, 'inc/ui') make_dirs(inc) xml_to_ui(raw, inc, THEME) emit_generate_res_after('ui') def gen_res_all_data(): if not THEME_PACKAGED and THEME != 'default': return raw = join_path(INPUT_DIR, 'data') if not os.path.exists(raw): return emit_generate_res_before('data') if IS_GENERATE_RAW: if INPUT_DIR != join_path(OUTPUT_DIR, 'raw'): dst = join_path(OUTPUT_DIR, 'raw/data') if os.path.exists(dst): remove_dir(dst) copy_dir(raw, dst) if IS_GENERATE_INC_RES or IS_GENERATE_INC_BITMAP: inc = join_path(OUTPUT_DIR, 'inc/data') make_dirs(inc) resgen(raw, inc, THEME, '.data') emit_generate_res_after('data') def gen_res_all_flows(): if not THEME_PACKAGED and THEME != 'default': return raw = join_path(INPUT_DIR, 'flows') if not os.path.exists(raw): return emit_generate_res_before('flows') if IS_GENERATE_RAW: if INPUT_DIR != join_path(OUTPUT_DIR, 'raw'): dst = join_path(OUTPUT_DIR, 'raw/flows') if os.path.exists(dst): remove_dir(dst) copy_dir(raw, dst) if IS_GENERATE_INC_RES or IS_GENERATE_INC_BITMAP: inc = join_path(OUTPUT_DIR, 'inc/flows') make_dirs(inc) resgen(raw, inc, THEME, '.flows') emit_generate_res_after('flows') def gen_res_all_xml(): if not THEME_PACKAGED and THEME != 'default': return raw = join_path(INPUT_DIR, 'xml') if not os.path.exists(raw): return emit_generate_res_before('xml') if IS_GENERATE_RAW: if INPUT_DIR != join_path(OUTPUT_DIR, 'raw'): dst = join_path(OUTPUT_DIR, 'raw/xml') if os.path.exists(dst): remove_dir(dst) copy_dir(raw, dst) if IS_GENERATE_INC_RES or IS_GENERATE_INC_BITMAP: inc = join_path(OUTPUT_DIR, 'inc/xml') make_dirs(inc) resgen(raw, inc, THEME, '.data') emit_generate_res_after('xml') def gen_res_bitmap_font(input_dir, font_options, theme): if STORAGE_DIR: input_dir = join_path(STORAGE_DIR, theme) if not os.path.exists(join_path(input_dir, 'fonts/config')): return for f in glob.glob(join_path(input_dir, 'fonts/config/*.txt')): filename, extname = os.path.splitext(f) fontname = os.path.basename(filename) index = fontname.rfind('_') if index > 0: raw = join_path(input_dir, 'fonts') + '/origin/' + fontname[0: index] + '.ttf' if not os.path.exists(raw): raw = os.path.dirname(os.path.dirname(filename)) + '/' + fontname[0: index] + '.ttf' if os.path.exists(raw): size = fontname[index + 1 : len(fontname)] if size.isdigit(): inc = join_path(OUTPUT_DIR, 'inc/fonts/' + fontname[0: index] + '_' + str(size) + '.data') fontgen(raw, f, inc, size, font_options, theme) def gen_res_all_font(): if not THEME_PACKAGED and THEME != 'default': return emit_generate_res_before('font') if IS_GENERATE_RAW: if INPUT_DIR != join_path(OUTPUT_DIR, 'raw'): make_dirs(join_path(OUTPUT_DIR, 'raw/fonts')) in_files = join_path(INPUT_DIR, 'fonts/') for f in get_appint_folder(in_files, '.ttf', False): out_files = f[0].replace(INPUT_DIR, join_path(OUTPUT_DIR, 'raw')) out_foler = os.path.dirname(out_files) if 'origin' in out_foler: continue if not os.path.exists(out_foler): make_dirs(out_foler) copy_file(f[0], out_files) if IS_GENERATE_INC_RES or IS_GENERATE_INC_BITMAP: inc_dir = join_path(OUTPUT_DIR, 'inc/fonts') make_dirs(inc_dir) if IS_GENERATE_INC_BITMAP: font_options = 'none' if IMAGEGEN_OPTIONS == 'mono': font_options = 'mono' # 位图字体的保留设置在fonts/config目录中,比如default_18.txt中设置default字体18字号的保留字符 gen_res_bitmap_font(INPUT_DIR, font_options, THEME) if THEME != 'default': # 如果当前主题的gen选项与default主题不同时为mono,则按新的gen选项重新生成位图字体 opt = get_imagegen_options_of_default_theme() if (opt == 'mono' or IMAGEGEN_OPTIONS == 'mono') and opt != IMAGEGEN_OPTIONS: input_dir = join_path(ASSETS_ROOT, 'default/raw') if not os.path.exists(input_dir): input_dir = join_path(ASSETS_ROOT, 'default') gen_res_bitmap_font(input_dir, font_options, THEME) # 对default_full的特殊处理,兼容awtk的demos IS_AWTK_DEMO = False if os.path.exists('scripts/update_res_common.py'): IS_AWTK_DEMO = True raw = join_path(INPUT_DIR, 'fonts/default_full.ttf') if IS_AWTK_DEMO and os.path.exists(raw): text = join_path(INPUT_DIR, 'fonts/text.txt') if os.path.exists(text): fontsizes = [16, 18, 20, 24, 32, 96] for size in fontsizes: inc = join_path(OUTPUT_DIR, 'inc/fonts/default_%d.data' % size) fontgen(raw, text, inc, size, font_options, THEME) if IS_GENERATE_INC_RES: if not os.path.exists(join_path(INPUT_DIR, 'fonts')): return for f in get_appint_folder(join_path(INPUT_DIR, 'fonts/'), ".ttf", False): filename, extname = os.path.splitext(f[0]) raw = f[0] filename = filename.replace(INPUT_DIR, join_path(OUTPUT_DIR, 'inc')) inc = filename + '.res' if "origin" in inc: continue resgen(raw, inc, THEME, '.res') emit_generate_res_after('font') def gen_res_all_script(): if not THEME_PACKAGED and THEME != 'default': return raw = join_path(INPUT_DIR, 'scripts') if not os.path.exists(raw): return emit_generate_res_before('script') if IS_GENERATE_RAW: if INPUT_DIR != join_path(OUTPUT_DIR, 'raw'): dst = join_path(OUTPUT_DIR, 'raw/scripts') if os.path.exists(dst): remove_dir(dst) copy_dir(raw, dst) if IS_GENERATE_INC_RES or IS_GENERATE_INC_BITMAP: inc = join_path(OUTPUT_DIR, 'inc/scripts') make_dirs(inc) resgen(raw, inc, THEME, '.res') emit_generate_res_after('script') def gen_res_all_string(): if not THEME_PACKAGED and THEME != 'default': return raw = join_path(INPUT_DIR, 'strings') if not os.path.exists(raw): return emit_generate_res_before('string') if IS_GENERATE_RAW: bin = join_path(OUTPUT_DIR, 'raw/strings') make_dirs(bin) strgen_bin(raw, bin) if IS_GENERATE_INC_RES or IS_GENERATE_INC_BITMAP: inc = join_path(OUTPUT_DIR, 'inc/strings') make_dirs(inc) strgen(raw, inc, THEME) emit_generate_res_after('string') def gen_gpinyin(): emit_generate_res_before('gpinyin') exec_cmd('\"' + to_exe('resgen') + '\" \"' + join_path('3rd', 'gpinyin/data/gpinyin.dat') + '\" \"' + join_path('3rd', 'gpinyin/src/gpinyin.inc') + '\"') exec_cmd('\"' + to_exe('resgen') + '\" ' + join_path('tools', 'word_gen/words.bin') + '\" \"' + join_path('src', 'input_methods/suggest_words.inc') + '\"') exec_cmd('\"' + to_exe('resgen') + '\" \"' + join_path('tools','word_gen/words.bin') + '\" \"' + join_path('tests', 'suggest_test.inc') + '\"') emit_generate_res_after('gpinyin') def gen_res_all(): print('=========================================================') emit_generate_res_before('all') gen_res_all_string() gen_res_all_font() gen_res_all_script() gen_res_all_image() gen_res_all_ui() gen_res_all_style() gen_res_all_data() gen_res_all_flows() gen_res_all_xml() emit_generate_res_after('all') print('=========================================================') def gen_includes(files, inherited, with_multi_theme): result = "" if with_multi_theme: remove = OUTPUT_ROOT else: remove = os.path.dirname(OUTPUT_ROOT) for f in files: if is_excluded_file(f): continue if inherited: filename = f.replace(join_path(OUTPUT_ROOT, 'default'), join_path(OUTPUT_ROOT, THEME)) if os.path.exists(filename): continue incf = copy.copy(f) incf = incf.replace(remove, ".") incf = incf.replace('\\', '/') incf = incf.replace('./', '') result += '#include "'+incf+'"\n' return result def gen_extern_declares(files): result = "" for f in files: if is_excluded_file(f): continue filename = f.replace(join_path(OUTPUT_ROOT, 'default'), join_path(OUTPUT_ROOT, THEME)) if not os.path.exists(filename): constname = to_asset_const_name(f, join_path(OUTPUT_ROOT, 'default/inc')) result += 'extern TK_CONST_DATA_ALIGN(const unsigned char '+constname+'[]);\n' return result def gen_assets_includes(curr_theme_path, defl_theme_path = None, with_multi_theme = True): files = glob_asset_files(curr_theme_path) result = gen_includes(files, False, with_multi_theme) if defl_theme_path != None and THEME != 'default': files = glob_asset_files(defl_theme_path) if with_multi_theme and is_packaged_of_default_theme(): result += gen_extern_declares(files) else: result += gen_includes(files, True, with_multi_theme) return result def gen_assets_add(filename, is_default_theme): if is_default_theme: constname = to_asset_const_name(filename, join_path(OUTPUT_ROOT, 'default/inc')) return ' assets_manager_add(am, '+constname+');\n' else: constname = to_asset_const_name(filename, join_path(OUTPUT_DIR, 'inc')) return ' assets_manager_add(am, '+constname+');\n' def gen_assets_adds(curr_theme_path, defl_theme_path = None): result = "" is_default_theme = THEME == 'default' files = glob_asset_files(curr_theme_path) for f in files: if is_excluded_file(f): continue result += gen_assets_add(f, is_default_theme) if defl_theme_path != None and not is_default_theme: files = glob_asset_files(defl_theme_path) for f in files: if is_excluded_file(f): continue filename = f.replace(join_path(OUTPUT_ROOT, 'default'), join_path(OUTPUT_ROOT, THEME)) if not os.path.exists(filename): result += gen_assets_add(f, True) return result def gen_assets_c_of_one_theme(with_multi_theme = True): if not THEME_PACKAGED: return if with_multi_theme: filename = join_path(OUTPUT_ROOT, ASSETS_SUBNAME+THEME+'.inc') else: filename, extname = os.path.splitext(ASSET_C) filename = filename + '_' + THEME + extname func_name = 'assets_init' if with_multi_theme: func_name = 'assets_init_'+THEME result = '#include "awtk.h"\n' result += '#include "base/assets_manager.h"\n' result += '#if !defined(WITH_FS_RES) || defined(AWTK_WEB)\n' result += gen_assets_includes(join_path(OUTPUT_DIR, 'inc/strings/*.data'), join_path(OUTPUT_ROOT, 'default/inc/strings/*.data'), with_multi_theme) result += gen_assets_includes(join_path(OUTPUT_DIR, 'inc/styles/*.data'), join_path(OUTPUT_ROOT, 'default/inc/styles/*.data'), with_multi_theme) result += gen_assets_includes(join_path(OUTPUT_DIR, 'inc/ui/*.data'), join_path(OUTPUT_ROOT, 'default/inc/ui/*.data'), with_multi_theme) result += gen_assets_includes(join_path(OUTPUT_DIR, 'inc/xml/*.data'), join_path(OUTPUT_ROOT, 'default/inc/xml/*.data'), with_multi_theme) result += gen_assets_includes(join_path(OUTPUT_DIR, 'inc/data/*.data'), join_path(OUTPUT_ROOT, 'default/inc/data/*.data'), with_multi_theme) result += gen_assets_includes(join_path(OUTPUT_DIR, 'inc/flows/*.flows'), join_path(OUTPUT_ROOT, 'default/inc/flows/*.flows'), with_multi_theme) result += "#ifndef AWTK_WEB\n" result += "#ifdef WITH_STB_IMAGE\n" result += gen_assets_includes(join_path(OUTPUT_DIR, 'inc/images/*.res'), join_path(OUTPUT_ROOT, 'default/inc/images/*.res'), with_multi_theme) result += "#else /*WITH_STB_IMAGE*/\n" result += gen_assets_includes(join_path(OUTPUT_DIR, 'inc/images/*.data'), join_path(OUTPUT_ROOT, 'default/inc/images/*.data'), with_multi_theme) result += '#endif /*WITH_STB_IMAGE*/\n' result += "#ifdef WITH_TRUETYPE_FONT\n" result += gen_assets_includes(join_path(OUTPUT_DIR, 'inc/fonts/*.res'), join_path(OUTPUT_ROOT, 'default/inc/fonts/*.res'), with_multi_theme) result += "#else /*WITH_TRUETYPE_FONT*/\n" result += gen_assets_includes(join_path(OUTPUT_DIR, 'inc/fonts/*.data'), join_path(OUTPUT_ROOT, 'default/inc/fonts/*.data'), with_multi_theme) result += '#endif /*WITH_TRUETYPE_FONT*/\n' result += gen_assets_includes(join_path(OUTPUT_DIR, 'inc/scripts/*.res'), join_path(OUTPUT_ROOT, 'default/inc/scripts/*.res'), with_multi_theme) result += '#endif /*AWTK_WEB*/\n' result += "#ifdef WITH_VGCANVAS\n" result += gen_assets_includes(join_path(OUTPUT_DIR, 'inc/images/*.bsvg'), join_path(OUTPUT_ROOT, 'default/inc/images/*.bsvg'), with_multi_theme) result += '#endif /*WITH_VGCANVAS*/\n' result += '#endif /*!defined(WITH_FS_RES) || defined(AWTK_WEB)*/\n' result += '\n' result += 'ret_t ' + func_name + '(void) {\n' result += ' assets_manager_t* am = assets_manager();\n' result += ' assets_manager_set_theme(am, "' + THEME + '");\n' result += '\n' result += '#if defined(WITH_FS_RES) && !defined(AWTK_WEB)\n' result += ' assets_manager_preload(am, ASSET_TYPE_STYLE, "default");\n' result += '#else /*defined(WITH_FS_RES) && !defined(AWTK_WEB)*/\n' result += gen_assets_adds(join_path(OUTPUT_DIR, 'inc/strings/*.data'), join_path(OUTPUT_ROOT, 'default/inc/strings/*.data')) result += gen_assets_adds(join_path(OUTPUT_DIR, 'inc/styles/*.data'), join_path(OUTPUT_ROOT, 'default/inc/styles/*.data')) result += gen_assets_adds(join_path(OUTPUT_DIR, 'inc/ui/*.data'), join_path(OUTPUT_ROOT, 'default/inc/ui/*.data')) result += gen_assets_adds(join_path(OUTPUT_DIR, 'inc/xml/*.data'), join_path(OUTPUT_ROOT, 'default/inc/xml/*.data')) result += gen_assets_adds(join_path(OUTPUT_DIR, 'inc/data/*.data'), join_path(OUTPUT_ROOT, 'default/inc/data/*.data')) result += gen_assets_adds(join_path(OUTPUT_DIR, 'inc/flows/*.flows'), join_path(OUTPUT_ROOT, 'default/inc/flows/*.flows')) result += '#ifndef AWTK_WEB\n' if IS_GENERATE_INC_RES: result += gen_assets_adds(join_path(OUTPUT_DIR, 'inc/images/*.res'), join_path(OUTPUT_ROOT, 'default/inc/images/*.res')) else: result += gen_assets_adds(join_path(OUTPUT_DIR, 'inc/images/*.data'), join_path(OUTPUT_ROOT, 'default/inc/images/*.data')) result += "#ifdef WITH_TRUETYPE_FONT\n" result += gen_assets_adds(join_path(OUTPUT_DIR, 'inc/fonts/*.res'), join_path(OUTPUT_ROOT, 'default/inc/fonts/*.res')) result += "#else /*WITH_TRUETYPE_FONT*/\n" result += gen_assets_adds(join_path(OUTPUT_DIR, 'inc/fonts/*.data'), join_path(OUTPUT_ROOT, 'default/inc/fonts/*.data')) result += '#endif /*WITH_TRUETYPE_FONT*/\n' result += gen_assets_adds(join_path(OUTPUT_DIR, 'inc/scripts/*.res'), join_path(OUTPUT_ROOT, 'default/inc/scripts/*.res')) result += '#endif /*AWTK_WEB*/\n' result += "#ifdef WITH_VGCANVAS\n" result += gen_assets_adds(join_path(OUTPUT_DIR, 'inc/images/*.bsvg'), join_path(OUTPUT_ROOT, 'default/inc/images/*.bsvg')) result += '#endif /*WITH_VGCANVAS*/\n' result += '#endif /*defined(WITH_FS_RES) && !defined(AWTK_WEB)*/\n' result += '\n' result += ' tk_init_assets();\n' result += ' return RET_OK;\n' result += '}\n' write_file(filename, result) def gen_asset_c_entry_with_multi_theme(): result = '#include "awtk.h"\n' result += '#include "base/assets_manager.h"\n' assets_root = os.path.relpath(OUTPUT_ROOT, os.path.dirname(ASSET_C)).replace('\\', '/') for i in range(len(THEMES)): set_current_theme(i) if THEME_PACKAGED: result += '#include "'+assets_root+'/'+ASSETS_SUBNAME+THEME+'.inc"\n' result += '\n' result += '#ifndef APP_THEME\n' result += '#define APP_THEME "' + APP_THEME + '"\n' result += '#endif /*APP_THEME*/\n\n' result += 'bool_t assets_has_theme(const char* name) {\n' result += ' return_value_if_fail(name != NULL, FALSE);\n\n' result += ' ' for i in range(len(THEMES)): set_current_theme(i) if THEME_PACKAGED: result += 'if (tk_str_eq(name, "'+THEME+'")) {\n' result += ' return TRUE;\n' result += ' } else ' result += '{\n' result += ' return FALSE;\n }\n}\n\n' result += 'static ret_t assets_init_internal(const char* theme) {\n' result += ' assets_manager_t* am = assets_manager();\n' result += ' return_value_if_fail(theme != NULL && am != NULL, RET_BAD_PARAMS);\n\n' result += ' assets_manager_set_theme(am, theme);\n\n' result += ' ' for i in range(len(THEMES)): set_current_theme(i) if THEME_PACKAGED: result += 'if (tk_str_eq(theme, "'+THEME+'")) {\n' result += ' return assets_init_'+THEME+'();\n' result += ' } else ' result += '{\n' result += ' log_debug(\"%s not support.\\n\", theme);\n' result += ' return RET_NOT_IMPL;\n }\n}\n\n' result += '#if !defined(WITH_FS_RES) || defined(AWTK_WEB)\n' result += 'static ret_t widget_set_theme_without_file_system(widget_t* widget, const char* name) {\n' result += ' const asset_info_t* info = NULL;\n' result += ' event_t e = event_init(EVT_THEME_CHANGED, NULL);\n' result += ' widget_t* wm = widget_get_window_manager(widget);\n' result += ' font_manager_t* fm = widget_get_font_manager(widget);\n' result += ' image_manager_t* imm = widget_get_image_manager(widget);\n' result += ' assets_manager_t* am = widget_get_assets_manager(widget);\n' result += ' locale_info_t* locale_info = widget_get_locale_info(widget);\n\n' result += ' return_value_if_fail(am != NULL && name != NULL, RET_BAD_PARAMS);\n' result += ' return_value_if_fail(assets_has_theme(name), RET_BAD_PARAMS);\n\n' result += ' font_manager_unload_all(fm);\n' result += ' image_manager_unload_all(imm);\n' result += ' assets_manager_clear_all(am);\n' result += ' widget_reset_canvas(widget);\n\n' result += ' assets_init_internal(name);\n' result += ' locale_info_reload(locale_info);\n\n' result += ' info = assets_manager_ref(am, ASSET_TYPE_STYLE, "default");\n' result += ' theme_set_theme_data(theme(), info->data);\n' result += ' assets_manager_unref(assets_manager(), info);\n\n' result += ' widget_dispatch(wm, &e);\n' result += ' widget_invalidate_force(wm, NULL);\n\n' result += ' log_debug("theme changed: %s\\n", name);\n\n' result += ' return RET_OK;\n' result += '}\n\n' result += 'static ret_t on_set_theme_without_file_system(void* ctx, event_t* e) {\n' result += ' theme_change_event_t* evt = theme_change_event_cast(e);\n' result += ' widget_set_theme_without_file_system(window_manager(), evt->name);\n' result += ' return RET_OK;\n' result += '}\n' result += '#endif /*!defined(WITH_FS_RES) || defined(AWTK_WEB)*/\n\n' result += 'ret_t assets_init(void) {\n' result += '#if !defined(WITH_FS_RES) || defined(AWTK_WEB)\n' result += ' widget_on(window_manager(), EVT_THEME_WILL_CHANGE, on_set_theme_without_file_system, NULL);\n' result += '#endif /*!defined(WITH_FS_RES) || defined(AWTK_WEB)*/\n' result += ' return assets_init_internal(APP_THEME);\n}\n\n' result += 'ret_t assets_set_global_theme(const char* name) {\n' result += ' return widget_set_theme(window_manager(), name);\n' result += '}\n' write_file(ASSET_C, result) def gen_res_c(with_multi_theme = True): theme_foreach(gen_assets_c_of_one_theme, with_multi_theme) if with_multi_theme: gen_asset_c_entry_with_multi_theme() def gen_res_json_one(res_type, files): result = '' for f in files: uri = f.replace(os.getcwd(), "")[1:] uri = uri.replace('\\', '/') filename, extname = os.path.splitext(uri) basename = os.path.basename(filename) result = result + ' {name:"' + basename + '\", uri:"' + uri if res_type == 'image' and extname != '.svg' and extname != '.bsvg': from PIL import Image img = Image.open(f) w, h = img.size result = result + '", w:' + str(w) + ', h:' + str(h) + '},\n' else: result = result + '"},\n' return result def gen_res_json_all_theme(res_type, sub_filepath): result = "\n " + res_type + ': [\n' for i in range(len(THEMES)): set_current_theme(i) files = glob.glob(join_path(INPUT_DIR, sub_filepath)) result += gen_res_json_one(res_type, files) result += ' ],' return result def gen_res_json(): result = 'const g_awtk_assets = {' result += gen_res_json_all_theme("image", 'images/*/*.*') result += gen_res_json_all_theme("ui", 'ui/*.bin') result += gen_res_json_all_theme("style",'styles/*.bin') result += gen_res_json_all_theme("string", 'strings/*.bin') result += gen_res_json_all_theme("xml", 'xml/*.xml') result += gen_res_json_all_theme("data", 'data/*.*') result += gen_res_json_all_theme("script", 'scripts/*.*') result += gen_res_json_all_theme("font", 'fonts/*.ttf') result += '\n};\n' write_file(ASSET_C.replace('.c', '_web.js'), result) def init(awtk_root, assets_root, themes, asset_c, output = None): global THEMES global ASSET_C global BIN_DIR global ASSETS_ROOT global AWTK_ROOT global OUTPUT_ROOT ASSET_C = asset_c AWTK_ROOT = awtk_root ASSETS_ROOT = assets_root BIN_DIR = join_path(AWTK_ROOT, 'bin') if output != None: OUTPUT_ROOT = output else: OUTPUT_ROOT = ASSETS_ROOT if isinstance(themes, str): THEMES = [themes] else: THEMES = themes set_current_theme(0) def dump_args(): print('---------------------------------------------------------') print('DPI = '+DPI) print('THEMES = '+str(THEMES)) print('IMAGEGEN_OPTIONS = '+IMAGEGEN_OPTIONS) print('LCD_FAST_ROTATION_MODE = '+str(LCD_FAST_ROTATION_MODE)) print('LCD_ORIENTATION = LCD_ORIENTATION_'+LCD_ORIENTATION) print('AWTK_ROOT = '+AWTK_ROOT) print('BIN_DIR = '+BIN_DIR) print('ASSETS_ROOT = '+ASSETS_ROOT) print('ASSET_C = '+ASSET_C) print('OUTPUT = '+OUTPUT_ROOT) def update_res(): if ACTION == 'all': clean_res() theme_foreach(gen_res_all) gen_res_c() elif ACTION == 'res': clean_res() theme_foreach(gen_res_all) elif ACTION == 'clean': clean_res() elif ACTION == 'web': gen_res_c() elif ACTION == 'json': gen_res_json() elif ACTION == 'string': theme_foreach(gen_res_all_string) gen_res_c() elif ACTION == "font": theme_foreach(gen_res_all_font) gen_res_c() elif ACTION == "script": theme_foreach(gen_res_all_script) gen_res_c() elif ACTION == 'image': theme_foreach(gen_res_all_image) gen_res_c() elif ACTION == 'ui': theme_foreach(gen_res_all_ui) gen_res_c() elif ACTION == 'style': theme_foreach(gen_res_all_style) gen_res_c() elif ACTION == 'data': theme_foreach(gen_res_all_data) gen_res_c() elif ACTION == 'flows': theme_foreach(gen_res_all_flows) gen_res_c() elif ACTION == 'xml': theme_foreach(gen_res_all_xml) gen_res_c() elif ACTION == 'pinyin': gen_gpinyin() elif ACTION == 'assets.c': gen_res_c() dump_args() def clean_res_bin(dir): if os.path.isdir(dir): for root, dirs, files in os.walk(dir): for f in files: filename, extname = os.path.splitext(f) if extname == '.bin' or extname == '.bsvg': real_path = join_path(root, f) os.chmod(real_path, stat.S_IRWXU) os.remove(real_path) def clean_res_of_one_theme(): print('clean res: ' + OUTPUT_DIR) clean_res_bin(join_path(OUTPUT_DIR, 'raw/ui')) clean_res_bin(join_path(OUTPUT_DIR, 'raw/images/svg')) clean_res_bin(join_path(OUTPUT_DIR, 'raw/strings')) clean_res_bin(join_path(OUTPUT_DIR, 'raw/styles')) remove_dir(join_path(OUTPUT_DIR, 'inc')) remove_dir(join_path(OUTPUT_ROOT, ASSETS_SUBNAME+THEME+'.inc')) def clean_res(): print('=========================================================') if ASSETS_ROOT != OUTPUT_ROOT: dir = os.path.dirname(OUTPUT_ROOT) print('clean res: ' + dir) remove_dir(dir) else: theme_foreach(clean_res_of_one_theme) remove_dir(ASSET_C) print('=========================================================') def get_args(args) : list_args = [] for arg in args: if arg.startswith('--') : continue list_args.append(arg) return list_args def get_opts(args) : import getopt longsots = ['awtk_root=', 'AWTK_ROOT=', 'action=', 'ACTION=', 'help', 'HELP', 'dpi=', 'DPI=', 'image_options=', 'IMAGE_OPTIONS=', 'lcd_orientation=', 'LCD_ORIENTATION=', 'lcd_enable_fast_rotation=', 'LCD_ENABLE_FAST_ROTATION=', 'res_config_file=', 'RES_CONFIG_FILE=', 'res_config_script=', 'RES_CONFIG_SCRIPT=', 'res_config_script_argv=', 'RES_CONFIG_SCRIPT_ARGV=', 'output_dir=', 'OUTPUT_DIR=', 'app_root=', 'APP_ROOT', ]; try : opts, tmp_args = getopt.getopt(args, 'h', longsots); return opts; except getopt.GetoptError as err: print(err.msg); return None; def is_all_sopts_args(args) : for arg in args: if not arg.startswith('--') and not arg.startswith('-'): return False; return True; def get_longsopt_name_by_tuple(tuple) : return tuple[0][2:].lower(); def get_shortopt_name_by_tuple(tuple) : return tuple[0][1:].lower(); def get_longsopts_args(args) : opts = get_opts(args); if opts != None : data = {}; for tmp_opts in opts : value = tmp_opts[1] if isinstance(value, str) and value[0] == '"' and value[-1] == '"' : value = value[1:-1] data[get_longsopt_name_by_tuple(tmp_opts)] = value return data; else : return None; def show_usage_imlp(is_new_usage): if is_new_usage : print('=========================================================') print('Usage: python '+sys.argv[0]) print('--action :'.ljust(30) + ' update res action, this sopt must set ') print(''.ljust(30) + ' use : --action=clean|web|json|all|font|image|ui|style|string|script|data|xml|assets.c') print(''.ljust(30) + ' clean'.ljust(10) +': clear res') print(''.ljust(30) + ' all'.ljust(10) +': update all res') print(''.ljust(30) + ' web'.ljust(10) +': update web res') print(''.ljust(30) + ' json'.ljust(10) +': only update json res') print(''.ljust(30) + ' font'.ljust(10) +': only update font res') print(''.ljust(30) + ' image'.ljust(10) +': only update image res') print(''.ljust(30) + ' ui'.ljust(10) +': only update ui res') print(''.ljust(30) + ' style'.ljust(10) +': only update style res') print(''.ljust(30) + ' string'.ljust(10) +': only update translator string res') print(''.ljust(30) + ' script'.ljust(10) +': only update script res') print(''.ljust(30) + ' data'.ljust(10) +': only update data res') print(''.ljust(30) + ' xml'.ljust(10) +': only update xml res') print(''.ljust(30) + ' assets.c'.ljust(10) +': only update assets.c file') print('--awtk_root :'.ljust(30) + ' set awtk root') print(''.ljust(30) + ' use : --awtk_root=XXXXX') print('--dpi :'.ljust(30) + ' set update res dpi') print(''.ljust(30) + ' use : --dpi=x1|x2|x3') print('--image_options :'.ljust(30) + ' set image foramt') print(''.ljust(30) + ' use : --image_options=rgba|bgra+bgr565|mono') print('--res_config_file :'.ljust(30) + ' set res config file path, priority : res_config_script > res_config_file') print(''.ljust(30) + ' use : --res_config_file=XXXXX') print('--res_config_script :'.ljust(30) + ' set res config script file path, this is script must has get_res_config(argv) function ') print(''.ljust(30) + ' use : --res_config_script=XXXXX') print('--res_config_script_argv :'.ljust(30) + ' set res config script argv, this is get_res_config() function parameter') print(''.ljust(30) + ' use : --res_config_script_argv=XXXXX') print('--lcd_orientation :'.ljust(30) + ' set lcd orientation ') print(''.ljust(30) + ' use : --lcd_orientation=90/180/270') print('--lcd_enable_fast_rotation :'.ljust(30) + ' set enable lcd fast rotation ') print(''.ljust(30) + ' use : --lcd_enable_fast_rotation=true/false') print('--output_dir :'.ljust(30) + ' set res output dir, default value is ./res ') print(''.ljust(30) + ' use : --output_dir=XXXXX') print('--app_root :'.ljust(30) + ' set app root dir, default value is getcwd() ') print(''.ljust(30) + ' use : --app_root=XXXXX') print('--help :'.ljust(30) + ' show all usage ') print(''.ljust(30) + ' use : --help') print('---------------------------------------------------------') print('Example:') print('python ' + sys.argv[0] + ' --action=all') print('python ' + sys.argv[0] + ' --action=clean') print('python ' + sys.argv[0] + ' --action=style --awtk_root=XXXXX ') print('python ' + sys.argv[0] + ' --action=all --dpi=x1 --image_options=bgra+bgr565') print('python ' + sys.argv[0] + ' --action=all --dpi=x1 --image_options=bgra+bgr565 --awtk_root=XXXXX') print('=========================================================') else : args = ' action[clean|web|json|all|font|image|ui|style|string|script|data|xml|assets.c] dpi[x1|x2] image_options[rgba|bgra+bgr565|mono] awtk_root[--awtk_root=XXXXX]' print('=========================================================') print('Usage: python '+sys.argv[0] + args) print('Example:') print('python ' + sys.argv[0] + ' all') print('python ' + sys.argv[0] + ' clean') print('python ' + sys.argv[0] + ' style --awtk_root=XXXXX ') print('python ' + sys.argv[0] + ' all x1 bgra+bgr565') print('python ' + sys.argv[0] + ' all x1 bgra+bgr565 --awtk_root=XXXXX') print('=========================================================') if exit : sys.exit(0) def show_usage(is_new_usage = False): if len(sys.argv) == 1: show_usage_imlp(is_new_usage) else: args = sys.argv[1:]; if is_all_sopts_args(args) : opts = get_opts(args); if opts == None : show_usage_imlp(is_new_usage) else : find_action = False; for tmp_opts in opts : str_opt = get_longsopt_name_by_tuple(tmp_opts); if str_opt == 'help' or get_shortopt_name_by_tuple(tmp_opts) == 'h': show_usage_imlp(is_new_usage) elif str_opt == 'action' : find_action = True; if not find_action : show_usage_imlp(is_new_usage) else : sys_args = get_args(args) if len(sys_args) == 0 : show_usage_imlp(is_new_usage)
0
repos/awtk
repos/awtk/scripts/compile_config.py
import os import io import sys import json import shutil import importlib import collections global COMPILE_CONFIG COMPILE_CONFIG = None global APP_ROOT APP_ROOT = '' global WIN32_RES WIN32_RES = '' def get_curr_config() : global COMPILE_CONFIG return COMPILE_CONFIG def set_curr_config(complie_config) : global COMPILE_CONFIG COMPILE_CONFIG = complie_config def set_app_win32_res(dir_path) : global WIN32_RES WIN32_RES = dir_path def set_curr_app_root(app_root) : global APP_ROOT APP_ROOT = app_root def get_curr_app_root() : global APP_ROOT return APP_ROOT def get_curr_config_for_awtk() : global WIN32_RES global COMPILE_CONFIG if COMPILE_CONFIG != None : return COMPILE_CONFIG else : COMPILE_CONFIG = complie_helper() if not COMPILE_CONFIG.load_last_complie_argv() : print('========================= Error ================================') print('Please Recompile AWTK !!!!!') sys.exit('Not found last complie argv config file !!!!!') COMPILE_CONFIG.set_value('WIN32_RES', WIN32_RES) return COMPILE_CONFIG; def json_obj_load_file(file_path) : obj = None; if os.path.exists(file_path) : try : with io.open(file_path, 'r', encoding='utf-8') as file : obj = json.load(file); except Exception as e : print(e) return obj; def json_obj_save_file(obj, file_path) : dir = os.path.dirname(file_path); if os.path.exists(dir) : try : with io.open(file_path, 'w', encoding='utf-8') as file : if sys.version_info >= (3, 0): json.dump(obj, file, indent=4, ensure_ascii=False) else : file.write(json.dumps(obj, indent=4, ensure_ascii=False).decode('utf-8')) except Exception as e : print(e) else : print(dir + ' is not exists') class complie_helper : DEFAULT_CONFIG_FILE = './awtk_config_define.py' LAST_COMLIP_ARGV_FILE = './bin/last_complie_argv.json' COMPILE_CMD_INFO = collections.OrderedDict({ 'help' : { 'name': 'HELP', 'help_info' : 'show all usage'}, 'userdefine' : { 'name' : 'DEFINE_FILE', 'help_info' : 'set user config define file, DEFINE_FILE=XXXXX'}, 'save_file' : { 'name' : 'EXPORT_DEFINE_FILE', 'help_info' : 'current config define export to file, EXPORT_DEFINE_FILE=./awtk_config_define.py'}, }) config = collections.OrderedDict({ 'OUTPUT_DIR' : { 'value' : None, 'type' : str.__name__, 'desc' : ['compiled export directory '], 'help_info' : 'set awtk compiled export directory, default value is \'\', \'\' is system\'s value'}, 'TOOLS_NAME' : { 'value' : None, 'type' : str.__name__, 'str_enum' : ['mingw'], 'desc' : ['value is \'mingw\' or None'], 'help_info' : 'set awtk compile\'s name, default value is None, None is system\'s value'}, 'INPUT_ENGINE' : { 'value' : None, 'type' : str.__name__, 'str_enum' : ['null', 'spinyin', 't9', 't9ext', 'pinyin'], 'desc' : ['value is null/spinyin/t9/t9ext/pinyin'], 'help_info' : 'set awtk use input engine, default value is None, None is system\'s value' }, 'VGCANVAS' : { 'value' : None, 'type' : str.__name__, 'str_enum' : ['NANOVG', 'NANOVG_PLUS', 'CAIRO'], 'desc' : ['value is NANOVG/NANOVG_PLUS/CAIRO'], 'help_info' : 'set awtk use render vgcanvas type, default value is None, None is system\'s value' }, 'NANOVG_BACKEND' : { 'value' : None, 'type' : str.__name__, 'str_enum' : ['GLES2', 'GLES3', 'GL3', 'AGG', 'AGGE'], 'desc' : ['if NANOVG_BACKEND is valid, VGCANVAS must be NANOVG or \'\'', 'if VGCANVAS is NANOVG_PLUS, NANOVG_BACKEND must be GLES2/GLES3/GL3 or None', 'NANOVG_BACKEND is GLES2/GLES3/GL3/AGG/AGGE'], 'help_info' : 'set awtk\'s nanovg use render model, default value is None, None is system\'s value'}, 'LCD_COLOR_FORMAT' : { 'value' : None, 'type' : str.__name__, 'str_enum' : ['bgr565', 'bgra8888', 'mono'], 'desc' : ['if NANOVG_BACKEND is GLES2/GLES3/GL3, LCD_COLOR_FORMAT must be bgra8888 or \'\'', 'if NANOVG_BACKEND is AGG/AGGE, LCD_COLOR_FORMAT must be bgr565/bgra8888/mono or None', 'NANOVG_BACKEND is bgr565/bgra8888/mono'], 'help_info' : 'set awtk\'s lcd color format, default value is None, None is system\'s value'}, 'DEBUG' : { 'value' : True, 'type' : bool.__name__, 'desc' : ['awtk\'s compile is debug'], 'help_info' : 'awtk\'s compile is debug, value is true or false, default value is true' }, 'PDB' : { 'value' : True, 'type' : bool.__name__, 'desc' : ['export pdb file'], 'help_info' : 'export pdb file, value is true or false' }, 'SDL_UBUNTU_USE_IME' : { 'value' : False, 'type' : bool.__name__, 'desc' : ['ubuntu use chinese input engine'], 'help_info' : 'ubuntu use ime, this sopt is ubuntu use chinese input engine, value is true or false, default value is false' }, 'NATIVE_WINDOW_BORDERLESS' : { 'value' : False, 'type' : bool.__name__, 'desc' : ['pc desktop program no borerless'], 'help_info' : 'pc desktop program no borerless, value is true or false, default value is false' }, 'NATIVE_WINDOW_NOT_RESIZABLE' : { 'value' : False, 'type' : bool.__name__, 'desc' : ['pc desktop program do not resize program'], 'help_info' : 'pc desktop program do not resize program\'s size, value is true or false, default value is false' }, 'BUILD_TESTS' : { 'value' : True, 'type' : bool.__name__, 'desc' : ['build awtk\'s gtest demo'], 'help_info' : 'build awtk\'s gtest demo, value is true or false, default value is true' }, 'BUILD_DEMOS' : { 'value' : True, 'type' : bool.__name__, 'desc' : ['build awtk\'s demo examples'], 'help_info' : 'build awtk\'s demo examples, value is true or false, default value is true' }, 'BUILD_TOOLS' : { 'value' : True, 'type' : bool.__name__, 'desc' : ['build awtk\'s tools'], 'help_info' : 'build awtk\'s tools, value is true or false, default value is true' }, 'WIN32_RES' : { 'value' : None, 'type' : str.__name__, 'save_file' : False, 'desc' : ['app\'s win32 res path'], 'help_info' : 'app\'s win32 res path, WIN32_RES=XXXXX, value\'s default=\'awtk/win32_res/awtk.res\' ' }, }) def try_load_default_config(self) : if os.path.exists(self.DEFAULT_CONFIG_FILE) : self.load_config(self.DEFAULT_CONFIG_FILE) def set_compile_config(self, config) : self.config = config def load_config_by_sopt(self, ARGUMENTS) : for key in ARGUMENTS : if key.upper() == self.COMPILE_CMD_INFO['userdefine']['name'] : file = ARGUMENTS[key] if os.path.exists(file) : self.load_config(file) break; else : sys.exit('userdefine sopt is not found :' + file) def check_config_legality(self) : for key in self.config : check = False if not 'str_enum' in self.config[key] : continue if self.config[key]['value'] != '' and self.config[key]['value'] != None: for str_enum in self.config[key]['str_enum'] : if str_enum == self.config[key]['value'] : check = True break if not check : if self.config[key]['value'] == None: sys.exit(key + ' \'s value is None, is not legality !') else : sys.exit(key + ' \'s value is ' + self.config[key]['value'] + ', is not legality !') def scons_user_sopt(self, ARGUMENTS) : EXPORT_USERDEFINE_FILE = None def find_compile_cmd_info_by_name(name) : for key in self.COMPILE_CMD_INFO : if name == self.COMPILE_CMD_INFO[key]['name']: return True return False for arg in sys.argv : key = arg.upper() if key == self.COMPILE_CMD_INFO['help']['name'] : self.show_usage() sys.exit() self.load_config_by_sopt(ARGUMENTS) for key in ARGUMENTS : userdefine_key = key.upper() if self.has_key(userdefine_key) : value = ARGUMENTS[key] self.set_value(userdefine_key, value) elif not find_compile_cmd_info_by_name(userdefine_key): print('awtk\'s default compiler list does not support {0} , so skip {0} !!!!!!'.format(key)) elif key.upper() == self.COMPILE_CMD_INFO['save_file']['name'] : EXPORT_USERDEFINE_FILE = ARGUMENTS[key] if EXPORT_USERDEFINE_FILE != None : self.save_config(EXPORT_USERDEFINE_FILE) sys.exit() self.check_config_legality() def show_usage(self) : print('=========================================================') for key in self.config : print((key + ' : ').ljust(32) + self.config[key]['help_info']) for desc in self.config[key]['desc'] : print(''.ljust(32) + desc) for key in self.COMPILE_CMD_INFO : print((self.COMPILE_CMD_INFO[key]['name'] + ' : ').ljust(32) + self.COMPILE_CMD_INFO[key]['help_info']) print('=========================================================') def write_file(self, filename, s): if sys.version_info >= (3, 0): with open(filename, 'w', encoding='utf8') as f: f.write(s) else: with open(filename, 'w') as f: s = s.encode('utf8') f.write(s) def save_config(self, file) : dir = os.path.dirname(file); if os.path.exists(dir) : save_data = '' save_data += '# user set default configuration item \n' save_data += '# if value is None, so value is default value \n' save_data += '\n' for key in self.config : if 'save_file' in self.config[key] and not self.config[key]['save_file'] : continue for desc in self.config[key]['desc'] : save_data += ('# ' + desc) save_data += '\n' if isinstance(self.config[key]['value'], str) : save_data += (key + ' = r\'' + self.config[key]['value'] + '\'') else : save_data += (key + ' = ' + str(self.config[key]['value'])) save_data += '\n\n' try : self.write_file(file, save_data) except Exception as e : print(e) else : print(dir + ' is not exists') def load_config(self, file) : file = os.path.abspath(file) if os.path.exists(file) : script_dir = os.path.dirname(file) file_name = os.path.basename(file) module_name, ext = os.path.splitext(file_name) sys.path.insert(0, script_dir) config_script = importlib.import_module(module_name) sys.path.remove(script_dir) for key in self.config : if hasattr(config_script, key) : if not 'save_file' in self.config[key] or self.config[key]['save_file'] : self.config[key]['value'] = getattr(config_script, key) else : sys.exit(file + ' is not found') def has_key(self, name) : return name in self.config def get_value(self, name, default_value = None) : return self.get_unique_value(name, default_value) def get_unique_value(self, name, default_value) : if name in self.config and self.config[name]['value'] != None : return self.config[name]['value'] return default_value def set_value(self, name, value) : if name in self.config : if isinstance(self.config[name]['value'], bool) and isinstance(value, bool): self.config[name]['value'] = value elif (isinstance(self.config[name]['value'], bool) and isinstance(value, str)) or ('type' in self.config[name] and self.config[name]['type'] == bool.__name__ and isinstance(value, str)): try : from utils import strtobool self.config[name]['value'] = strtobool(value) == 1 except : self.config[name]['value'] = value.lower() == 'true' elif isinstance(self.config[name]['value'], list) and isinstance(value, str) : self.config[name]['value'] = value.split(',') elif self.config[name]['value'] == None and (not 'type' in self.config[name]): self.config[name]['value'] = value else: self.config[name]['value'] = value def save_last_complie_argv(self) : json_obj_save_file(self.config, self.LAST_COMLIP_ARGV_FILE); def load_last_complie_argv(self) : if os.path.exists(self.LAST_COMLIP_ARGV_FILE) : obj = json_obj_load_file(self.LAST_COMLIP_ARGV_FILE); if obj != None : self.config = collections.OrderedDict(obj); return True return False def output_compile_data(self, awtk_root) : output_dir = self.config['OUTPUT_DIR']['value'] if output_dir != '' and output_dir != None : if os.path.exists(output_dir) : shutil.rmtree(output_dir) os.makedirs(output_dir) shutil.copytree(awtk_root + '/bin', output_dir + '/bin') shutil.copytree(awtk_root + '/lib', output_dir + '/lib')
0
repos/awtk
repos/awtk/scripts/release.py
import os import sys import release_common as common if len(sys.argv) < 2: print("Usage: python " + sys.argv[0] + ' exe [assets root] [bin root]') print(" Ex: python " + sys.argv[0] + ' demoui.exe') sys.exit(0) CWD = os.getcwd() bin_root = CWD assets_root = CWD exe_name = sys.argv[1] if len(sys.argv) > 2: assets_root = sys.argv[2] if len(sys.argv) > 3: bin_root = sys.argv[3] common.init(exe_name, assets_root, bin_root) common.release()
0
repos/awtk
repos/awtk/scripts/awtk_locator.py
import os import sys def getAwtkConfig(LINUX_FB): AWTK_ROOT = getAwtkOrAwtkLinuxFbRoot(LINUX_FB) sys.path.insert(0, AWTK_ROOT) import awtk_config as awtk return awtk def getTkcOnly(): env = os.environ if 'TKC_ONLY' in env: return env['TKC_ONLY'] == 'True' else: return False def getAwtkOrAwtkLinuxFbRoot(is_linux_fb): if getTkcOnly(): print('TKC_ONLY == True'); return locateAWTK('tkc') elif is_linux_fb: return locateAWTK('awtk-linux-fb') else: return locateAWTK('awtk') def getAwtkScriptsRoot(): return os.path.join(locateAWTK('awtk'), 'scripts') def getAwtkRoot(): return locateAWTK('awtk') def getAwtkLinuxFbRoot(): return locateAWTK('awtk-linux-fb') def locateAWTK(awtk): awtk_root = '../' + awtk if not os.path.exists(awtk_root): dirnames = ['../'+awtk, '../../'+awtk, '../../../'+awtk] for dirname in dirnames: if os.path.exists(dirname): awtk_root = dirname break return os.path.abspath(awtk_root) AWTK_ROOT = getAwtkRoot() AWTK_SCRIPTS_ROOT = getAwtkScriptsRoot() sys.path.insert(0, AWTK_SCRIPTS_ROOT) print('AWTK_ROOT:' + AWTK_ROOT) print('AWTK_SCRIPTS_ROOT:' + AWTK_SCRIPTS_ROOT)
0
repos/awtk
repos/awtk/scripts/README.md
# 工具脚本 ## 一、update\_res.py 资源生成工具 ``` Usage: python ./scripts/update_res.py action[clean|all|font|image|ui|style|string] dpi[x1|x2] image_options[bgra+bgr565|rgba] Example: python ./scripts/update_res.py all python ./scripts/update_res.py clean python ./scripts/update_res.py style python ./scripts/update_res.py all x1 bgra+bgr565 ``` 第一个参数action是必须的,其取值如下: * clean 清除之前生成的资源文件。 * all 重新生成全部资源。 * font 仅生成有变化的字体资源。 * image 仅生成有变化的图像资源。 * ui 仅生成有变化的UI资源。 * style 仅生成有变化的窗体样式资源。 * string 仅生成有变化的字符串资源。 > 除非你清楚你在做什么,指定第一个参数就可以了。 第二个参数dpi是可选的。用来指定图片的DPI,缺省为x1,即普通屏幕的图片。 > 如果定义了WITH\_FS\_RES(即支持文件系统),AWTK自动从文件系统中加载对应DPI的图片,此时这个参数没有意义。 第三个参数image\_options是可选的。用来指定生成位图的图片格式,缺省为bgra+bgr565。 > 如果定义了WITH\_FS\_RES(即支持文件系统)或者WITH\_STB\_IMAGE(支持png/jpg),就不会使用生成的位图,此时这个参数没有意义。 ## 二、release.py 发布工具 将运行时需要的文件拷贝到release目录。 用法: ``` python scripts/release.py [exe name] ``` 示例: ``` python scripts/release.py demoui.exe ``` 也可在其它项目中使用。 用法: ``` python ../awtk/scripts/release.py [exe name] ``` 示例: > 比如当前项目为awtk-mvvm-c-hello。 ``` python ../awtk/scripts/release.py awtk_mvvm_app.exe ```
0
repos/awtk
repos/awtk/scripts/utils.py
def strtobool(value): if(isinstance(value, str)): value = value.lower() if value in ("y", "yes", "on", "1", "true", "t"): return True return False
0
repos/awtk
repos/awtk/scripts/update_res_app.py
#!/usr/bin/python import os import sys import json import collections # AWTK_ROOT/scripts/update_res_common.py import update_res_common as common import res_config RES_CONFIG = None RES_OUTPUT_DIR='./res' def get_theme(i): return THEMES[i] def use_theme_config_from_res_config(res_config_path, config = None): global DPI global THEMES global OUTPUT_ROOT global IS_GENERATE_INC_RES global IS_GENERATE_INC_BITMAP global APP_THEME global APP_ROOT global LCD_ORIENTATION global LCD_FAST_ROTATION_MODE content = None if config == None : config_json = common.join_path(APP_ROOT, res_config_path) if not os.path.exists(config_json) or res_config_path == '': config_json = common.join_path(APP_ROOT, 'project.json') if not os.path.exists(config_json) : print(config_json + ' is not exists.') return content = res_config.res_config() content.load_file(config_json) else : content = config; OUTPUT_ROOT = common.join_path(APP_ROOT, common.join_path(content.get_res_res_root(), 'assets')) APP_THEME = content.get_res_actived_theme() LCD_FAST_ROTATION_MODE = content.get_res_lcd_fast_rotation_mode() LCD_ORIENTATION = content.get_res_lcd_orientation() DPI = content.get_res_dpi() IS_GENERATE_INC_RES = content.get_inc_res() IS_GENERATE_INC_BITMAP = content.get_inc_bitmap() if not content.has_themes(): return for theme_name in content.get_res_themes_key() : color_format = content.get_res_color_format(theme_name) color_depth = content.get_res_color_depth(theme_name) if color_format == 'MONO': imagegen_options = 'mono' elif color_format == 'BGR(A)': if color_depth == '16bit': imagegen_options = 'bgr565' else: imagegen_options = 'bgra' else: if color_depth == '16bit': imagegen_options = 'rgb565' else: imagegen_options = 'rgba' if IS_GENERATE_INC_BITMAP: config_dir = common.join_path(ASSETS_ROOT, common.join_path(theme_name, 'fonts/config')) common.remove_dir(config_dir) common.make_dirs(config_dir) for font_name in content.get_res_fonts_key(theme_name): for font_size in content.get_res_font_size_key(theme_name, font_name): font_name = common.to_file_system_coding(font_name) font_size = common.to_file_system_coding(font_size) filename = common.join_path(config_dir, font_name+'_'+font_size+'.txt') common.write_file(filename, content.get_res_font_value(theme_name, font_name, font_size, '')) theme = {'name': theme_name, 'imagegen_options': imagegen_options, 'packaged': content.get_res_packaged(theme_name), 'storage_dir': content.get_storage_dir()} if theme_name == 'default': THEMES.insert(0, theme) else: THEMES.append(theme) def use_default_theme_config(res_config_path, res_config = None): global THEMES use_theme_config_from_res_config(res_config_path, res_config) if len(THEMES) == 0: if os.path.isdir(ASSETS_ROOT): for file in os.listdir(ASSETS_ROOT): if os.path.isdir(common.join_path(ASSETS_ROOT, file)): if file == 'default': THEMES.insert(0, file) else: THEMES.append(file) def is_dependencies_ok(): dependencies = ['bsvggen', 'fontgen', 'imagegen', 'resgen', 'strgen', 'themegen', 'xml_to_ui'] for d in dependencies: if not os.path.exists(common.join_path(TOOLS_ROOT, common.to_exe(d))): print('Can\'t find ' + common.to_exe(d) + ', please build AWTK.') return False if IS_GENERATE_INC_BITMAP: for t in THEMES: if isinstance(t, dict): print(t['imagegen_options']) return True def on_generate_res_event(): if os.path.exists(common.join_path(APP_ROOT, 'scripts/update_res_generate_res_handler.py')): import update_res_generate_res_handler as generate_res if hasattr(generate_res, 'on_generate_res_before'): common.on_generate_res_before(generate_res.on_generate_res_before) if hasattr(generate_res, 'on_generate_res_after'): common.on_generate_res_after(generate_res.on_generate_res_after) def getopt(args): return common.get_args(args); def set_res_config(config) : global RES_CONFIG RES_CONFIG = config def set_res_config_by_script(script_path, res_config_script_argv): return set_res_config(res_config.set_res_config_by_script(script_path, res_config_script_argv)) def get_dict_value(dict, key, default_value) : if key in dict : return dict[key] return default_value def run(awtk_root, is_excluded_file_handler = None, is_new_usage = False) : global DPI global AWTK_ROOT global TOOLS_ROOT global THEMES global APP_THEME global APP_ROOT global ASSETS_ROOT global OUTPUT_ROOT global IS_GENERATE_INC_RES global IS_GENERATE_INC_BITMAP global LCD_ORIENTATION global LCD_FAST_ROTATION_MODE global RES_CONFIG common.show_usage(is_new_usage); GDPI='' TMP_APP_ROOT = '' IMAGEGEN_OPTIONS='' TMP_LCD_ORIENTATION='' RES_CONFIG_JSON_PATH='' RES_OUTPUT_DIR='./res' TMP_LCD_FAST_ROTATION_MODE=None args = sys.argv[1:]; is_longsots_res_output_dir = False if common.is_all_sopts_args(args) : longsots_dict = common.get_longsopts_args(args) common.set_action(longsots_dict['action']) awtk_root = get_dict_value(longsots_dict, 'awtk_root', awtk_root) GDPI = get_dict_value(longsots_dict, 'dpi', GDPI) IMAGEGEN_OPTIONS = get_dict_value(longsots_dict, 'image_options', IMAGEGEN_OPTIONS) TMP_LCD_ORIENTATION = get_dict_value(longsots_dict, 'lcd_orientation', TMP_LCD_ORIENTATION) TMP_LCD_FAST_ROTATION_MODE = get_dict_value(longsots_dict, 'lcd_enable_fast_rotation', TMP_LCD_FAST_ROTATION_MODE) RES_CONFIG_JSON_PATH = get_dict_value(longsots_dict, 'res_config_file', RES_CONFIG_JSON_PATH) TMP_APP_ROOT = get_dict_value(longsots_dict, 'app_root', TMP_APP_ROOT) if 'output_dir' in longsots_dict: is_longsots_res_output_dir = True RES_OUTPUT_DIR = longsots_dict['output_dir'] if 'res_config_script' in longsots_dict : res_config_script_argv = '' res_config_script = longsots_dict['res_config_script'] if 'res_config_script_argv' in longsots_dict : res_config_script_argv = longsots_dict['res_config_script_argv'] set_res_config_by_script(res_config_script, res_config_script_argv) else : sys_args = common.get_args(args) if len(sys_args) > 0 : common.set_action(sys_args[0]) if len(sys_args) > 1: GDPI = sys_args[1] if len(sys_args) > 2: IMAGEGEN_OPTIONS = sys_args[2] if len(sys_args) > 3: TMP_LCD_ORIENTATION = sys_args[3] TMP_LCD_FAST_ROTATION_MODE = False AWTK_ROOT = awtk_root action = common.get_action() if TMP_APP_ROOT == '' : APP_ROOT = common.getcwd() if APP_ROOT.endswith('scripts'): APP_ROOT = os.path.dirname(APP_ROOT) else : APP_ROOT = TMP_APP_ROOT os.chdir(APP_ROOT) DPI = 'x1' THEMES = [] APP_THEME = 'default' LCD_ORIENTATION = '' OUTPUT_ROOT = None IS_GENERATE_INC_RES = True IS_GENERATE_INC_BITMAP = True LCD_FAST_ROTATION_MODE = False TOOLS_ROOT = common.join_path(AWTK_ROOT, 'bin') AWTK_ROOT = common.join_path(APP_ROOT, AWTK_ROOT) ASSETS_ROOT = common.join_path(APP_ROOT, 'design') use_default_theme_config(RES_CONFIG_JSON_PATH, RES_CONFIG) if is_longsots_res_output_dir or OUTPUT_ROOT == None : OUTPUT_ROOT = os.path.abspath(common.join_path(RES_OUTPUT_DIR, 'assets')) if TMP_LCD_ORIENTATION != '' : LCD_ORIENTATION = TMP_LCD_ORIENTATION if TMP_LCD_FAST_ROTATION_MODE != None : LCD_FAST_ROTATION_MODE = TMP_LCD_FAST_ROTATION_MODE ASSET_C = common.join_path(OUTPUT_ROOT, '../assets.inc') if action == 'json': ASSET_C = common.join_path(APP_ROOT, 'assets_web.js') if not is_dependencies_ok(): print('For details, please read scripts/README.md.') elif len(THEMES) == 0: print('Not found theme.') print('For details, please read scripts/README.md.') else: if GDPI != '': DPI = GDPI if IMAGEGEN_OPTIONS != '': for theme in THEMES : theme["imagegen_options"] = IMAGEGEN_OPTIONS if LCD_ORIENTATION != '': for theme in THEMES : theme["lcd_orientation"] = LCD_ORIENTATION common.init(AWTK_ROOT, ASSETS_ROOT, THEMES, ASSET_C, OUTPUT_ROOT) common.set_tools_dir(TOOLS_ROOT) common.set_lcd_rortrail_info(LCD_ORIENTATION, LCD_FAST_ROTATION_MODE) common.set_dpi(DPI) common.set_app_theme(APP_THEME) common.set_enable_generate_inc_res(IS_GENERATE_INC_RES) common.set_enable_generate_inc_bitmap(IS_GENERATE_INC_BITMAP) common.set_is_excluded_file_handler(is_excluded_file_handler) on_generate_res_event() common.update_res() if isinstance(THEMES[0], dict): if action != 'clean' and action != 'web' and action != 'json' and action != 'pinyin' and action != 'res': common.gen_res_c(False)
0
repos/awtk
repos/awtk/scripts/release_version.sh
#!/bin/bash VERSION="1.8" git checkout -b "$VERSION" git push --set-upstream origin "$VERSION"
0
repos/awtk/scripts
repos/awtk/scripts/project_scripts/__init__.py
import os import sys APP_SCRIPTS_ROOT = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, APP_SCRIPTS_ROOT)
0
repos/awtk/scripts
repos/awtk/scripts/project_scripts/release.py
import os import sys import platform import shutil import json import collections import fnmatch def join_path(root, subdir): return os.path.normpath(os.path.join(root, subdir)) OS_NAME = platform.system() PRJ_DIR = os.getcwd(); OUTPUT_DIR = join_path(PRJ_DIR, 'release') BIN_DIR = join_path(PRJ_DIR, 'bin') def read_file(filename): content = '' if sys.version_info >= (3, 0): with open(filename, 'r', encoding='utf8') as f: content = f.read() else: with open(filename, 'r') as f: content = f.read() return content def to_file_system_coding(s): if sys.version_info >= (3, 0): return s coding = sys.getfilesystemencoding() return s.encode(coding) def init_project_config(): global CONFIG json_path = join_path(PRJ_DIR, 'project.json') if not os.path.exists(json_path): return content = read_file(json_path) CONFIG = json.loads(content, object_pairs_hook=collections.OrderedDict) def get_args(args, longsopts = []) : list_opts = [] for arg in args: if arg.startswith('--') : tmp_opt = '' for opt in longsopts: if arg.find(opt) > 0 : tmp_opt = opt break if tmp_opt != '' : list_opts.append(arg.split(tmp_opt)[1]) continue else : print(arg + " not find command, command :") print(longsopts) sys.exit() return list_opts def release(): if not os.path.exists(OUTPUT_DIR): os.makedirs(OUTPUT_DIR) init_project_config() assets = CONFIG['assets'] if 'outputDir' in assets: res_root = to_file_system_coding(assets['outputDir']) assets_root = join_path(PRJ_DIR, res_root + '/assets') exeName = ''; if 'appExeName' in CONFIG : exeName = CONFIG['appExeName'] if exeName == '': exeName = 'demo' exeName = exeName + '.exe' if OS_NAME == 'Windows' else exeName copyExe(exeName) copyAssets(assets_root) cleanFiles() def copyExe(exeName): output_bin_dir = join_path(OUTPUT_DIR, 'bin') common.copyFile(BIN_DIR, exeName, output_bin_dir, exeName) common.copySharedLib(BIN_DIR, output_bin_dir) os.chmod(join_path(output_bin_dir, exeName), 0o755) def copyAssets(assets_root): common.copyFiles(assets_root, '', OUTPUT_DIR, 'assets/') def cleanFiles(): assets = CONFIG['assets'] if 'themes' not in assets: return themes = assets['themes'] for theme in themes: d = join_path(OUTPUT_DIR, 'assets/' + theme + '/inc') shutil.rmtree(d, True) import release_common as common release()
0
repos/awtk/scripts
repos/awtk/scripts/project_scripts/app_helper.py
import os import sys import shutil import awtk_locator as locator from SCons import Script def Helper(ARGUMENTS): from app_helper_base import AppHelperBase return AppHelperBase(ARGUMENTS) def parse_needed_file(helper, root, file): dst = helper.APP_BIN_DIR if isinstance(file, list): src = os.path.abspath(os.path.join(root, file[0])) if len(file) > 1: dst = os.path.abspath(os.path.join(helper.APP_BIN_DIR, file[1])) else: src = os.path.abspath(os.path.join(root, file)) return src, dst def clear_needed_files(helper, root, needed_files): for file in needed_files: src, dst = parse_needed_file(helper, root, file) if os.path.isfile(src): if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) if os.path.exists(dst): os.remove(dst) print('Removed {}'.format(os.path.relpath(dst, helper.APP_ROOT))) elif os.path.isdir(src) and os.path.isdir(dst): dirs = [] for _root, _dirs, _files in os.walk(src): for _file in _files: _dst = os.path.join(dst, os.path.relpath(os.path.join(_root, _file), src)) if os.path.exists(_dst): os.remove(_dst) print('Removed {}'.format(os.path.relpath(_dst, helper.APP_ROOT))) for _dir in _dirs: dirs.append(os.path.join(dst, _dir)) for _dir in dirs: try: os.rmdir(_dir) print('Removed {}'.format(os.path.relpath(_dir, helper.APP_ROOT))) except: none if not os.path.relpath(helper.APP_BIN_DIR, dst) == '.': try: os.rmdir(dst) print('Removed {}'.format(os.path.relpath(dst, helper.APP_ROOT))) except: none def copy_needed_files(helper, root, needed_files): for file in needed_files: src, dst = parse_needed_file(helper, root, file) if os.path.isfile(src): if os.path.exists(src): if not os.path.exists(os.path.dirname(dst)): os.makedirs(os.path.dirname(dst)) shutil.copy(src, dst) print(src + '==>' + dst) else: print('[NeededFiles]: Not found {src}', src) elif os.path.isdir(src): if os.path.exists(src): for _root, _dirs, _files in os.walk(src): for _file in _files: _src = os.path.join(_root, _file) _dst = os.path.join(dst, os.path.relpath(_src, src)) if not os.path.exists(os.path.dirname(_dst)): os.makedirs(os.path.dirname(_dst)) shutil.copy(_src, _dst) print(src + '==>' + dst) else: print('[NeededFiles]: Not found {src}', src) def prepare_depends_libs(ARGUMENTS, helper, libs): if ARGUMENTS.get('PREPARE_DEPENDS', '').lower().startswith('f'): return args = ' AWTK_ROOT=\"{}\"'.format(helper.AWTK_ROOT) if helper.MVVM_ROOT: args += ' MVVM_ROOT=\"{}\"'.format(helper.MVVM_ROOT) if 'APP_BIN_DIR' in ARGUMENTS: args += ' APP_BIN_DIR=\"{}\"'.format(helper.APP_BIN_DIR.replace('\\', '/')) if not os.path.exists(helper.APP_BIN_DIR): os.makedirs(helper.APP_BIN_DIR) else: args += ' APP_BIN_DIR=\"{}\"'.format(os.path.abspath(helper.APP_BIN_DIR).replace('\\', '/')) for key in ARGUMENTS: if not key == 'AWTK_ROOT' and not key == 'MVVM_ROOT' and not key == 'APP_BIN_DIR' : if ' ' in ARGUMENTS[key]: args += ' {}=\"{}\"'.format(key, ARGUMENTS[key]) else: args += ' {}={}'.format(key, ARGUMENTS[key]) num_jobs_str = '' num_jobs = Script.GetOption('num_jobs') if num_jobs > 1: num_jobs_str = ' -j' + str(num_jobs) clean_str = '' if Script.GetOption('clean'): clean_str = ' -c ' for lib in libs: if 'root' in lib and os.path.exists(lib['root'] + '/SConstruct'): cmd = 'cd ' + lib['root'] + ' && scons' + clean_str + num_jobs_str + args print('\n*******************************************************************************') print('[Dependencies]: {}'.format(lib['root'])) print('*******************************************************************************\n') result = os.system(cmd) if not result == 0: sys.exit(result) if 'needed_files' in lib: if Script.GetOption('clean'): clear_needed_files(helper, lib['root'], lib['needed_files']) else: copy_needed_files(helper, lib['root'], lib['needed_files']) def helper_has_func(helper, func_name): return False; def helper_run_func(helper, func_name, argv): return None;
0
repos/awtk
repos/awtk/staticcheck/README.md
# 静态代码检查
0
repos/awtk/staticcheck
repos/awtk/staticcheck/common/awtk_files.py
import os import copy import glob import subprocess def joinPath(root, subdir): return os.path.abspath(os.path.normpath(os.path.join(root, subdir))) if 'AWTK_ROOT_DIR' in os.environ: AWTK_ROOT_DIR=os.path.abspath(os.environ['AWTK_ROOT_DIR']); else: AWTK_ROOT_DIR=os.path.abspath('../../'); AWTK_SRC_DIR=joinPath(AWTK_ROOT_DIR, 'src'); AWKT_TKC_FILES=glob.glob(AWTK_SRC_DIR+'/tkc/*.c') AWKT_BASE_FILES=glob.glob(AWTK_SRC_DIR+'/base/*.c') AWKT_WIDGETS_FILES=glob.glob(AWTK_SRC_DIR+'/widgets/*.c') AWKT_WIDGETS_FILES=glob.glob(AWTK_SRC_DIR+'/widgets/*.c') AWKT_EXT_WIDGETS_FILES=glob.glob(AWTK_SRC_DIR+'/ext_widgets/*.c') + glob.glob(AWTK_SRC_DIR+'/ext_widgets/*/*.c') AWKT_UILOADER_FILES=glob.glob(AWTK_SRC_DIR+'/ui_loader/*.c') AWKT_LAYOUTERS_FILES=glob.glob(AWTK_SRC_DIR+'/layouters/*.c') AWKT_XML_FILES=glob.glob(AWTK_SRC_DIR+'/xml/*.c') AWKT_ROMFS_FILES=glob.glob(AWTK_SRC_DIR+'/romfs/romfs.c') AWKT_SVG_FILES=glob.glob(AWTK_SRC_DIR+'/svg/*.c') AWKT_APP_CONF_FILES=glob.glob(AWTK_SRC_DIR+'/conf_io/*.c') AWKT_UBJSON_FILES=glob.glob(AWTK_SRC_DIR+'/ubjson/*.c') AWKT_CSV_FILES=glob.glob(AWTK_SRC_DIR+'/csv/*.c') AWKT_FSCRIPT_EXT_FILES=glob.glob(AWTK_SRC_DIR+'/fscript_ext/*.c') AWKT_STREAMS_FILES=glob.glob(AWTK_SRC_DIR+'/streams/file/*.c') + glob.glob(AWTK_SRC_DIR+'/streams/mem/*.c') AWKT_CLIPBOARD_FILES=glob.glob(AWTK_SRC_DIR+'/clip_board/clip_board_default.c') AWKT_WIDGET_ANIMATORS_FILES=glob.glob(AWTK_SRC_DIR+'/widget_animators/*.c') AWKT_WINDOW_ANIMATORS_FILES=glob.glob(AWTK_SRC_DIR+'/window_animators/*.c') AWKT_DIALOG_HIGHLIGHTERS_FILES=glob.glob(AWTK_SRC_DIR+'/dialog_highlighters/*.c') AWKT_FONT_LOADER_FILES=glob.glob(AWTK_SRC_DIR+'/font_loader/*.c') AWKT_IMAGE_LOADER_FILES=glob.glob(AWTK_SRC_DIR+'/image_loader/*.c') AWKT_DESIGNER_SUPPORT_FILES=glob.glob(AWTK_SRC_DIR+'/designer_support/*.c') AWKT_INPUT_METHOD_FILES=glob.glob(AWTK_SRC_DIR+'/input_methods/input_method_creator.c') AWKT_FONT_GLOBAL_FILES=glob.glob(AWTK_SRC_DIR+'/*.c') NATIVE_WINDOW_FILES=glob.glob(AWTK_SRC_DIR+'/native_window/native_window_raw.c') WINDOW_MANAGER_FILES=glob.glob(AWTK_SRC_DIR+'/window_manager/window_manager_default.c') GRAPHIC_BUFFER_FILES=glob.glob(AWTK_SRC_DIR+'/graphic_buffer/graphic_buffer_default.c') COMMON_FILES=AWKT_TKC_FILES + AWKT_BASE_FILES + AWKT_WIDGETS_FILES + AWKT_EXT_WIDGETS_FILES + AWKT_UILOADER_FILES + AWKT_LAYOUTERS_FILES + AWKT_SVG_FILES + AWKT_APP_CONF_FILES + AWKT_WIDGET_ANIMATORS_FILES + AWKT_WINDOW_ANIMATORS_FILES + AWKT_DIALOG_HIGHLIGHTERS_FILES + AWKT_CLIPBOARD_FILES + AWKT_FONT_GLOBAL_FILES + AWKT_INPUT_METHOD_FILES + NATIVE_WINDOW_FILES + WINDOW_MANAGER_FILES + GRAPHIC_BUFFER_FILES + AWKT_UBJSON_FILES + AWKT_CSV_FILES + AWKT_STREAMS_FILES + AWKT_FSCRIPT_EXT_FILES; INFER_FILES=COMMON_FILES WEB_FILES=COMMON_FILES + AWKT_XML_FILES + AWKT_ROMFS_FILES + AWKT_DESIGNER_SUPPORT_FILES CPPCHECK_FILES=COMMON_FILES + AWKT_XML_FILES + AWKT_ROMFS_FILES + AWKT_FONT_LOADER_FILES + AWKT_IMAGE_LOADER_FILES def getCppCheckFiles(): return CPPCHECK_FILES; def getInferFiles(): return INFER_FILES; def getWebFiles(): return WEB_FILES; def getIncludes(): return '-I' + AWTK_ROOT_DIR + '/3rd ' + '-I' + AWTK_ROOT_DIR + ' -I' + AWTK_SRC_DIR +' -I' + AWTK_SRC_DIR +'/ext_widgets'; def toExe(name): if OS_NAME == 'Windows': return name + '.exe' else: return name def writeArgs(filename, str): with open(filename, "w") as text_file: text_file.write(str); def runArgsInFile(cmd, flags, files): cmd_args = flags + ' ' + getIncludes() + ' ' + ' '.join(files) cmd_args = cmd_args.replace('\\', '\\\\'); writeArgs("args.txt", cmd_args); print(cmd_args) os.system(cmd + ' @args.txt'); def run(cmd, flags, files): cmd_args = cmd + ' ' + flags + ' ' + getIncludes() + ' ' + ' '.join(files) cmd_args = cmd_args.replace('\\', '\\\\'); print(cmd_args) os.system(cmd_args);
0
repos/awtk/staticcheck
repos/awtk/staticcheck/cppcheck/README.md
# 使用cppcheck对AWTK进行静态检查 ### 安装cppcheck 请参考[http://cppcheck.sourceforge.net/](http://cppcheck.sourceforge.net/) ### 使用方法 ``` python run.py ```
0
repos/awtk/staticcheck
repos/awtk/staticcheck/cppcheck/run.py
import os import sys sys.path.append("../common") import awtk_files as awtk; CPPFLAGS = '-DHAS_STD_MALLOC -DNDEBUG --enable=warning --enable=performance -DWITH_CPPCHECK --check-level=exhaustive ' awtk.run('cppcheck', CPPFLAGS, awtk.getCppCheckFiles())
0
repos/awtk/staticcheck
repos/awtk/staticcheck/infer/README.md
# 使用infer对AWTK进行静态检查 ### 安装infer 请参考[https://fbinfer.com/](https://fbinfer.com/) ### 使用方法 ``` python run.py ```
0
repos/awtk/staticcheck
repos/awtk/staticcheck/infer/run.py
import os import sys sys.path.append("../common") import awtk_files as awtk; CPPFLAGS = 'run -- clang -c -DHAS_STD_MALLOC -DNDEBUG -DWITH_INFERCHECK ' awtk.run('infer', CPPFLAGS, awtk.getInferFiles())
0
repos/awtk
repos/awtk/src/awtk_tkc.h
/** * File: awtk_tkc.h * Author: AWTK Develop Team * Brief: awtk toolkit c libs * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-12-15 Li XianJing <[email protected]> created * */ #include "tkc.h"
0
repos/awtk
repos/awtk/src/tkc.h
/** * File: tkc.h * Author: AWTK Develop Team * Brief: awtk toolkit c libs * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-12-15 Li XianJing <[email protected]> created * */ #ifndef TK_TKC_ONLY_H #define TK_TKC_ONLY_H #include "tkc/ostream.h" #include "tkc/semaphore.h" #include "tkc/fps.h" #include "tkc/socket_helper.h" #include "tkc/named_value.h" #include "tkc/stream_const.h" #include "tkc/color_parser.h" #include "tkc/utils.h" #include "tkc/object_array.h" #include "tkc/date_time.h" #include "tkc/data_reader.h" #include "tkc/easing.h" #include "tkc/emitter.h" #include "tkc/iostream.h" #include "tkc/types_def.h" #include "tkc/object_typed_array.h" #include "tkc/event.h" #include "tkc/path.h" #include "tkc/object_date_time.h" #include "tkc/rlog.h" #include "tkc/endian.h" #include "tkc/general_factory.h" #include "tkc/object_locker.h" #include "tkc/ring_buffer.h" #include "tkc/data_writer_file.h" #include "tkc/crc.h" #include "tkc/func_call_parser.h" #include "tkc/rom_fs.h" #include "tkc/asset_info.h" #include "tkc/func_desc.h" #include "tkc/fscript.h" #include "tkc/dl.h" #include "tkc/int_str.h" #include "tkc/value_desc.h" #include "tkc/matrix.h" #include "tkc/color.h" #include "tkc/timer_info.h" #include "tkc/object_wbuffer.h" #include "tkc/qaction.h" #include "tkc/data_writer_wbuffer.h" #include "tkc/tokenizer.h" #include "tkc/time_now.h" #include "tkc/event_source_timer.h" #include "tkc/value.h" #include "tkc/waitable_ring_buffer.h" #include "tkc/hash_table.h" #include "tkc/object_compositor.h" #include "tkc/idle_manager.h" #include "tkc/action_thread.h" #include "tkc/async.h" #include "tkc/event_source_fd.h" #include "tkc/buffer.h" #include "tkc/thread.h" #include "tkc/darray.h" #include "tkc/data_reader_mem.h" #include "tkc/rect.h" #include "tkc/event_source_manager.h" #include "tkc/object_rbuffer.h" #include "tkc/log.h" #include "tkc/url.h" #include "tkc/socket_pair.h" #include "tkc/slist.h" #include "tkc/data_writer_factory.h" #include "tkc/istream.h" #include "tkc/object_default.h" #include "tkc/action_thread_pool.h" #include "tkc/waitable_action_queue.h" #include "tkc/data_writer.h" #include "tkc/object.h" #include "tkc/wstr.h" #include "tkc/str.h" #include "tkc/typed_array.h" #include "tkc/mutex_nest.h" #include "tkc/cond.h" #include "tkc/event_source_idle.h" #include "tkc/data_reader_factory.h" #include "tkc/cond_var.h" #include "tkc/mutex.h" #include "tkc/mem.h" #include "tkc/mmap.h" #include "tkc/event_source.h" #include "tkc/mime_types.h" #include "tkc/action_queue.h" #include "tkc/idle_info.h" #include "tkc/compressor.h" #include "tkc/platform.h" #include "tkc/timer_manager.h" #include "tkc/utf8.h" #include "tkc/fs.h" #include "tkc/mem_pool.h" #include "tkc/data_reader_file.h" #include "tkc/event_source_manager_default.h" #include "tkc/plugin_manager.h" #include "tkc/str_str.h" #include "tkc/sha256.h" #endif /*TK_TKC_ONLY_H*/
0
repos/awtk
repos/awtk/src/awtk_version.h
/** * File: awtk_version.h * Author: AWTK Develop Team * Brief: awtk version * * Copyright (c) 2021 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-08-06 Luo Zhiming <[email protected]> created * */ #ifndef AWTK_VERSION_H #define AWTK_VERSION_H #define AWTK_VERSION_MAJOR 1 #define AWTK_VERSION_MINOR 7 #define AWTK_VERSION_MICRO 1 #define AWTK_VERSION_RELEASE_NUMBER 0 #define AWTK_VERSION_EXPERIMENTAL 0x7FFFFFFF /* awtk develop released a stable version */ #ifndef AWTK_VERSION_RELEASE_ID #define AWTK_VERSION_RELEASE_ID AWTK_VERSION_EXPERIMENTAL #endif /*AWTK_VERSION_RELEASE_ID*/ #endif /*AWTK_VERSION_H*/
0
repos/awtk
repos/awtk/src/awtk_main.inc
/** * File: awtk_main.c * Author: AWTK Develop Team * Brief: awtk main * * Copyright (c) 2018 - 2020 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-02-16 Li XianJing <[email protected]> created * */ #include "awtk.h" BEGIN_C_DECLS extern ret_t assets_init(void); END_C_DECLS #ifndef APP_DEFAULT_FONT #define APP_DEFAULT_FONT "default" #endif /*APP_DEFAULT_FONT*/ #ifndef LCD_WIDTH #define LCD_WIDTH 320 #endif /*LCD_WIDTH*/ #ifndef LCD_HEIGHT #define LCD_HEIGHT 480 #endif /*LCD_HEIGHT*/ #ifndef APP_TYPE #define APP_TYPE APP_SIMULATOR #endif /*APP_TYPE*/ #ifndef GLOBAL_INIT #define GLOBAL_INIT() #endif /*GLOBAL_INIT*/ #ifndef GLOBAL_EXIT #define GLOBAL_EXIT() #endif /*GLOBAL_EXIT*/ #ifndef FINAL_EXIT #define FINAL_EXIT() #endif /*FINAL_EXIT*/ #ifndef APP_NAME #define APP_NAME "awtk" #endif /*APP_NAME*/ #ifndef APP_RES_ROOT #define APP_RES_ROOT NULL #endif /*APP_RES_ROOT*/ #ifndef APP_ENABLE_CONSOLE #define APP_ENABLE_CONSOLE TRUE #endif /*APP_ENABLE_CONSOLE*/ #include "base/custom_keys.inc" #include "base/asset_loader_zip.h" #ifdef USE_GUI_MAIN int gui_app_start_ex(int lcd_w, int lcd_h, const char* res_root); int gui_app_start(int lcd_w, int lcd_h) { return gui_app_start_ex(lcd_w, lcd_h, APP_RES_ROOT); } int gui_app_start_ex(int lcd_w, int lcd_h, const char* res_root) { tk_init(lcd_w, lcd_h, APP_MOBILE, APP_NAME, res_root); #elif defined(MOBILE_APP) && defined(WITH_SDL) int SDL_main(int argc, char* argv[]) { int32_t lcd_w = 0; int32_t lcd_h = 0; tk_init(lcd_w, lcd_h, APP_MOBILE, APP_NAME, APP_RES_ROOT); #elif defined(WIN32) && !defined(MINGW) #include <windows.h> #ifndef MAX_ARGV #define MAX_ARGV 7 #endif static void command_line_to_argv(char* lpcmdline, char* argv[MAX_ARGV], int32_t* argc) { int32_t i = 1; char* p = lpcmdline; argv[0] = "awtk.exe"; if (p == NULL || *p == '\0') { argv[1] = NULL; return; } for (i = 1; i < MAX_ARGV; i++) { argv[i] = p; if (*p == '\"') { argv[i] = p + 1; p = strchr(p + 1, '\"'); if (p == NULL) break; *p++ = '\0'; if (*p == 0) break; } else { p = strchr(p, ' '); } if (p == NULL) { break; } while (*p == ' ') { *p++ = '\0'; } } *argc = i + 1; return; } int WINAPI wWinMain(HINSTANCE hinstance, HINSTANCE hprevinstance, LPWSTR lpcmdline, int ncmdshow) { str_t str; int argc = 1; char* argv[MAX_ARGV]; bool_t enable_console = APP_ENABLE_CONSOLE; int32_t lcd_w = LCD_WIDTH; int32_t lcd_h = LCD_HEIGHT; str_init(&str, 0); str_from_wstr(&str, lpcmdline); command_line_to_argv(str.str, argv, &argc); tk_pre_init(); #ifdef ON_CMD_LINE ON_CMD_LINE(argc, argv); #else if (argc >= 2) { lcd_w = tk_atoi(argv[1]); } if (argc >= 3) { lcd_h = tk_atoi(argv[2]); } if (argc >= 4) { enable_console = tk_atob(argv[3]); } #endif /*ON_CMD_LINE*/ if (enable_console) { TK_ENABLE_CONSOLE(); } tk_init(lcd_w, lcd_h, APP_TYPE, APP_NAME, APP_RES_ROOT); #else int main(int argc, char* argv[]) { bool_t enable_console = APP_ENABLE_CONSOLE; int32_t lcd_w = LCD_WIDTH; int32_t lcd_h = LCD_HEIGHT; tk_pre_init(); #ifdef ON_CMD_LINE (void)enable_console; ON_CMD_LINE(argc, argv); #else if (argc >= 2) { lcd_w = tk_atoi(argv[1]); } if (argc >= 3) { lcd_h = tk_atoi(argv[2]); } #ifdef WINDOWS if (argc >= 4) { enable_console = tk_atob(argv[3]); } if (enable_console) { TK_ENABLE_CONSOLE(); } #else (void)enable_console; #endif #endif /*ON_CMD_LINE*/ tk_init(lcd_w, lcd_h, APP_TYPE, APP_NAME, APP_RES_ROOT); #endif #ifdef ASSETS_ZIP assets_manager_set_res_root(assets_manager(), ""); log_debug("Load assets from zip: %s\n", ASSETS_ZIP); assets_manager_set_loader(assets_manager(), asset_loader_zip_create(ASSETS_ZIP)); #elif defined(ASSETS_CUSTOM_INIT) ASSETS_CUSTOM_INIT(); #endif /*ASSETS_ZIP*/ #if defined(WITH_LCD_PORTRAIT) if (lcd_w > lcd_h) { tk_set_lcd_orientation(LCD_ORIENTATION_90); } #endif /*WITH_LCD_PORTRAIT*/ #ifdef WITH_LCD_LANDSCAPE if (lcd_w < lcd_h) { tk_set_lcd_orientation(LCD_ORIENTATION_90); } #endif /*WITH_LCD_PORTRAIT*/ #ifndef TK_IS_PC #ifdef APP_LCD_ORIENTATION #if defined(APP_ENABLE_FAST_LCD_PORTRAIT) tk_enable_fast_lcd_portrait(TRUE); #endif tk_set_lcd_orientation(APP_LCD_ORIENTATION); #endif #endif/*TK_IS_PC*/ system_info_set_default_font(system_info(), APP_DEFAULT_FONT); assets_init(); #ifndef WITH_FS_RES locale_info_reload(locale_info()); #endif #ifndef WITHOUT_EXT_WIDGETS tk_ext_widgets_init(); #endif /*WITHOUT_EXT_WIDGETS*/ #ifdef NDEBUG log_set_log_level(LOG_LEVEL_INFO); #else log_set_log_level(LOG_LEVEL_DEBUG); #endif /*NDEBUG*/ log_info("Build at: %s %s\n", __DATE__, __TIME__); #ifdef ENABLE_CURSOR window_manager_set_cursor(window_manager(), "cursor"); #endif /*ENABLE_CURSOR*/ #ifdef WIN32 setvbuf(stdout, NULL, _IONBF, 0); #elif defined(HAS_STDIO) setlinebuf(stdout); #endif /*WIN32*/ GLOBAL_INIT(); #if defined(APP_DEFAULT_LANGUAGE) && defined(APP_DEFAULT_COUNTRY) locale_info_change(locale_info(), APP_DEFAULT_LANGUAGE, APP_DEFAULT_COUNTRY); #endif /*APP_DEFAULT_LANGUAGE and APP_DEFAULT_LANGUAGE*/ custom_keys_init(TRUE); application_init(); tk_run(); application_exit(); custom_keys_deinit(TRUE); GLOBAL_EXIT(); tk_exit(); FINAL_EXIT(); #ifdef HAS_STDIO fflush(stdout); #endif /*HAS_STDIO*/ #if defined(WIN32) && !defined(MINGW) str_reset(&str); #endif /*WIN32*/ #if defined(IOS) || defined(ANDROID) exit(0); #endif /*IOS | ANDROID*/ return 0; }
0
repos/awtk
repos/awtk/src/awtk_ext_widgets.h
/** * File: awtk.h * Author: AWTK Develop Team * Brief: awtk widgets * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-12-15 Li XianJing <[email protected]> created * */ #ifndef AWTK_EXT_WIDGETS_H #define AWTK_EXT_WIDGETS_H #include "vpage/vpage.h" #include "switch/switch.h" #include "gauge/gauge.h" #include "gauge/gauge_pointer.h" #include "gif_image/gif_image.h" #include "svg_image/svg_image.h" #include "keyboard/keyboard.h" #include "keyboard/candidates.h" #include "keyboard/lang_indicator.h" #include "base/widget_factory.h" #include "rich_text/rich_text.h" #include "rich_text/rich_text_view.h" #include "slide_menu/slide_menu.h" #include "image_value/image_value.h" #include "time_clock/time_clock.h" #include "scroll_view/list_item.h" #include "scroll_view/list_item_seperator.h" #include "scroll_view/list_view.h" #include "slide_view/slide_view.h" #include "slide_view/slide_indicator.h" #include "scroll_view/scroll_bar.h" #include "scroll_view/scroll_view.h" #include "scroll_view/list_view_h.h" #include "color_picker/color_picker.h" #include "canvas_widget/canvas_widget.h" #include "text_selector/text_selector.h" #include "color_picker/color_component.h" #include "progress_circle/progress_circle.h" #include "image_animation/image_animation.h" #include "mutable_image/mutable_image.h" #include "combo_box_ex/combo_box_ex.h" #include "scroll_label/hscroll_label.h" #include "mledit/line_number.h" #include "mledit/mledit.h" #include "features/draggable.h" #include "timer_widget/timer_widget.h" #include "serial_widget/serial_widget.h" #if defined(WITH_FS_RES) || defined(WITH_FS) #include "file_browser/file_chooser.h" #include "file_browser/file_browser_view.h" #endif /*WITH_FS*/ #include "ext_widgets/ext_widgets.h" #endif /*AWTK_EXT_WIDGETS_H*/
0
repos/awtk
repos/awtk/src/awtk_base.h
/** * File: awtk_tkc.h * Author: AWTK Develop Team * Brief: awtk toolkit c libs * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-12-15 Li XianJing <[email protected]> created * */ #ifndef TK_BASE_H #define TK_BASE_H #include "base/bidi.h" #include "base/ui_feedback.h" #include "base/assets_manager.h" #include "base/awtk_config_sample.h" #include "base/bitmap.h" #include "base/canvas.h" #include "base/canvas_offline.h" #include "base/children_layouter.h" #include "base/children_layouter_factory.h" #include "base/clip_board.h" #include "base/dialog_highlighter.h" #include "base/dialog_highlighter_factory.h" #include "base/enums.h" #include "base/event_queue.h" #include "base/events.h" #include "base/font.h" #include "base/font_loader.h" #include "base/font_manager.h" #include "base/g2d.h" #include "base/glyph_cache.h" #include "base/idle.h" #include "base/image_base.h" #include "base/image_loader.h" #include "base/image_manager.h" #include "base/input_device_status.h" #include "base/input_engine.h" #include "base/input_method.h" #include "base/keys.h" #include "base/layout.h" #include "base/layout_def.h" #include "base/lcd.h" #include "base/lcd_profile.h" #include "base/line_break.h" #include "base/locale_info.h" #include "base/main_loop.h" #include "base/pixel.h" #include "base/pixel_pack_unpack.h" #include "base/self_layouter.h" #include "base/self_layouter_factory.h" #include "base/shortcut.h" #include "base/style.h" #include "base/style_const.h" #include "base/style_factory.h" #include "base/suggest_words.h" #include "base/system_info.h" #include "base/theme.h" #include "base/timer.h" #include "base/types_def.h" #include "base/ui_builder.h" #include "base/ui_loader.h" #include "base/velocity.h" #include "base/vgcanvas.h" #include "base/widget.h" #include "base/widget_animator.h" #include "base/widget_animator_factory.h" #include "base/widget_animator_manager.h" #include "base/widget_consts.h" #include "base/widget_factory.h" #include "base/widget_vtable.h" #include "base/window_animator.h" #include "base/window_animator_factory.h" #include "base/window_base.h" #include "base/window_manager.h" #include "base/style_mutable.h" #endif /*TK_BASE_H*/
0
repos/awtk
repos/awtk/src/dllexports_for_tests.h
/** * @method canvas_draw_image_scale_h * @annotation ["global"] */ /** * @method canvas_draw_char * @annotation ["global"] */ /** * @method clip_board_default_create * @annotation ["global"] */ /** * @method combo_box_parse_options * @annotation ["global"] */ /** * @method digit_clock_format_time * @annotation ["global"] */ /** * @method edit_add_value_with_sep * @annotation ["global"] */ /** * @method edit_add_value_with_sep * @annotation ["global"] */ /** * @method edit_add_value_with_sep * @annotation ["global"] */ /** * @method edit_add_value_with_sep * @annotation ["global"] */ /** * @method edit_pre_input_with_sep * @annotation ["global"] */ /** * @method edit_pre_input_with_sep * @annotation ["global"] */ /** * @method edit_pre_input_with_sep * @annotation ["global"] */ /** * @method edit_pre_input_with_sep * @annotation ["global"] */ /** * @method edit_is_valid_value * @annotation ["global"] */ /** * @method edit_input_char * @annotation ["global"] */ /** * @method asset_type_find * @annotation ["global"] */ /** * @method event_queue_create * @annotation ["global"] */ /** * @method event_queue_recv * @annotation ["global"] */ /** * @method event_queue_send * @annotation ["global"] */ /** * @method event_queue_replace_last * @annotation ["global"] */ /** * @method event_queue_destroy * @annotation ["global"] */ /** * @method fb_filter_files_only * @annotation ["global"] */ /** * @method fb_filter_by_ext_names * @annotation ["global"] */ /** * @method fb_filter_directories_only * @annotation ["global"] */ /** * @method fb_compare_by_name * @annotation ["global"] */ /** * @method fb_compare_by_type * @annotation ["global"] */ /** * @method fb_compare_by_size * @annotation ["global"] */ /** * @method fb_compare_by_mtime * @annotation ["global"] */ /** * @method fb_compare_by_name_dec * @annotation ["global"] */ /** * @method fb_compare_by_type_dec * @annotation ["global"] */ /** * @method fb_compare_by_size_dec * @annotation ["global"] */ /** * @method fb_compare_by_mtime_dec * @annotation ["global"] */ /** * @method font_bitmap_create * @annotation ["global"] */ /** * @method gauge_pointer_set_anchor_for_str * @annotation ["global"] */ /** * @method idle_exist * @annotation ["global"] */ /** * @method image_animation_update * @annotation ["global"] */ /** * @method image_animation_get_image_name * @annotation ["global"] */ /** * @method bitmap_get_mem_size * @annotation ["global"] */ /** * @method image_manager_add * @annotation ["global"] */ /** * @method image_manager_lookup * @annotation ["global"] */ /** * @method image_value_add_delta * @annotation ["global"] */ /** * @method lcd_set_canvas * @annotation ["global"] */ /** * @method rich_text_text_create * @annotation ["global"] */ /** * @method rich_text_text_create * @annotation ["global"] */ /** * @method rich_text_image_create * @annotation ["global"] */ /** * @method rich_text_node_append * @annotation ["global"] */ /** * @method rich_text_node_count * @annotation ["global"] */ /** * @method rich_text_node_count * @annotation ["global"] */ /** * @method rich_text_node_destroy * @annotation ["global"] */ /** * @method rich_text_node_destroy * @annotation ["global"] */ /** * @method rich_text_node_destroy * @annotation ["global"] */ /** * @method rich_text_parse * @annotation ["global"] */ /** * @method rich_text_render_node_append * @annotation ["global"] */ /** * @method rich_text_render_node_count * @annotation ["global"] */ /** * @method rich_text_render_node_destroy * @annotation ["global"] */ /** * @method rich_text_render_node_create * @annotation ["global"] */ /** * @method widget_layout_self_menu_with_rect * @annotation ["global"] */ /** * @method widget_layout_self_set_trigger * @annotation ["global"] */ /** * @method slide_menu_fix_index * @annotation ["global"] */ /** * @method widget_destroy_sync * @annotation ["global"] */ /** * @method slide_view_get_prev * @annotation ["global"] */ /** * @method slide_view_get_next * @annotation ["global"] */ /** * @method slide_view_activate_prev * @annotation ["global"] */ /** * @method slide_view_activate_next * @annotation ["global"] */ /** * @method slider_dec * @annotation ["global"] */ /** * @method slider_inc * @annotation ["global"] */ /** * @method soft_rotate_image * @annotation ["global"] */ /** * @method str_table_lookup * @annotation ["global"] */ /** * @method svg_path_size * @annotation ["global"] */ /** * @method svg_path_move_init * @annotation ["global"] */ /** * @method svg_path_line_init * @annotation ["global"] */ /** * @method svg_path_curve_to_init * @annotation ["global"] */ /** * @method svg_shape_size * @annotation ["global"] */ /** * @method svg_shape_text_init * @annotation ["global"] */ /** * @method svg_shape_path_init * @annotation ["global"] */ /** * @method bsvg_visit * @annotation ["global"] */ /** * @method bsvg_builder_init * @annotation ["global"] */ /** * @method bsvg_builder_add_shape * @annotation ["global"] */ /** * @method bsvg_builder_add_sub_path * @annotation ["global"] */ /** * @method bsvg_builder_done * @annotation ["global"] */ /** * @method bsvg_to_svg_path * @annotation ["global"] */ /** * @method bsvg_to_svg_shape * @annotation ["global"] */ /** * @method bsvg_get_first_shape * @annotation ["global"] */ /** * @method system_info_eval_exprs * @annotation ["global"] */ /** * @method text_selector_parse_options * @annotation ["global"] */ /** * @method widget_has_focused_widget_in_window * @annotation ["global"] */ /** * @method widget_on_pointer_down * @annotation ["global"] */ /** * @method widget_on_pointer_move * @annotation ["global"] */ /** * @method widget_on_pointer_up * @annotation ["global"] */ /** * @method widget_is_focusable * @annotation ["global"] */ /** * @method widget_animator_time_elapse * @annotation ["global"] */ /** * @method widget_animator_time_elapse * @annotation ["global"] */ /** * @method widget_animator_time_elapse * @annotation ["global"] */ /** * @method widget_animator_time_elapse * @annotation ["global"] */ /** * @method widget_animator_time_elapse * @annotation ["global"] */ /** * @method bitmap_mono_create_data * @annotation ["global"] */ /** * @method bitmap_mono_create_data * @annotation ["global"] */ /** * @method bitmap_mono_get_pixel * @annotation ["global"] */ /** * @method bitmap_mono_get_pixel * @annotation ["global"] */ /** * @method bitmap_mono_set_pixel * @annotation ["global"] */ /** * @method bitmap_mono_set_pixel * @annotation ["global"] */ /** * @method canvas_draw_image_center * @annotation ["global"] */ /** * @method canvas_draw_image_patch3_x_scale_y * @annotation ["global"] */ /** * @method canvas_draw_image_patch3_y_scale_x * @annotation ["global"] */ /** * @method canvas_draw_image_patch9 * @annotation ["global"] */ /** * @method canvas_draw_image_repeat * @annotation ["global"] */ /** * @method canvas_draw_image_repeat_x * @annotation ["global"] */ /** * @method canvas_draw_image_repeat_y * @annotation ["global"] */ /** * @method canvas_draw_image_repeat_y_inverse * @annotation ["global"] */ /** * @method canvas_draw_image_repeat9 * @annotation ["global"] */ /** * @method canvas_draw_image_repeat3_x * @annotation ["global"] */ /** * @method canvas_draw_image_repeat3_y * @annotation ["global"] */ /** * @method canvas_draw_image_scale_w * @annotation ["global"] */ /** * @method assets_manager_build_asset_filename * @annotation ["global"] */ /** * @method canvas_draw_image_scale * @annotation ["global"] */
0
repos/awtk
repos/awtk/src/README.md
## 目录介绍 * **tkc** toolkit c library。 * **base** GUI 基本库。 * **widgets** 基本控件。 * **blend** 图片渲染函数。 * **lcd** LCD的各种实现。 * **font** 字体的各种实现。 * **misc** C++支持等。 * **xml** XML解析器。 * **widget\_animators** 控件动画实现。 * **ext\_widgets** 扩展控件。 * **main\_loop** 主循环的各种实现。 * **window\_animators** 窗口动画的实现。 * **image\_loader** 加载的各种实现。 * **platforms** 平台相关的函数。 * **input\_engines** 输入法引擎的各种实现。 * **ui\_loader** 从界面描述数据创建窗口。 * **vgcanvas** 矢量图画布。 * **svg** 矢量图画SVG。 * **clip\_board** 剪切板的实现。 * **ubjson** Universal Binary JSON实现。 * **window\_manager** 窗口管理器的实现。 * **native_window** 原生窗口的实现。 * **graphic_buffer** 图像数据缓冲区。 * **streams** 各种流的实现(如果不用可以不移植)。 * **compressors** 压缩算法的实现(如果不用可以不移植)。 * **conf_io** json/jni/ubjson 等配置文件读写。 * **csv** csv 文件读写。 ## 使用方法 应用程序只需包含awtk.h即可。 ``` #include "awtk.h" ```
0
repos/awtk
repos/awtk/src/dllexports.h
/** * 这个文件单纯用于脚本生成第三方库的导出函数 * */ /** * @method SDL_ShowCursor * Toggle whether or not the cursor is shown. * @annotation ["global"] * @param {int} toggle 1 to show the cursor, 0 to hide it, -1 to query the current state. * @return {int} 1 if the cursor is shown, or 0 if the cursor is hidden. */ /** * @method SDL_WarpMouseInWindow * Moves the mouse to the given position within the window. * @annotation ["global"] * @param {SDL_Window*} window 1 to show the cursor, 0 to hide it, -1 to query the current state. * @param {int} x The x coordinate within the window. * @param {int} y The y coordinate within the window. */ /** * @method SDL_GetDefaultCursor * Return the default cursor. * @annotation ["global"] * @return {SDL_Cursor*} the default cursor. */ /** * @method SDL_SetCursor * Set the active cursor. * @annotation ["global"] * @param {SDL_Cursor*} cursor cursor. */ /** * @method SDL_FreeCursor * Frees a cursor created with SDL_CreateCursor() or similar functions. * @annotation ["global"] * @param {SDL_Cursor*} cursor cursor. */ /** * @method SDL_CreateSystemCursor * Create a system cursor. * @annotation ["global"] * @param {SDL_SystemCursor} id id. * @return {SDL_Cursor*} the cursor. */ /** * @method SDL_GetMouseFocus * Get the window which currently has mouse focus. * @annotation ["global"] * @return {SDL_Window*} the window. */ /** * @method SDL_MixAudioFormat * @annotation ["global"] * @param {Uint8*} dst * @param {const Uint8*} src * @param {SDL_AudioFormat} format * @param {Uint32} len * @param {int} volume */ /** * @method SDL_DequeueAudio * @annotation ["global"] * @param {SDL_AudioDeviceID} dev The device ID from which we will dequeue audio. * @param {void*} data A pointer into where audio data should be copied. * @param {Uint32} len The number of bytes (not samples!) to which (data) points. * @return {Uint32} number of bytes dequeued, which could be less than requested. */ /** * @method SDL_QueueAudio * @annotation ["global"] * @param {SDL_AudioDeviceID} dev The device ID to which we will queue audio. * @param {const void*} data The data to queue to the device for later playback. * @param {Uint32} len The number of bytes (not samples!) to which (data) points. * @return {Uint32} 0 on success, or -1 on error. */ /** * @method SDL_GetQueuedAudioSize * @annotation ["global"] * @param {SDL_AudioDeviceID} dev The device ID of which we will query queued audio size. * @return {Uint32} Number of bytes (not samples!) of queued audio. */ /** * @method SDL_ClearQueuedAudio * @annotation ["global"] * @param {SDL_AudioDeviceID} dev The device ID of which to clear the audio queue. */ /** * @method SDL_PauseAudioDevice * @annotation ["global"] * @param {SDL_AudioDeviceID} dev * @param {int} pause_on */ /** * @method SDL_CloseAudioDevice * @annotation ["global"] * @param {SDL_AudioDeviceID} dev */ /** * @method SDL_OpenAudioDevice * @annotation ["global"] * @param {const char*} device * @param {int} iscapture * @param {const SDL_AudioSpec*} desired * @param {const SDL_AudioSpec*} obtained * @param {int} allowed_changes * @return {SDL_AudioDeviceID} 0 on error, a valid device ID that is >= 2 on success. */ /** * @method SDL_WasInit * @annotation ["global"] * @param {Uint32} flags * @return {Uint32} */ /** * @method SDL_Init * @annotation ["global"] * @param {Uint32} flags * @return {int} */ /** * @method SDL_GetError * @annotation ["global"] * @return {const char*} */ /** * @method SDL_CreateWindow * @annotation ["global"] * @return {int} */ /** * @method SDL_DestroyWindow * @annotation ["global"] * @return {int} */ /** * @method SDL_GL_CreateContext * @annotation ["global"] * @return {int} */ /** * @method SDL_GL_MakeCurrent * @annotation ["global"] * @return {int} */ /** * @method SDL_GL_GetDrawableSize * @annotation ["global"] * @return {int} */ /** * @method SDL_GL_DeleteContext * @annotation ["global"] * @return {int} */ SDL_GL_DeleteContext /** * @method SDL_GL_DeleteContext * @annotation ["global"] * @return {int} */ /** * @method SDL_GL_SwapWindow * @annotation ["global"] * @return {int} */ /** * @method SDL_GL_SetSwapInterval * @annotation ["global"] * @return {int} */ /** * @method SDL_GetWindowPosition * @annotation ["global"] * @return {int} */ /** * @method SDL_GetWindowSize * @annotation ["global"] * @return {int} */
0
repos/awtk
repos/awtk/src/awtk.h
/** * File: awtk.h * Author: AWTK Develop Team * Brief: awtk entry. * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-03-03 Li XianJing <[email protected]> created * */ #ifndef TK_AWTK_H #define TK_AWTK_H #include "awtk_version.h" #include "awtk_tkc.h" #include "awtk_base.h" #include "awtk_global.h" #include "awtk_widgets.h" #ifndef WITHOUT_EXT_WIDGETS #include "awtk_ext_widgets.h" #endif /*WITHOUT_EXT_WIDGETS*/ #endif /*TK_AWTK_H*/
0
repos/awtk
repos/awtk/src/awtk_widgets.h
/** * File: awtk.h * Author: AWTK Develop Team * Brief: awtk widgets * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-12-15 Li XianJing <[email protected]> created * */ #ifndef AWTK_WIDGETS_H #define AWTK_WIDGETS_H #include "base/dialog.h" #include "base/window.h" #include "widgets/app_bar.h" #include "widgets/button.h" #include "widgets/button_group.h" #include "widgets/calibration_win.h" #include "widgets/check_button.h" #include "widgets/color_tile.h" #include "widgets/clip_view.h" #include "widgets/column.h" #include "widgets/combo_box.h" #include "widgets/combo_box_item.h" #include "widgets/dialog_client.h" #include "widgets/dialog_title.h" #include "widgets/dragger.h" #include "widgets/edit.h" #include "widgets/grid.h" #include "widgets/grid_item.h" #include "widgets/group_box.h" #include "widgets/image.h" #include "widgets/label.h" #include "widgets/overlay.h" #include "widgets/pages.h" #include "widgets/popup.h" #include "widgets/progress_bar.h" #include "widgets/row.h" #include "widgets/slider.h" #include "widgets/spin_box.h" #include "widgets/system_bar.h" #include "widgets/tab_button.h" #include "widgets/tab_button_group.h" #include "widgets/tab_control.h" #include "widgets/view.h" #include "widgets/digit_clock.h" #endif /*AWTK_WIDGETS_H*/
0
repos/awtk
repos/awtk/src/awtk_global.c
/** * File: awtk.c * Author: AWTK Develop Team * Brief: awtk * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-03-03 Li XianJing <[email protected]> created * */ #include "awtk.h" #include "tkc/mem.h" #include "tkc/easing.h" #include "tkc/fscript.h" #include "base/idle.h" #include "base/timer.h" #include "tkc/thread.h" #include "tkc/time_now.h" #include "base/locale_info.h" #include "tkc/platform.h" #include "base/main_loop.h" #include "base/font_manager.h" #include "base/input_method.h" #include "base/image_manager.h" #include "base/window_manager.h" #include "base/widget_factory.h" #include "base/assets_manager.h" #include "fscript_ext/fscript_ext.h" #ifdef FSCRIPT_WITH_WIDGET #include "fscript_ext/fscript_widget.h" #endif /*FSCRIPT_WITH_WIDGET*/ #ifdef WITH_VGCANVAS #include "base/vgcanvas_asset_manager.h" #endif #ifdef WITH_SOCKET #include "tkc/socket_helper.h" #endif /*WITH_SOCKET*/ #ifdef WITH_FSCRIPT_EXT #ifndef WITH_DATA_READER_WRITER #define WITH_DATA_READER_WRITER #endif /*WITH_DATA_READER_WRITER*/ #endif /*WITH_FSCRIPT_EXT*/ #ifdef WITH_DATA_READER_WRITER #include "tkc/data_reader_factory.h" #include "tkc/data_writer_factory.h" #include "tkc/data_writer_file.h" #include "tkc/data_writer_wbuffer.h" #include "tkc/data_reader_file.h" #include "tkc/data_reader_mem.h" #include "base/data_reader_asset.h" #ifdef WITH_SOCKET #include "tkc/data_reader_http.h" #endif /*WITH_SOCKET*/ #endif /*WITH_DATA_READER_WRITER*/ #include "base/widget_animator_manager.h" #include "font_loader/font_loader_bitmap.h" #include "base/window_animator_factory.h" #include "widgets/widgets.h" #include "base/self_layouter_factory.h" #include "base/children_layouter_factory.h" #include "base/dialog_highlighter_factory.h" #ifndef WITHOUT_LAYOUT #include "layouters/self_layouter_builtins.h" #include "layouters/children_layouter_builtins.h" #endif /*WITHOUT_LAYOUT*/ #ifndef WITHOUT_WINDOW_ANIMATORS #include "window_animators/window_animator_builtins.h" #endif /*WITHOUT_WINDOW_ANIMATORS*/ #ifndef WITHOUT_DIALOG_HIGHLIGHTER #include "dialog_highlighters/dialog_highlighter_builtins.h" #endif /*WITHOUT_DIALOG_HIGHLIGHTER*/ #ifndef WITHOUT_CLIPBOARD #ifdef WITH_SDL #include "clip_board/clip_board_sdl.h" #define clip_board_create clip_board_sdl_create #else #include "clip_board/clip_board_default.h" #define clip_board_create clip_board_default_create #endif /*WITH_SDL*/ #endif /*WITHOUT_CLIPBOARD*/ #ifdef WITH_TRUETYPE_FONT #include "font_loader/font_loader_truetype.h" #endif /*WITH_TRUETYPE_FONT*/ #ifdef WITH_STB_IMAGE #include "image_loader/image_loader_stb.h" #endif /*WITH_STB_IMAGE*/ #ifdef AWTK_WEB #include "image_loader_web.h" #endif /*AWTK_WEB*/ static ret_t tk_add_font(const asset_info_t* res) { if (res->subtype == ASSET_TYPE_FONT_BMP) { #ifdef WITH_BITMAP_FONT font_manager_add_font(font_manager(), font_bitmap_create(asset_info_get_name(res), res->data, res->size)); #endif } else if (res->subtype == ASSET_TYPE_FONT_TTF) { #ifdef WITH_TRUETYPE_FONT font_manager_add_font(font_manager(), font_truetype_create(asset_info_get_name(res), res->data, res->size)); #endif /*WITH_TRUETYPE_FONT*/ } else { log_debug("not support font type:%d\n", res->subtype); } return RET_OK; } ret_t tk_init_assets(void) { uint32_t i = 0; uint32_t nr = assets_manager()->assets.size; const asset_info_t** all = (const asset_info_t**)(assets_manager()->assets.elms); for (i = 0; i < nr; i++) { const asset_info_t* iter = all[i]; switch (iter->type) { case ASSET_TYPE_FONT: tk_add_font(iter); break; case ASSET_TYPE_STYLE: { theme_t* t = theme(); const char* iter_name = asset_info_get_name(iter); if ((t == NULL || t->data == NULL) && tk_str_eq(iter_name, TK_DEFAULT_STYLE)) { theme_set(theme_load_from_data(iter_name, iter->data, iter->size)); } break; } } } return RET_OK; } static ret_t tk_clear_cache_when_oom(uint32_t tried_times) { if (tried_times == 1) { image_manager_unload_unused(image_manager(), 10); font_manager_shrink_cache(font_manager(), 10); } else if (tried_times == 2) { image_manager_unload_unused(image_manager(), 0); font_manager_shrink_cache(font_manager(), 0); } else if (tried_times == 3) { event_t e = event_init(EVT_LOW_MEMORY, NULL); font_manager_unload_all(font_manager()); widget_dispatch(window_manager(), &e); } else { event_t e = event_init(EVT_OUT_OF_MEMORY, NULL); widget_dispatch(window_manager(), &e); } return RET_OK; } static tk_semaphore_t* s_clear_cache_semaphore = NULL; static ret_t exec_clear_cache(exec_info_t* info) { uint32_t tried_times = (uint32_t)tk_pointer_to_int(info->ctx); tk_clear_cache_when_oom(tried_times); tk_semaphore_post(s_clear_cache_semaphore); log_debug("clear cache: %u\n", tried_times); return RET_REMOVE; } static ret_t awtk_mem_on_out_of_memory(void* ctx, uint32_t tried_times, uint32_t need_size) { if (tk_is_ui_thread()) { tk_clear_cache_when_oom(tried_times); } else { event_queue_req_t req; memset(&req, 0x00, sizeof(req)); req.exec_in_ui.e.type = REQ_EXEC_IN_UI; req.exec_in_ui.info.func = exec_clear_cache; req.exec_in_ui.info.ctx = tk_pointer_from_int(tried_times); log_debug("req clear cache begin: %u\n", tried_times); main_loop_queue_event(main_loop(), &req); tk_semaphore_wait(s_clear_cache_semaphore, 10000); log_debug("req clear cache done: %u\n", tried_times); } return RET_OK; } ret_t tk_init_internal(void) { font_loader_t* font_loader = NULL; tk_set_ui_thread(tk_thread_self()); #ifndef WITHOUT_FSCRIPT fscript_global_init(); #endif #ifdef WITH_FSCRIPT_EXT fscript_ext_init(); #ifdef FSCRIPT_WITH_WIDGET fscript_widget_register(); #endif /*FSCRIPT_WITH_WIDGET*/ #endif /*WITH_FSCRIPT_EXT*/ #ifdef WITH_STB_IMAGE image_loader_register(image_loader_stb()); #endif /*WITH_STB_IMAGE*/ #ifdef AWTK_WEB image_loader_register(image_loader_web()); #endif /*AWTK_WEB*/ #ifdef WITH_TRUETYPE_FONT font_loader = font_loader_truetype(); #elif defined(WITH_BITMAP_FONT) font_loader = font_loader_bitmap(); #endif /*WITH_TRUETYPE_FONT*/ return_value_if_fail(easing_init() == RET_OK, RET_FAIL); return_value_if_fail(timer_prepare(time_now_ms) == RET_OK, RET_FAIL); return_value_if_fail(idle_manager_set(idle_manager_create()) == RET_OK, RET_FAIL); return_value_if_fail(widget_factory_set(widget_factory_create()) == RET_OK, RET_FAIL); return_value_if_fail(assets_manager_set(assets_manager_create(30)) == RET_OK, RET_FAIL); #ifndef WITHOUT_INPUT_METHOD return_value_if_fail(input_method_set(input_method_create()) == RET_OK, RET_FAIL); #endif /*WITHOUT_INPUT_METHOD*/ #ifdef WITH_VGCANVAS return_value_if_fail(vgcanvas_asset_manager_set(vgcanvas_asset_manager_create()) == RET_OK, RET_FAIL); #endif return_value_if_fail(locale_info_set(locale_info_create(NULL, NULL)) == RET_OK, RET_FAIL); return_value_if_fail(font_manager_set(font_manager_create(font_loader)) == RET_OK, RET_FAIL); return_value_if_fail(font_manager_set_assets_manager(font_manager(), assets_manager()) == RET_OK, RET_FAIL); return_value_if_fail(image_manager_set(image_manager_create()) == RET_OK, RET_FAIL); #ifndef WITHOUT_WINDOW_ANIMATORS return_value_if_fail(window_animator_factory_set(window_animator_factory_create()) == RET_OK, RET_FAIL); window_animator_register_builtins(); #endif /*WITHOUT_WIDGET_ANIMATORS*/ #ifndef WITHOUT_DIALOG_HIGHLIGHTER return_value_if_fail( dialog_highlighter_factory_set(dialog_highlighter_factory_create()) == RET_OK, RET_FAIL); #endif /*WITHOUT_DIALOG_HIGHLIGHTER*/ #ifndef WITHOUT_LAYOUT return_value_if_fail(children_layouter_factory_set(children_layouter_factory_create()) == RET_OK, RET_FAIL); return_value_if_fail(self_layouter_factory_set(self_layouter_factory_create()) == RET_OK, RET_FAIL); self_layouter_register_builtins(); children_layouter_register_builtins(); #endif /*WITHOUT_LAYOUT*/ return_value_if_fail(window_manager_set(window_manager_create()) == RET_OK, RET_FAIL); #ifndef WITHOUT_CLIPBOARD return_value_if_fail(clip_board_set(clip_board_create()) == RET_OK, RET_FAIL); #endif /*WITHOUT_CLIPBOARD*/ #ifndef WITHOUT_WIDGET_ANIMATORS return_value_if_fail(widget_animator_manager_set(widget_animator_manager_create()) == RET_OK, RET_FAIL); #endif /*WITHOUT_WIDGET_ANIMATORS*/ #ifndef WITHOUT_DIALOG_HIGHLIGHTER dialog_highlighter_register_builtins(); #endif /*WITHOUT_DIALOG_HIGHLIGHTER*/ tk_widgets_init(); tk_mem_set_on_out_of_memory(awtk_mem_on_out_of_memory, NULL); s_clear_cache_semaphore = tk_semaphore_create(0, "clear_cache"); return RET_OK; } ret_t tk_pre_init(void) { static bool_t inited = FALSE; if (!inited) { return_value_if_fail(platform_prepare() == RET_OK, RET_FAIL); return_value_if_fail(tk_mem_init_stage2() == RET_OK, RET_FAIL); #ifdef WITH_DATA_READER_WRITER data_writer_factory_set(data_writer_factory_create()); data_reader_factory_set(data_reader_factory_create()); data_writer_factory_register(data_writer_factory(), "file", data_writer_file_create); data_reader_factory_register(data_reader_factory(), "file", data_reader_file_create); data_reader_factory_register(data_reader_factory(), "asset", data_reader_asset_create); data_reader_factory_register(data_reader_factory(), "mem", data_reader_mem_create); data_writer_factory_register(data_writer_factory(), "wbuffer", data_writer_wbuffer_create); #ifdef WITH_SOCKET data_reader_factory_register(data_reader_factory(), "http", data_reader_http_create); #ifdef WITH_MBEDTLS data_reader_factory_register(data_reader_factory(), "https", data_reader_http_create); #endif /*WITH_MBEDTLS*/ #endif /*WITH_SOCKET*/ #endif /*WITH_DATA_READER_WRITER*/ inited = TRUE; } return RET_OK; } #if WITH_MAIN_LOOP_CONSOLE #include "main_loop/main_loop_console.h" #endif /*WITH_MAIN_LOOP_CONSOLE*/ ret_t tk_init(wh_t w, wh_t h, app_type_t app_type, const char* app_name, const char* app_root) { main_loop_t* loop = NULL; return_value_if_fail(tk_pre_init() == RET_OK, RET_FAIL); ENSURE(system_info_init(app_type, app_name, app_root) == RET_OK); return_value_if_fail(tk_init_internal() == RET_OK, RET_FAIL); if (APP_CONSOLE == system_info()->app_type) { #if WITH_MAIN_LOOP_CONSOLE loop = (main_loop_t*)main_loop_console_init(); #else assert(!"APP_CONSOLE not supported"); #endif /*WITH_MAIN_LOOP_CONSOLE*/ } else { loop = main_loop_init(w, h); } return_value_if_fail(loop != NULL, RET_FAIL); #ifdef WITH_SOCKET tk_socket_init(); #endif /*WITH_SOCKET*/ return RET_OK; } ret_t tk_deinit_internal(void) { idle_manager_dispatch(idle_manager()); #ifndef WITHOUT_CLIPBOARD clip_board_destroy(clip_board()); clip_board_set(NULL); #endif /*WITHOUT_CLIPBOARD*/ #ifndef WITHOUT_LAYOUT children_layouter_factory_destroy(children_layouter_factory()); children_layouter_factory_set(NULL); self_layouter_factory_destroy(self_layouter_factory()); self_layouter_factory_set(NULL); #endif /*WITHOUT_LAYOUT*/ image_manager_destroy(image_manager()); image_manager_set(NULL); window_manager_close_all(window_manager()); widget_factory_destroy(widget_factory()); widget_factory_set(NULL); idle_manager_dispatch(idle_manager()); window_manager_destroy(window_manager()); window_manager_set(NULL); #ifndef WITHOUT_INPUT_METHOD input_method_destroy(input_method()); input_method_set(NULL); #endif /*WITHOUT_INPUT_METHOD*/ #ifndef WITHOUT_DIALOG_HIGHLIGHTER dialog_highlighter_factory_destroy(dialog_highlighter_factory()); dialog_highlighter_factory_set(NULL); #endif /*WITHOUT_DIALOG_HIGHLIGHTER*/ #ifndef WITHOUT_WINDOW_ANIMATORS window_animator_factory_destroy(window_animator_factory()); window_animator_factory_set(NULL); #endif /*WITHOUT_WINDOW_ANIMATORS*/ #ifndef WITHOUT_WIDGET_ANIMATORS widget_animator_manager_destroy(widget_animator_manager()); widget_animator_manager_set(NULL); #endif /*WITHOUT_WIDGET_ANIMATORS*/ easing_deinit(); timer_manager_destroy(timer_manager()); timer_manager_set(NULL); idle_manager_destroy(idle_manager()); idle_manager_set(NULL); theme_destroy(theme()); theme_set(NULL); font_manager_destroy(font_manager()); font_manager_set(NULL); locale_info_destroy(locale_info()); locale_info_set(NULL); assets_manager_destroy(assets_manager()); assets_manager_set(NULL); assets_managers_clear_applet_res_roots(); #ifdef WITH_VGCANVAS vgcanvas_asset_manager_destroy(vgcanvas_asset_manager()); vgcanvas_asset_manager_set(NULL); #endif #ifdef WITH_DATA_READER_WRITER data_writer_factory_destroy(data_writer_factory()); data_reader_factory_destroy(data_reader_factory()); data_writer_factory_set(NULL); data_reader_factory_set(NULL); #endif /*WITH_DATA_READER_WRITER*/ system_info_deinit(); #ifndef WITHOUT_FSCRIPT fscript_global_deinit(); #endif tk_semaphore_destroy(s_clear_cache_semaphore); #ifdef WITH_SOCKET tk_socket_deinit(); #endif /*WITH_SOCKET*/ return RET_OK; } ret_t tk_exit(void) { main_loop_destroy(main_loop()); main_loop_set(NULL); return tk_deinit_internal(); } ret_t tk_run() { return main_loop_run(main_loop()); } static ret_t tk_quit_in_timer(const timer_info_t* timer) { main_loop_t* loop = main_loop(); loop->app_quited = TRUE; return main_loop_quit(loop); } ret_t tk_quit_ex(uint32_t delay_ms) { timer_add(tk_quit_in_timer, NULL, delay_ms); return RET_OK; } ret_t tk_quit() { return tk_quit_ex(0); } ret_t tk_set_lcd_orientation(lcd_orientation_t orientation) { main_loop_t* loop = main_loop(); lcd_orientation_t old_orientation; system_info_t* info = system_info(); return_value_if_fail(loop != NULL && info != NULL, RET_OK); if (info->lcd_orientation != orientation) { orientation_event_t e; old_orientation = info->lcd_orientation; system_info_set_lcd_orientation(info, orientation); orientation_event_init(&e, EVT_ORIENTATION_WILL_CHANGED, NULL, old_orientation, orientation); widget_dispatch(window_manager(), (event_t*)&e); } return RET_OK; } ret_t tk_enable_fast_lcd_portrait(bool_t enable) { system_info_t* info = system_info(); return_value_if_fail(info != NULL, RET_BAD_PARAMS); #if defined(WITH_FAST_LCD_PORTRAIT) if (enable) { info->flags |= SYSTEM_INFO_FLAG_FAST_LCD_PORTRAIT; } else { info->flags &= ~SYSTEM_INFO_FLAG_FAST_LCD_PORTRAIT; } return RET_OK; #else return RET_FAIL; #endif } int32_t tk_get_pointer_x(void) { return window_manager_get_pointer_x(window_manager()); } int32_t tk_get_pointer_y(void) { return window_manager_get_pointer_y(window_manager()); } bool_t tk_is_pointer_pressed(void) { return window_manager_get_pointer_pressed(window_manager()); } typedef struct _idle_callback_info_t { void* ctx; bool_t done; bool_t sync; ret_t result; tk_callback_t func; } idle_callback_info_t; static idle_callback_info_t* idle_callback_info_create(tk_callback_t func, void* ctx) { idle_callback_info_t* info = TKMEM_ZALLOC(idle_callback_info_t); return_value_if_fail(info != NULL, NULL); info->func = func; info->ctx = ctx; return info; } static ret_t idle_callback_info_destroy(idle_callback_info_t* info) { return_value_if_fail(info != NULL && info->func != NULL, RET_BAD_PARAMS); memset(info, 0x00, sizeof(*info)); TKMEM_FREE(info); return RET_OK; } static ret_t idle_func_of_callback(const idle_info_t* info) { idle_callback_info_t* cinfo = (idle_callback_info_t*)(info->ctx); ret_t ret = cinfo->func(cinfo->ctx); if (cinfo->sync) { cinfo->done = TRUE; cinfo->result = ret; /*call by sync not allow repeat*/ assert(ret != RET_REPEAT); return RET_REMOVE; } else { if (ret != RET_REPEAT) { idle_callback_info_destroy(cinfo); ret = RET_REMOVE; } return ret; } } ret_t tk_run_in_ui_thread(tk_callback_t func, void* ctx, bool_t wait_until_done) { return_value_if_fail(func != NULL, RET_BAD_PARAMS); if (tk_is_ui_thread()) { return func(ctx); } else { idle_callback_info_t* info = idle_callback_info_create(func, ctx); return_value_if_fail(info != NULL, RET_OOM); info->sync = wait_until_done; if (idle_queue(idle_func_of_callback, info) == RET_OK) { ret_t ret = RET_OK; if (wait_until_done) { while (!(info->done)) { sleep_ms(20); } ret = info->result; idle_callback_info_destroy(info); } return ret; } else { idle_callback_info_destroy(info); return RET_FAIL; } } }
0
repos/awtk
repos/awtk/src/awtk_global.h
/** * File: awtk.h * Author: AWTK Develop Team * Brief: awtk * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-03-03 Li XianJing <[email protected]> created * */ #ifndef TK_GLOBAL_H #define TK_GLOBAL_H #include "base/types_def.h" BEGIN_C_DECLS /** * @class global_t * @annotation ["scriptable", "fake"] * TK全局对象。 */ /** * @method tk_pre_init * 初始化基本功能。 *> 在tk_init之前,应用程序可能需要加载配置文件, *> 为了保证这些功能正常工作,可以先调用tk_pre_init来初始化平台、内存和data reader等等。 * * @alias pre_init * @annotation ["static", "scriptable"] * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t tk_pre_init(void); /** * @method tk_init * 初始化TK。 * @alias init * @annotation ["static", "scriptable"] * @param {wh_t} w LCD宽度。 * @param {wh_t} h LCD高度。 * @param {app_type_t} app_type 应用程序的类型。 * @param {const char*} app_name 应用程序的名称(必须为常量字符串)。 * @param {const char*} app_root 应用程序的根目录,用于定位资源文件(必须为常量字符串)。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t tk_init(wh_t w, wh_t h, app_type_t app_type, const char* app_name, const char* app_root); /** * @method tk_run * 进入TK事件主循环。 * @alias run * @annotation ["static", "scriptable"] * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t tk_run(void); /** * @method tk_quit * 退出TK事件主循环。 * @alias global_quit * @annotation ["static", "scriptable"] * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t tk_quit(void); /** * @method tk_quit_ex * 退出TK事件主循环。 * @alias global_quit_ex * @annotation ["static", "scriptable"] * * @param {uint32_t} delay 延迟退出的时间(毫秒)。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t tk_quit_ex(uint32_t delay); /** * @method tk_get_pointer_x * 获取全局指针的X坐标。 * @alias global_get_pointer_x * @annotation ["static", "scriptable"] * * @return {int32_t} 返回全局指针的X坐标。 */ int32_t tk_get_pointer_x(void); /** * @method tk_get_pointer_y * 获取全局指针的Y坐标。 * @alias global_get_pointer_y * @annotation ["static", "scriptable"] * * @return {int32_t} 返回全局指针的X坐标。 */ int32_t tk_get_pointer_y(void); /** * @method tk_is_pointer_pressed * 获取全局指针是否按下。 * @alias global_is_pointer_pressed * @annotation ["static", "scriptable"] * * @return {bool_t} 返回全局指针是否按下。 */ bool_t tk_is_pointer_pressed(void); /** * @method tk_set_lcd_orientation * 设置屏幕的旋转方向(XXX:目前仅支持0度,90度,180度和270度,旋转方向为逆时针方向)。 * @param {lcd_orientation_t} orientation 旋转方向。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t tk_set_lcd_orientation(lcd_orientation_t orientation); /** * @method tk_enable_fast_lcd_portrait * 设置是否开启快速旋转功能。(开启这个功能需要定义 WITH_FAST_LCD_PORTRAIT 宏) * 备注:需要在 tk_set_lcd_orientation 函数之前调用 * @param {bool_t} enable 是否开启。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t tk_enable_fast_lcd_portrait(bool_t enable); /** * @method tk_init_assets * 初始化资源。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t tk_init_assets(void); /** * @method tk_init_internal * init。 *> public for test program * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t tk_init_internal(void); /** * @method tk_deinit_internal * deinit。 *> public for test program * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t tk_deinit_internal(void); /** * @method tk_exit * public for web * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t tk_exit(void); /** * @method tk_run_in_ui_thread * 后台线程在UI线程执行指定的函数。 * * @param {tk_callback_t} func 函数。 * @param {void*} ctx 回调函数的上下文。 * @param {bool_t} wait_until_done 是否等待完成。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t tk_run_in_ui_thread(tk_callback_t func, void* ctx, bool_t wait_until_done); END_C_DECLS #endif /*TK_GLOBAL_H*/
0
repos/awtk/src
repos/awtk/src/romfs/romfs.c
/** * File: romfs.c * Author: AWTK Develop Team * Brief: romfs * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2023-07-27 Li XianJing <[email protected]> adapt from uclib * */ #include "tkc/fs.h" #include "tkc/mem.h" #include "tkc/utils.h" #include "conf_io/conf_node.h" #include "conf_io/conf_ubjson.h" typedef struct _romfs_fs_t { fs_t fs; uint32_t header_size; uint32_t body_size; const uint8_t* header_data; const uint8_t* body_data; conf_doc_t* doc; } romfs_fs_t; typedef struct _romfs_file_t { int32_t size; int32_t offset; const uint8_t* data; } romfs_file_t; static int32_t romfs_file_read(fs_file_t* file, void* buffer, uint32_t size) { romfs_file_t* fp = (romfs_file_t*)(file->data); int32_t rsize = (fp->offset + size) <= fp->size ? size : (fp->size - fp->offset); memcpy(buffer, fp->data + fp->offset, rsize); fp->offset += rsize; return rsize; } static int32_t romfs_file_write(fs_file_t* file, const void* buffer, uint32_t size) { return RET_NOT_IMPL; } static int32_t romfs_file_printf(fs_file_t* file, const char* const format_str, va_list vl) { return RET_NOT_IMPL; } static ret_t romfs_file_seek(fs_file_t* file, int32_t offset) { romfs_file_t* fp = (romfs_file_t*)(file->data); fp->offset = offset; return RET_OK; } static int64_t romfs_file_tell(fs_file_t* file) { romfs_file_t* fp = (romfs_file_t*)(file->data); return fp->offset; } static int64_t romfs_file_size(fs_file_t* file) { romfs_file_t* fp = (romfs_file_t*)(file->data); return fp->size; } static ret_t romfs_file_stat(fs_file_t* file, fs_stat_info_t* fst) { romfs_file_t* fp = (romfs_file_t*)(file->data); memset(fst, 0x00, sizeof(*fst)); fst->size = fp->size; fst->is_reg_file = TRUE; return RET_OK; } static ret_t romfs_file_sync(fs_file_t* file) { return RET_NOT_IMPL; } static ret_t romfs_file_truncate(fs_file_t* file, int32_t size) { return RET_NOT_IMPL; } static bool_t romfs_file_eof(fs_file_t* file) { romfs_file_t* fp = (romfs_file_t*)(file->data); return fp->offset >= fp->size; } static ret_t romfs_file_close(fs_file_t* file) { TKMEM_FREE(file); return RET_OK; } typedef struct _romfs_dir_t { conf_node_t* first; conf_node_t* iter; } romfs_dir_t; static ret_t romfs_dir_rewind(fs_dir_t* dir) { romfs_dir_t* d = (romfs_dir_t*)(dir->data); d->iter = d->first; return RET_OK; } static ret_t romfs_dir_read(fs_dir_t* dir, fs_item_t* item) { romfs_dir_t* d = (romfs_dir_t*)(dir->data); memset(item, 0x00, sizeof(fs_item_t)); if (d->iter != NULL) { value_t v; if (conf_node_get_child_value(d->iter, "name", &v) == RET_OK) { tk_strncpy(item->name, value_str(&v), MAX_PATH); } if (conf_node_get_child_value(d->iter, "type", &v) == RET_OK) { item->is_dir = tk_str_eq(value_str(&v), "dir"); item->is_reg_file = tk_str_eq(value_str(&v), "file"); } d->iter = d->iter->next; return RET_OK; } else { return RET_FAIL; } } static ret_t romfs_dir_close(fs_dir_t* dir) { romfs_dir_t* d = (romfs_dir_t*)dir->data; TKMEM_FREE(d); TKMEM_FREE(dir); return RET_OK; } static const fs_file_vtable_t s_file_vtable = {.read = romfs_file_read, .write = romfs_file_write, .printf = romfs_file_printf, .seek = romfs_file_seek, .tell = romfs_file_tell, .size = romfs_file_size, .stat = romfs_file_stat, .sync = romfs_file_sync, .truncate = romfs_file_truncate, .eof = romfs_file_eof, .close = romfs_file_close}; static ret_t romfs_file_destory(romfs_file_t* fp) { TKMEM_FREE(fp); return RET_OK; } static fs_file_t* fs_file_create(romfs_file_t* fp) { fs_file_t* f = NULL; return_value_if_fail(fp != NULL, NULL); f = TKMEM_ZALLOC(fs_file_t); if (f != NULL) { f->vt = &s_file_vtable; f->data = fp; } else { romfs_file_destory(fp); } return f; } static conf_node_t* romfs_find_node(conf_node_t* node, const char* name) { value_t v; char curr_name[MAX_PATH + 1] = {0}; const char* p = strchr(name, '/'); conf_node_t* iter = conf_node_get_first_child(node); if (p == NULL) { p = strchr(name, '\\'); } if (p != NULL) { tk_strncpy(curr_name, name, p - name); name = p + 1; } else { tk_strncpy(curr_name, name, sizeof(curr_name) - 1); name = NULL; } while (iter != NULL) { if (conf_node_get_child_value(iter, "name", &v) == RET_OK) { if (tk_str_eq(value_str(&v), curr_name)) { if (name == NULL) { return iter; } else { conf_node_t* children = conf_node_find_child(iter, "children"); if (children != NULL) { return romfs_find_node(children, name); } else { return NULL; } } } } iter = iter->next; } return NULL; } static romfs_file_t* romfs_file_create(fs_t* fs, const char* name) { conf_node_t* node = NULL; romfs_fs_t* rfs = (romfs_fs_t*)fs; romfs_file_t* file = NULL; node = romfs_find_node(rfs->doc->root, name); if (node != NULL) { value_t v; file = TKMEM_ZALLOC(romfs_file_t); return_value_if_fail(file != NULL, NULL); file->offset = 0; if (conf_node_get_child_value(node, "size", &v) == RET_OK) { file->size = value_int(&v); } if (conf_node_get_child_value(node, "data", &v) == RET_OK) { file->data = rfs->body_data + value_uint32(&v); assert(value_uint32(&v) < rfs->body_size); } } return file; } static fs_file_t* romfs_open_file(fs_t* fs, const char* name, const char* mode) { return_value_if_fail(name != NULL && mode != NULL, NULL); return fs_file_create(romfs_file_create(fs, name)); } static ret_t romfs_remove_file(fs_t* fs, const char* name) { return RET_NOT_IMPL; } static bool_t romfs_file_exist(fs_t* fs, const char* name) { fs_stat_info_t st; return_value_if_fail(name != NULL, FALSE); if (fs_stat(fs, name, &st) == RET_OK) { return st.is_reg_file; } else { return FALSE; } } static ret_t romfs_file_rename(fs_t* fs, const char* name, const char* new_name) { return RET_NOT_IMPL; } static const fs_dir_vtable_t s_dir_vtable = { .read = romfs_dir_read, .rewind = romfs_dir_rewind, .close = romfs_dir_close}; static romfs_dir_t* romfs_dir_create(fs_t* fs, const char* name) { romfs_dir_t* dir = NULL; romfs_fs_t* rfs = (romfs_fs_t*)fs; conf_node_t* node = romfs_find_node(rfs->doc->root, name); return_value_if_fail(node != NULL, NULL); node = conf_node_find_child(node, "children"); return_value_if_fail(node != NULL, NULL); node = conf_node_get_first_child(node); dir = TKMEM_ZALLOC(romfs_dir_t); return_value_if_fail(dir != NULL, NULL); dir->first = node; dir->iter = node; return dir; } static fs_dir_t* romfs_open_dir(fs_t* fs, const char* name) { fs_dir_t* dir = NULL; romfs_dir_t* rdir = romfs_dir_create(fs, name); return_value_if_fail(rdir != NULL, NULL); dir = TKMEM_ZALLOC(fs_dir_t); if (dir != NULL) { dir->vt = &s_dir_vtable; dir->data = rdir; } else { TKMEM_FREE(rdir); } return dir; } static ret_t romfs_remove_dir(fs_t* fs, const char* name) { return RET_NOT_IMPL; } static ret_t romfs_change_dir(fs_t* fs, const char* name) { return RET_NOT_IMPL; } static ret_t romfs_create_dir(fs_t* fs, const char* name) { return RET_NOT_IMPL; } static bool_t romfs_dir_exist(fs_t* fs, const char* name) { fs_stat_info_t st; return_value_if_fail(name != NULL, FALSE); if (fs_stat(fs, name, &st) == RET_OK) { return st.is_dir; } else { return FALSE; } } static ret_t romfs_dir_rename(fs_t* fs, const char* name, const char* new_name) { return romfs_file_rename(fs, name, new_name); } static int32_t romfs_get_file_size(fs_t* fs, const char* name) { fs_stat_info_t st; return_value_if_fail(name != NULL, FALSE); if (fs_stat(fs, name, &st) == RET_OK && st.is_reg_file) { return st.size; } else { return -1; } } static ret_t romfs_get_disk_info(fs_t* fs, const char* volume, int32_t* free_kb, int32_t* total_kb) { return RET_NOT_IMPL; } static ret_t romfs_get_exe(fs_t* fs, char path[MAX_PATH + 1]) { strcpy(path, "/bin/app"); return RET_OK; } static ret_t romfs_get_temp_path(fs_t* fs, char path[MAX_PATH + 1]) { return RET_NOT_IMPL; } static ret_t romfs_get_user_storage_path(fs_t* fs, char path[MAX_PATH + 1]) { return RET_NOT_IMPL; } static ret_t romfs_get_cwd(fs_t* fs, char path[MAX_PATH + 1]) { return RET_NOT_IMPL; } static ret_t romfs_stat(fs_t* fs, const char* name, fs_stat_info_t* fst) { conf_node_t* node = NULL; romfs_fs_t* rfs = (romfs_fs_t*)fs; return_value_if_fail(rfs->doc != NULL && rfs->doc->root != NULL, RET_BAD_PARAMS); node = romfs_find_node(rfs->doc->root, name); if (node != NULL) { value_t v; memset(fst, 0x00, sizeof(fs_stat_info_t)); if (conf_node_get_child_value(node, "size", &v) == RET_OK) { fst->size = value_int(&v); } if (conf_node_get_child_value(node, "type", &v) == RET_OK) { fst->is_dir = tk_str_eq(value_str(&v), "dir"); fst->is_reg_file = tk_str_eq(value_str(&v), "file"); } return RET_OK; } else { return RET_NOT_FOUND; } } static romfs_fs_t s_romfs_fs = {.fs = { .open_file = romfs_open_file, .remove_file = romfs_remove_file, .file_exist = romfs_file_exist, .file_rename = romfs_file_rename, .open_dir = romfs_open_dir, .remove_dir = romfs_remove_dir, .create_dir = romfs_create_dir, .change_dir = romfs_change_dir, .dir_exist = romfs_dir_exist, .dir_rename = romfs_dir_rename, .get_file_size = romfs_get_file_size, .get_disk_info = romfs_get_disk_info, .get_cwd = romfs_get_cwd, .get_exe = romfs_get_exe, .get_user_storage_path = romfs_get_user_storage_path, .get_temp_path = romfs_get_temp_path, .stat = romfs_stat, }, .header_size = 0, .body_size = 0, .header_data = NULL, .body_data = NULL, .doc = NULL}; ret_t romfs_init(const uint8_t* header_data, uint32_t header_size, const uint8_t* body_data, uint32_t body_size) { return_value_if_fail(header_data != NULL && body_data != NULL, RET_BAD_PARAMS); return_value_if_fail(s_romfs_fs.doc == NULL, RET_BAD_PARAMS); s_romfs_fs.body_data = body_data; s_romfs_fs.header_data = header_data; s_romfs_fs.body_size = body_size; s_romfs_fs.header_size = header_size; s_romfs_fs.doc = conf_doc_load_ubjson(header_data, header_size); return RET_OK; } ret_t romfs_deinit(void) { return_value_if_fail(s_romfs_fs.doc != NULL, RET_BAD_PARAMS); conf_doc_destroy(s_romfs_fs.doc); s_romfs_fs.doc = NULL; return RET_OK; } fs_t* romfs_get(void) { return (fs_t*)&s_romfs_fs; } #if defined(WITH_ROMFS_AS_OS_FS) || defined(AWTK_WEB) fs_t* os_fs(void) { return_value_if_fail(s_romfs_fs.doc != NULL, NULL); return (fs_t*)&s_romfs_fs; } #endif /*WITH_ROMFS_AS_OS_FS*/
0
repos/awtk/src
repos/awtk/src/romfs/test.sh
./bin/romfs_make tests foo find tests | sed 's/^[^/]*\///' | while read -r file do ./bin/romfs_read foo $file t if [ -d "tests/$file" ]; then echo "$file 是目录" else result=$(cmp tests/$file t) if [ $? -eq 0 ]; then echo "文件相同" else echo "tests/$file t 不同" fi fi done rm -f foo.* t ./bin/romfs_make tests foo true find tests | while read -r file do ./bin/romfs_read foo $file t if [ -d "$file" ]; then echo "$file 是目录" else result=$(cmp $file t) if [ $? -eq 0 ]; then echo "文件相同" else echo "$file t 不同" fi fi done rm -f foo.* t
0
repos/awtk/src
repos/awtk/src/romfs/romfs.h
/** * File: romfs.c * Author: AWTK Develop Team * Brief: romfs * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2023-07-27 Li XianJing <[email protected]> adapt from uclib * */ #ifndef TK_ROMFS_H #define TK_ROMFS_H #include "tkc/value.h" #include "tkc/types_def.h" BEGIN_C_DECLS /** * @class romfs_t * 一个简单的ROMFS(目前用于WEB加载配置文件) */ /** * @method romfs_init * 初始化。 * @param {const uint8_t*} header_data 文件信息数据。 * @param {uint32_t} header_size 文件信息数据长度。 * @param {const uint8_t*} body_data 文件数据。 * @param {uint32_t} body_size 文件数据长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t romfs_init(const uint8_t* header_data, uint32_t header_size, const uint8_t* body_data, uint32_t body_size); /** * @method romfs_deinit * ~初始化。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t romfs_deinit(void); /** * @method romfs_get * 获取fs对象。 * * @return {fs_t*} 返回fs对象。 */ fs_t* romfs_get(void); END_C_DECLS #endif /*TK_ROMFS_H*/
0
repos/awtk/src
repos/awtk/src/romfs/romfs_maker.c
/** * File: romfs_maker.c * Author: AWTK Develop Team * Brief: romfs maker * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2023-07-27 Li XianJing <[email protected]> adapt from uclib * */ #include "tkc/fs.h" #include "tkc/mem.h" #include "tkc/path.h" #include "tkc/utils.h" #include "tkc/buffer.h" #include "ubjson/ubjson_writer.h" static ret_t make_romfs_one_level(const char* path, ubjson_writer_t* writer, uint32_t* offset, fs_file_t* fp); static ret_t make_romfs_dir(const char* filename, const char* name, ubjson_writer_t* writer, uint32_t* offset, fs_file_t* fp) { ubjson_writer_write_object_begin(writer); ubjson_writer_write_kv_str(writer, "name", name); ubjson_writer_write_kv_str(writer, "type", "dir"); ubjson_writer_write_kv_array_begin(writer, "children"); make_romfs_one_level(filename, writer, offset, fp); ubjson_writer_write_array_end(writer); ubjson_writer_write_object_end(writer); return RET_OK; } static ret_t make_romfs_one_level(const char* path, ubjson_writer_t* writer, uint32_t* offset, fs_file_t* fp) { fs_item_t item; fs_t* fs = os_fs(); fs_dir_t* dir = NULL; char filename[MAX_PATH + 1]; return_value_if_fail(path != NULL && writer != NULL && offset != NULL, RET_BAD_PARAMS); dir = fs_open_dir(fs, path); return_value_if_fail(dir != NULL, RET_BAD_PARAMS); while (fs_dir_read(dir, &item) == RET_OK) { if (tk_str_eq(item.name, ".") || tk_str_eq(item.name, "..")) { continue; } path_build(filename, MAX_PATH, path, item.name, NULL); if (item.is_reg_file) { uint32_t size = 0; void* data = file_read(filename, &size); assert(data != NULL); assert(fs_file_write(fp, data, size) == size); TKMEM_FREE(data); ubjson_writer_write_object_begin(writer); ubjson_writer_write_kv_str(writer, "name", item.name); ubjson_writer_write_kv_int(writer, "size", size); ubjson_writer_write_kv_int(writer, "data", *offset); ubjson_writer_write_kv_str(writer, "type", "file"); ubjson_writer_write_object_end(writer); *offset += size; } else if (item.is_dir) { make_romfs_dir(filename, item.name, writer, offset, fp); } } fs_dir_close(dir); return RET_OK; } static ret_t make_romfs(const char* path, const char* header_filename, const char* body_filename, bool_t with_folder_name) { wbuffer_t wb; ubjson_writer_t ub; ret_t ret = RET_OK; fs_file_t* fp = NULL; ubjson_writer_t* writer = &ub; return_value_if_fail(path != NULL, RET_BAD_PARAMS); return_value_if_fail(header_filename != NULL && body_filename != NULL, RET_BAD_PARAMS); wbuffer_init_extendable(&wb); ubjson_writer_init(writer, (ubjson_write_callback_t)wbuffer_write_binary, &wb); log_debug("%s => %s\n", path, header_filename); fp = fs_open_file(os_fs(), body_filename, "wb+"); if (fp != NULL) { uint32_t offset = 0; if (with_folder_name) { char name[MAX_PATH + 1] = {0}; path_basename(path, name, sizeof(name) - 1); ubjson_writer_write_array_begin(writer); make_romfs_dir(path, name, writer, &offset, fp); ubjson_writer_write_array_end(writer); } else { ubjson_writer_write_array_begin(writer); ret = make_romfs_one_level(path, writer, &offset, fp); ubjson_writer_write_array_end(writer); } fs_file_close(fp); if (ret == RET_OK) { file_write(header_filename, wb.data, wb.cursor); } } wbuffer_deinit(&wb); return RET_OK; } int main(int argc, char* argv[]) { const char* path = NULL; const char* name = NULL; char header_filename[MAX_PATH + 1] = {0}; char body_filename[MAX_PATH + 1] = {0}; bool_t with_folder_name = FALSE; if (argc < 3) { log_info("Usage: %s dir name [with_folder_name]\n", argv[0]); return -1; } path = argv[1]; name = argv[2]; if (argc > 3) { with_folder_name = tk_atob(argv[3]); } tk_snprintf(header_filename, sizeof(header_filename), "%s.header", name); tk_snprintf(body_filename, sizeof(body_filename), "%s.body", name); make_romfs(path, header_filename, body_filename, with_folder_name); return 0; }
0
repos/awtk/src
repos/awtk/src/romfs/README.md
# ROMFS 一个简单的只读文件系统,并不是标准的 ROMFS,主要用于方便 WEB 访问配置数据。 ## 将文件夹打包成 ROMFS 映像。 * 用法 ``` ./bin/romfs_make 目录 映像名 ``` * 示例 ``` ./bin/romfs_make tests foo ``` > 将目录 tests 打包成 ROMFS 映像,foo.header 存放文件信息,foo.body 存放文件数据。 ## 从 ROMFS 映像读取文件或目录 * 用法 ``` ./bin/romfs_read 映像名 文件名 输出文件名 ``` * 示例 ``` ./bin/romfs_read foo fscripts/demo_udp.fs output.fs ``` > 从 foo 中读取文件 fscripts/demo_udp.fs,写入 output.fs。如果文件名是目录,则将目录列表输出到输出文件中。
0
repos/awtk/src
repos/awtk/src/romfs/romfs_read.c
/** * File: romfs_read.c * Author: AWTK Develop Team * Brief: romfs read * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2023-07-27 Li XianJing <[email protected]> adapt from uclib * */ #include "romfs.c" static ret_t romfs_read(const char* filename, const char* output_filename) { fs_t* fs = romfs_get(); fs_stat_info_t info; if (fs_stat(fs, filename, &info) == RET_OK) { if (info.is_reg_file) { uint32_t i = 0; uint32_t size = info.size; fs_file_t* fp = fs_open_file(fs, filename, "rb"); uint8_t* buff1 = (uint8_t*)TKMEM_ALLOC(size); uint8_t* buff2 = (uint8_t*)TKMEM_ALLOC(size); /*test*/ for (i = 0; i < size; i++) { ENSURE(fs_file_tell(fp) == i); ENSURE(fs_file_read(fp, buff1 + i, 1) == 1); } ENSURE(fs_file_eof(fp)); ENSURE(fs_file_read(fp, buff2, size) == 0); ENSURE(fs_file_seek(fp, 0) == RET_OK); ENSURE(fs_file_tell(fp) == 0); ENSURE(fs_file_read(fp, buff2, size) == size); ENSURE(fs_file_eof(fp)); ENSURE(memcmp(buff1, buff2, size) == 0); file_write(output_filename, buff2, size); TKMEM_FREE(buff1); TKMEM_FREE(buff2); fs_file_close(fp); } else { fs_dir_t* dir = fs_open_dir(fs, filename); if (dir != NULL) { str_t str; fs_item_t item; str_init(&str, 100); while (fs_dir_read(dir, &item) == RET_OK) { str_append_format(&str, MAX_PATH, "[%s] %s\n", item.is_reg_file ? "file" : "dir ", item.name); } file_write(output_filename, str.str, str.size); str_reset(&str); fs_dir_close(dir); } } log_debug("%s => %s\n", filename, output_filename); } else { log_debug("not found %s\n", filename); } return RET_OK; } int main(int argc, char* argv[]) { if (argc != 4) { log_debug("Usage: %s romfs filename output_filename\n", argv[0]); return 0; } else { uint32_t header_size = 0; uint8_t* header_data = NULL; uint32_t body_size = 0; uint8_t* body_data = NULL; char header_filename[MAX_PATH + 1]; char body_filename[MAX_PATH + 1]; const char* romfs = argv[1]; const char* filename = argv[2]; const char* output_filename = argv[3]; tk_snprintf(header_filename, sizeof(header_filename) - 1, "%s.header", romfs); header_data = file_read(header_filename, &header_size); tk_snprintf(body_filename, sizeof(body_filename) - 1, "%s.body", romfs); body_data = file_read(body_filename, &body_size); if (header_data != NULL && body_data != NULL) { romfs_init(header_data, header_size, body_data, body_size); } romfs_read(filename, output_filename); TKMEM_FREE(header_data); TKMEM_FREE(body_data); romfs_deinit(); } return 0; }
0
repos/awtk/src
repos/awtk/src/hal/network_interface.h
/** * File: network_interface.h * Author: AWTK Develop Team * Brief: network_interface * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-02-3 pengguowen<[email protected]> created * */ #ifndef _NETWORK_INTERFACE_H_ #define _NETWORK_INTERFACE_H_ #include "tkc/types_def.h" #include "tkc/object.h" BEGIN_C_DECLS typedef struct _network_interface_t network_interface_t; /** * @enum network_interface_wifi_auth_t * @prefix NETWORK_INTERFACE_WIFI_AUTH_ * 属性描述WIFI的认证方式。 */ typedef enum _network_interface_wifi_auth_t { /** * @const NETWORK_INTERFACE_WIFI_AUTH_WEP * WEP认证。 */ NETWORK_INTERFACE_WIFI_AUTH_WEP = 1, /** * @const NETWORK_INTERFACE_WIFI_AUTH_WPAWPA2 * WPA/WPA2 认证。 */ NETWORK_INTERFACE_WIFI_AUTH_WPAWPA2, /** * @const NETWORK_INTERFACE_WIFI_AUTH_NONE * 无认证。 */ NETWORK_INTERFACE_WIFI_AUTH_NONE } network_interface_wifi_auth_t; /** * @enum network_interface_wifi_freq_t * @prefix NETWORK_INTERFACE_WIFI_FREQ_ * 属性描述WIFI的频段。 */ typedef enum _network_interface_wifi_freq_t { /** * @const NETWORK_INTERFACE_WIFI_FREQ_2_4G * 2.4G频段。 */ NETWORK_INTERFACE_WIFI_FREQ_2_4G = 1, /** * @const NETWORK_INTERFACE_WIFI_FREQ_5G * 5G频段。 */ NETWORK_INTERFACE_WIFI_FREQ_5G } network_interface_wifi_freq_t; /** * @enum network_interface_type_t * @prefix NETWORK_INTERFACE_TYPE_ * 属性描述网卡类型。 */ typedef enum _network_interface_type_t { /** * @const NETWORK_INTERFACE_TYPE_ETH * 以太网。 */ NETWORK_INTERFACE_TYPE_ETH = 1, /** * @const NETWORK_INTERFACE_TYPE_WIFI * WIFI。 */ NETWORK_INTERFACE_TYPE_WIFI, /** * @const NETWORK_INTERFACE_TYPE_MOBILE * 3G/4G/5G。 */ NETWORK_INTERFACE_TYPE_MOBILE, /** * @const NETWORK_INTERFACE_TYPE_UNKNOWN * 未知类型。 */ NETWORK_INTERFACE_TYPE_UNKNOWN } network_interface_type_t; typedef void (*network_interface_destroy_t)(network_interface_t* interface); typedef ret_t (*network_interface_enable_t)(network_interface_t* interface); typedef ret_t (*network_interface_disable_t)(network_interface_t* interface); typedef char* (*network_interface_get_ipaddr_t)(network_interface_t* interface); typedef char* (*network_interface_get_macaddr_t)(network_interface_t* interface); typedef int (*network_interface_get_status_t)(network_interface_t* interface); typedef int (*network_interface_get_quality_t)(network_interface_t* interface); typedef ret_t (*network_interface_set_ipaddr_t)(network_interface_t* interface, const char* ipaddr, const char* netmask); typedef ret_t (*network_interface_set_dns_t)(network_interface_t* interface, const char* dns); typedef ret_t (*network_interface_set_dhcp_t)(network_interface_t* interface); typedef ret_t (*network_interface_set_gateway_t)(network_interface_t* interface, const char* gateway, const char* dev); typedef ret_t (*network_interface_set_wifi_sta_t)(network_interface_t* interface, const char* essid, const char* passwd, network_interface_wifi_auth_t auth); typedef ret_t (*network_interface_set_wifi_ap_t)(network_interface_t* interface, const char* essid, const char* passwd, network_interface_wifi_auth_t auth, uint8_t channel, network_interface_wifi_freq_t freq, uint8_t hidden); typedef struct _network_interface_vtable_t { const char* type; const char* desc; network_interface_enable_t enable; network_interface_disable_t disable; network_interface_destroy_t destroy; network_interface_get_ipaddr_t get_ipaddr; network_interface_get_macaddr_t get_macaddr; network_interface_get_status_t get_status; network_interface_get_quality_t get_quality; network_interface_set_ipaddr_t set_ipaddr; network_interface_set_dns_t set_dns; network_interface_set_gateway_t set_gateway; network_interface_set_dhcp_t set_dhcp; network_interface_set_wifi_ap_t set_wifi_ap; network_interface_set_wifi_sta_t set_wif_sta; } network_interface_vtable_t; /** * @class network_interface_t * 网卡接口。 */ struct _network_interface_t { const network_interface_vtable_t* vt; char* interface_name; network_interface_type_t type; }; /** * @method network_interface_create * 网卡接口创建函数。 * * @param {const char*} interface 网卡名。 * @param {network_interface_type_t} type 网卡接口类型。 * * @return {network_interface_t*} 网卡接口对象。 */ network_interface_t* network_interface_create(const char* interface, network_interface_type_t type); /** * @method network_interface_enable * 网卡接口使能函数。 * * @param {network_interface_t *} interface 网卡对象。 * * @return {ret_t} RET_OK表示成功,否则失败。 */ ret_t network_interface_enable(network_interface_t* interface); /** * @method network_interface_disable * 网卡接口禁能函数。 * * @param {network_interface_t *} interface 网卡对象。 * * @return {ret_t} RET_OK表示成功,否则失败。 */ ret_t network_interface_disable(network_interface_t* interface); /** * @method network_interface_get_ipaddr * 网卡接口获取IP地址。 * * @param {network_interface_t *} interface 网卡对象。 * * @return {char *} 返回IP地址成功,NULL失败。 */ char* network_interface_get_ipaddr(network_interface_t* interface); /** * @method network_interface_get_macaddr * 网卡接口获取MAC地址。 * * @param {network_interface_t *} interface 网卡对象。 * * @return {char *} 返回MAC地址成功,NULL失败。 */ char* network_interface_get_macaddr(network_interface_t* interface); /** * @method network_interface_get_status * 网卡接口获取状态。 * * @param {network_interface_t *} interface 网卡对象。 * * @return {int} 0表示未连接,1表示连接成功,-1表示操作失败。 */ int network_interface_get_status(network_interface_t* interface); /** * @method network_interface_get_quality * 网卡接口获取通信质量。 * * @param {network_interface_t *} interface 网卡对象。 * * @return {int} 对于无线网络返回信号RSSI的绝对值, 对于有线网络,返回10、100、1000M带宽。 */ int network_interface_get_quality(network_interface_t* interface); /** * @method network_interface_set_ipaddr * 网卡接口设置IP地址。 * * @param {network_interface_t *} interface 网卡对象。 * @param {const char*} ipaddr 网卡IP。 * @param {const char*} netmask 网卡MASK。 * * @return {ret_t} RET_OK表示成功,否则失败。 */ ret_t network_interface_set_ipaddr(network_interface_t* interface, const char* ipaddr, const char* netmask); /** * @method network_interface_set_dns * 网卡接口设置DNS。 * * @param {network_interface_t *} interface 网卡对象。 * @param {const char*} dns 网卡dns。 * * @return {ret_t} RET_OK表示成功,否则失败。 */ ret_t network_interface_set_dns(network_interface_t* interface, const char* dns); /** * @method network_interface_set_dhcp * 网卡接口设置DNS。 * * @param {network_interface_t *} interface 网卡对象。 * * @return {ret_t} RET_OK表示成功,否则失败。 */ ret_t network_interface_set_dhcp(network_interface_t* interface); /** * @method network_interface_set_gateway * 网卡接口设置DNS。 * * @param {network_interface_t *} interface 网卡对象。 * @param {const char*} gateway 网卡网关。 * @param {const char*} dev 出口网卡设备名。 * * @return {ret_t} RET_OK表示成功,否则失败。 */ ret_t network_interface_set_gateway(network_interface_t* interface, const char* gateway, const char* dev); /** * @method network_interface_set_wifi_sta * 网卡接口设置WIFI STA模式。 * * @param {network_interface_t *} interface 网卡对象。 * @param {const char*} essid wifi帐号 。 * @param {const char*} passwd wifi密码。 * @param {network_interface_wifi_auth_t } auth wifi认证方式。 * * @return {ret_t} RET_OK表示成功,否则失败。 */ ret_t network_interface_set_wifi_sta(network_interface_t* interface, const char* essid, const char* passwd, network_interface_wifi_auth_t auth); /** * @method network_interface_set_wifi_ap * 网卡接口设置WIFI AP模式。 * * @param {network_interface_t *} interface 网卡对象。 * @param {const char*} essid wifi帐号 。 * @param {const char*} passwd wifi密码。 * @param {network_interface_wifi_auth_t } auth wifi认证方式。 * @param {uint8_t } channel wifi通道。 * @param {network_interface_wifi_freq_t } freq wifi频段。 * @param {uint8_t } hidden wifi是否隐藏。 * * @return {ret_t} RET_OK表示成功,否则失败。 */ ret_t network_interface_set_wifi_ap(network_interface_t* interface, const char* essid, const char* passwd, network_interface_wifi_auth_t auth, uint8_t channel, network_interface_wifi_freq_t freq, uint8_t hidden); /** * @method network_interface_destroy * 网卡接口销毁函数。 * * @param {network_interface_t *} interface 网卡对象。 * * @return {void}。 */ void network_interface_destroy(network_interface_t* interface); END_C_DECLS #endif
0
repos/awtk/src
repos/awtk/src/hal/network_interface.c
/** * File: network_interface.c * Author: AWTK Develop Team * Brief: network_interface * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-02-3 pengguowen<[email protected]> created * */ #include "network_interface.h" ret_t network_interface_enable(network_interface_t* interface) { return_value_if_fail(interface != NULL && interface->vt != NULL && interface->vt->enable != NULL, RET_FAIL); return interface->vt->enable(interface); } ret_t network_interface_disable(network_interface_t* interface) { return_value_if_fail(interface != NULL && interface->vt != NULL && interface->vt->disable != NULL, RET_FAIL); return interface->vt->disable(interface); } void network_interface_destroy(network_interface_t* interface) { if (interface != NULL && interface->vt != NULL && interface->vt->destroy != NULL) interface->vt->destroy(interface); } char* network_interface_get_ipaddr(network_interface_t* interface) { return_value_if_fail( interface != NULL && interface->vt != NULL && interface->vt->get_ipaddr != NULL, NULL); return interface->vt->get_ipaddr(interface); } char* network_interface_get_macaddr(network_interface_t* interface) { return_value_if_fail( interface != NULL && interface->vt != NULL && interface->vt->get_macaddr != NULL, NULL); return interface->vt->get_macaddr(interface); } int network_interface_get_status(network_interface_t* interface) { return_value_if_fail( interface != NULL && interface->vt != NULL && interface->vt->get_status != NULL, -1); return interface->vt->get_status(interface); } int network_interface_get_quality(network_interface_t* interface) { return_value_if_fail( interface != NULL && interface->vt != NULL && interface->vt->get_quality != NULL, -1); return interface->vt->get_quality(interface); } ret_t network_interface_set_ipaddr(network_interface_t* interface, const char* ipaddr, const char* netmask) { return_value_if_fail( interface != NULL && interface->vt != NULL && interface->vt->set_ipaddr != NULL, RET_FAIL); return interface->vt->set_ipaddr(interface, ipaddr, netmask); } ret_t network_interface_set_dns(network_interface_t* interface, const char* dns) { return_value_if_fail(interface != NULL && interface->vt != NULL && interface->vt->set_dns != NULL, RET_FAIL); return interface->vt->set_dns(interface, dns); } ret_t network_interface_set_gateway(network_interface_t* interface, const char* gateway, const char* dev) { return_value_if_fail( interface != NULL && interface->vt != NULL && interface->vt->set_gateway != NULL, RET_FAIL); return interface->vt->set_gateway(interface, gateway, dev); } ret_t network_interface_set_dhcp(network_interface_t* interface) { return_value_if_fail( interface != NULL && interface->vt != NULL && interface->vt->set_dhcp != NULL, RET_FAIL); return interface->vt->set_dhcp(interface); } ret_t network_interface_set_wifi_sta(network_interface_t* interface, const char* essid, const char* passwd, network_interface_wifi_auth_t auth) { return_value_if_fail( interface != NULL && interface->vt != NULL && interface->vt->set_wif_sta != NULL, RET_FAIL); return_value_if_fail(interface->type == NETWORK_INTERFACE_TYPE_WIFI, RET_FAIL); return interface->vt->set_wif_sta(interface, essid, passwd, auth); } ret_t network_interface_set_wifi_ap(network_interface_t* interface, const char* essid, const char* passwd, network_interface_wifi_auth_t auth, uint8_t channel, network_interface_wifi_freq_t freq, uint8_t hidden) { return_value_if_fail( interface != NULL && interface->vt != NULL && interface->vt->set_wifi_ap != NULL, RET_FAIL); return_value_if_fail(interface->type == NETWORK_INTERFACE_TYPE_WIFI, RET_FAIL); return interface->vt->set_wifi_ap(interface, essid, passwd, auth, channel, freq, hidden); }
0
repos/awtk/src/hal
repos/awtk/src/hal/linux/network_interface_linux.c
/** * File: network_interface_linux.c * Author: AWTK Develop Team * Brief: network_interface for linux * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-02-3 pengguowen<[email protected]> created * */ #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <sys/types.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <net/if.h> #include "tkc/mem.h" #include "tkc/utils.h" #include "tkc/object_default.h" #include "hal/network_interface.h" typedef struct _network_interface_linux_t { network_interface_t network_interface; char* ipaddr; char* macaddr; } network_interface_linux_t; static ret_t network_interface_linux_enable(network_interface_t* interface) { char command[128]; int ret; return_value_if_fail(interface != NULL, RET_FAIL); snprintf(command, sizeof(command), "ifconfig %s up", interface->interface_name); ret = system(command); if (WEXITSTATUS(ret) != 0) return RET_FAIL; return RET_OK; } static ret_t network_interface_linux_disable(network_interface_t* interface) { char command[128]; int ret; return_value_if_fail(interface != NULL, RET_FAIL); snprintf(command, sizeof(command), "ifconfig %s down", interface->interface_name); ret = system(command); if (WEXITSTATUS(ret) != 0) return RET_FAIL; return RET_OK; } static char* network_interface_linux_get_ipaddr(network_interface_t* interface) { char ipstr[16]; uint8_t ipaddr[4]; struct ifreq ifr; struct sockaddr_in* addr = NULL; network_interface_linux_t* linux_network_interface = (network_interface_linux_t*)interface; int fd = socket(PF_INET, SOCK_DGRAM, 0); return_value_if_fail(fd > 0, NULL); strcpy(ifr.ifr_name, interface->interface_name); if (ioctl(fd, SIOCGIFADDR, &ifr) < 0) { close(fd); return NULL; } addr = (struct sockaddr_in*)&ifr.ifr_addr; *((u_int32_t*)ipaddr) = addr->sin_addr.s_addr; snprintf(ipstr, sizeof(ipstr), "%d.%d.%d.%d", ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]); close(fd); if (linux_network_interface->ipaddr != NULL) TKMEM_FREE(linux_network_interface->ipaddr); linux_network_interface->ipaddr = tk_strdup(ipstr); return linux_network_interface->ipaddr; } static char* network_interface_linux_get_macaddr(network_interface_t* interface) { int fd; struct ifreq ifr; uint8_t m[6]; char macstr[18]; network_interface_linux_t* linux_network_interface = (network_interface_linux_t*)interface; fd = socket(PF_INET, SOCK_DGRAM, 0); return_value_if_fail(fd > 0, NULL); strcpy(ifr.ifr_name, interface->interface_name); if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) { close(fd); return NULL; } memcpy(m, ifr.ifr_hwaddr.sa_data, 6); snprintf(macstr, sizeof(macstr), "%02x:%02x:%02x:%02x:%02x:%02x", m[0], m[1], m[2], m[3], m[4], m[5]); close(fd); if (linux_network_interface->macaddr != NULL) TKMEM_FREE(linux_network_interface->macaddr); linux_network_interface->macaddr = tk_strdup(macstr); return linux_network_interface->macaddr; } static int network_interface_linux_eth_get_status(network_interface_t* interface) { char carrier_path[128]; char carrier; int fd; snprintf(carrier_path, sizeof(carrier_path), "/sys/class/net/%s/carrier", interface->interface_name); fd = open(carrier_path, O_RDONLY); return_value_if_fail(fd > 0, -1); if (read(fd, &carrier, 1) <= 0) { close(fd); return 0; } close(fd); if (carrier == '1') return 1; else return 0; } static int network_interface_linux_eth_get_quality(network_interface_t* interface) { char speed_path[128]; int fd; char speed[12]; int val; snprintf(speed_path, sizeof(speed_path), "/sys/class/net/%s/speed", interface->interface_name); fd = open(speed_path, O_RDONLY); return_value_if_fail(fd > 0, -1); if (read(fd, speed, sizeof(speed)) <= 0) { close(fd); return -1; } close(fd); val = strtol(speed, NULL, 10); return val; } static ret_t network_interface_linux_set_ipaddr(network_interface_t* interface, const char* ipaddr, const char* netmask) { char command[128]; int ret; return_value_if_fail(interface != NULL, RET_FAIL); snprintf(command, sizeof(command), "ifconfig %s %s netmask %s", interface->interface_name, ipaddr, netmask); ret = system(command); if (WEXITSTATUS(ret) != 0) return RET_FAIL; return RET_OK; } static ret_t network_interface_linux_set_dns(network_interface_t* interface, const char* dns) { char command[128]; int ret; return_value_if_fail(interface != NULL, RET_FAIL); snprintf(command, sizeof(command), "echo \"nameserver %s\" > /etc/resolv.conf", dns); ret = system(command); if (WEXITSTATUS(ret) != 0) return RET_FAIL; return RET_OK; } static ret_t network_interface_linux_set_dhcp(network_interface_t* interface) { char command[128]; int ret; return_value_if_fail(interface != NULL, RET_FAIL); snprintf(command, sizeof(command), "udhcpc -i %s &", interface->interface_name); ret = system(command); if (WEXITSTATUS(ret) != 0) return RET_FAIL; return RET_OK; } static ret_t network_interface_linux_set_gateway(network_interface_t* interface, const char* gateway, const char* dev) { return RET_OK; } static ret_t network_interface_linux_set_wifi_sta(network_interface_t* interface, const char* essid, const char* passwd, network_interface_wifi_auth_t auth) { return RET_OK; } static ret_t network_interface_linux_set_wifi_ap(network_interface_t* interface, const char* essid, const char* passwd, network_interface_wifi_auth_t auth, uint8_t channel, network_interface_wifi_freq_t freq, uint8_t hidden) { return RET_OK; } static int network_interface_linux_wifi_get_status(network_interface_t* interface) { return 0; } static int network_interface_linux_wifi_get_quality(network_interface_t* interface) { return 0; } static int network_interface_linux_mobile_get_status(network_interface_t* interface) { return 0; } static int network_interface_linux_mobile_get_quality(network_interface_t* interface) { return 0; } static void network_interface_linux_destroy(network_interface_t* interface) { network_interface_linux_t* linux_network_interface = (network_interface_linux_t*)interface; TKMEM_FREE(interface->interface_name); TKMEM_FREE(interface); if (linux_network_interface->ipaddr != NULL) TKMEM_FREE(linux_network_interface->ipaddr); if (linux_network_interface->macaddr != NULL) TKMEM_FREE(linux_network_interface->macaddr); } static const network_interface_vtable_t s_linux_eth_vtable = { .type = "linux_eth", .desc = "vtable for linux eth device", .enable = network_interface_linux_enable, .disable = network_interface_linux_disable, .destroy = network_interface_linux_destroy, .get_ipaddr = network_interface_linux_get_ipaddr, .get_macaddr = network_interface_linux_get_macaddr, .get_quality = network_interface_linux_eth_get_quality, .get_status = network_interface_linux_eth_get_status, .set_ipaddr = network_interface_linux_set_ipaddr, .set_dhcp = network_interface_linux_set_dhcp, .set_dns = network_interface_linux_set_dns, .set_gateway = network_interface_linux_set_gateway, }; static const network_interface_vtable_t s_linux_wifi_vtable = { .type = "linux_wifi", .desc = "vtable for linux wifi device", .enable = network_interface_linux_enable, .disable = network_interface_linux_disable, .destroy = network_interface_linux_destroy, .get_ipaddr = network_interface_linux_get_ipaddr, .get_macaddr = network_interface_linux_get_macaddr, .get_quality = network_interface_linux_wifi_get_quality, .get_status = network_interface_linux_wifi_get_status, .set_ipaddr = network_interface_linux_set_ipaddr, .set_dns = network_interface_linux_set_dns, .set_dhcp = network_interface_linux_set_dhcp, .set_gateway = network_interface_linux_set_gateway, .set_wif_sta = network_interface_linux_set_wifi_sta, .set_wifi_ap = network_interface_linux_set_wifi_ap, }; static const network_interface_vtable_t s_linux_mobile_vtable = { .type = "linux_mobile", .desc = "vtable for linux mobile device", .enable = network_interface_linux_enable, .disable = network_interface_linux_disable, .destroy = network_interface_linux_destroy, .get_quality = network_interface_linux_mobile_get_quality, .get_status = network_interface_linux_mobile_get_status, }; static const network_interface_vtable_t s_linux_unknown_vtable = { .type = "linux_unknown_network", .desc = "vtable for linux common network", .get_ipaddr = network_interface_linux_get_ipaddr, .get_macaddr = network_interface_linux_get_macaddr, }; network_interface_t* network_interface_create(const char* interface, network_interface_type_t type) { network_interface_linux_t* linux_network_interface = TKMEM_ZALLOC(network_interface_linux_t); return_value_if_fail(linux_network_interface != NULL, NULL); linux_network_interface->network_interface.interface_name = tk_strdup(interface); linux_network_interface->network_interface.type = type; linux_network_interface->ipaddr = NULL; linux_network_interface->macaddr = NULL; if (type == NETWORK_INTERFACE_TYPE_ETH) linux_network_interface->network_interface.vt = &s_linux_eth_vtable; else if (type == NETWORK_INTERFACE_TYPE_WIFI) linux_network_interface->network_interface.vt = &s_linux_wifi_vtable; else if (type == NETWORK_INTERFACE_TYPE_MOBILE) linux_network_interface->network_interface.vt = &s_linux_mobile_vtable; else if (type == NETWORK_INTERFACE_TYPE_UNKNOWN) linux_network_interface->network_interface.vt = &s_linux_unknown_vtable; return (network_interface_t*)linux_network_interface; }
0
repos/awtk/src/hal
repos/awtk/src/hal/windows/network_interface_windows.c
/** * File: network_interface_windows.c * Author: AWTK Develop Team * Brief: network_interface for windows * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-02-3 pengguowen<[email protected]> created * 2021-03-15 zhangzhongji<[email protected]> add imp * */ #include "tkc/darray.h" #include "tkc/mem.h" #include "tkc/utils.h" #include "tkc/object_default.h" #include "hal/network_interface.h" #ifdef MINGW network_interface_t* network_interface_create(const char* interface_name, network_interface_type_t type) { return NULL; } #else #include <stdio.h> #include <WinSock2.h> #include <Iphlpapi.h> #include <SetupAPI.h> #include <cfgmgr32.h> #include <WbemIdl.h> #pragma comment(lib, "wbemuuid.lib") #pragma comment(lib, "comsuppw.lib") #pragma comment(lib, "SetupAPI.lib") #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "User32.lib") #pragma comment(lib, "Ole32.lib") #pragma comment(lib, "OleAut32.lib") #pragma comment(lib, "Iphlpapi.lib") typedef struct _network_interface_windows_t { network_interface_t network_interface; char* ipaddr; char* macaddr; /*private*/ wchar_t* adapter_name; wchar_t* friendly_name; wchar_t* description_name; bool_t is_init_; IWbemLocator* p_instance_; IWbemServices* p_service_; IEnumWbemClassObject* p_enum_; IWbemClassObject* p_obj_; IWbemClassObject* p_config; VARIANT path_; int last_error_code_; darray_t* arg; ULONG64 speed; //单位M int status; } network_interface_windows_t; typedef enum _info_type_t { LOCAL_IF_IP, LOCAL_IF_MAC, LOCAL_IF_STATUS, LOCAL_IF_SPEED, LOCAL_IF_DESC } info_type_t; static char* wchar_to_char(const wchar_t* wc) { int len = WideCharToMultiByte(CP_ACP, 0, wc, wcslen(wc), NULL, 0, NULL, NULL); char* c = (char*)malloc(len + 1); if (c == NULL) { log_debug("wchar_to_char malloc failed."); return NULL; } WideCharToMultiByte(CP_ACP, 0, wc, wcslen(wc), c, len, NULL, NULL); c[len] = '\0'; return c; } static wchar_t* char_to_wchar(const char* c) { int len = MultiByteToWideChar(CP_ACP, 0, c, strlen(c), NULL, 0); wchar_t* w = (wchar_t*)malloc((len + 1) * sizeof(wchar_t)); if (w == NULL) { log_debug("char_to_wchar malloc failed."); return NULL; } MultiByteToWideChar(CP_ACP, 0, c, strlen(c), w, len); w[len] = '\0'; return w; } static ret_t get_ip_adapter_address_by_friendly_name( network_interface_windows_t* windows_network_interface, info_type_t info_type) { PIP_ADAPTER_ADDRESSES current_addresses = NULL; ULONG flags = GAA_FLAG_INCLUDE_PREFIX; ULONG family = AF_INET; ULONG out_buff_len = 0; ret_t ret = RET_FAIL; out_buff_len = sizeof(IP_ADAPTER_ADDRESSES); PIP_ADAPTER_ADDRESSES adapter_addresses = NULL; adapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(out_buff_len); bool_t if_found = FALSE; wchar_t* friendly_name = NULL; wchar_t* adapter_name = NULL; return_value_if_fail(windows_network_interface != NULL, RET_FAIL); friendly_name = char_to_wchar(windows_network_interface->network_interface.interface_name); if (friendly_name == NULL) { return RET_FAIL; } // Make an initial call to GetAdaptersAddresses to get the // size needed into the out_buff_len variable if (GetAdaptersAddresses(family, flags, NULL, adapter_addresses, &out_buff_len) == ERROR_BUFFER_OVERFLOW) { free(adapter_addresses); adapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(out_buff_len); } if (adapter_addresses == NULL) { log_debug("Memory allocation failed for IP_ADAPTER_ADDRESSES struct."); return RET_FAIL; } if (ERROR_SUCCESS == GetAdaptersAddresses(family, flags, NULL, adapter_addresses, &out_buff_len)) { current_addresses = adapter_addresses; while (current_addresses) { if (wcscmp(current_addresses->FriendlyName, friendly_name) == 0) { if_found = TRUE; break; } current_addresses = current_addresses->Next; } if (if_found) { switch (info_type) { case LOCAL_IF_STATUS: windows_network_interface->status = current_addresses->OperStatus == IfOperStatusUp ? 1 : 0; break; case LOCAL_IF_SPEED: windows_network_interface->speed = current_addresses->TransmitLinkSpeed / 1000000; //单位M break; case LOCAL_IF_DESC: if (windows_network_interface->description_name != NULL) { TKMEM_FREE(windows_network_interface->description_name) } windows_network_interface->description_name = tk_wstrdup(current_addresses->Description); adapter_name = char_to_wchar(current_addresses->AdapterName); if (adapter_name != NULL) { if (windows_network_interface->adapter_name != NULL) { TKMEM_FREE(windows_network_interface->adapter_name) } windows_network_interface->adapter_name = tk_wstrdup(adapter_name); free(adapter_name); } default: break; } ret = RET_OK; } else { ret = RET_FAIL; } } else { ret = RET_FAIL; } free(adapter_addresses); free(friendly_name); return ret; } static ret_t get_adapter_info_by_dev_desc(network_interface_windows_t* windows_network_interface, info_type_t info_type) { uint8_t m[6]; char macstr[18]; ret_t ret = RET_FAIL; PIP_ADAPTER_INFO current_ip_adapter_info = NULL; PIP_ADAPTER_INFO ip_adapter_info = NULL; unsigned long stSize = sizeof(IP_ADAPTER_INFO); int nRel = 0; bool_t if_found = FALSE; return_value_if_fail( windows_network_interface != NULL && windows_network_interface->description_name != NULL, RET_FAIL); ip_adapter_info = (PIP_ADAPTER_INFO)malloc(sizeof(IP_ADAPTER_INFO)); if (ip_adapter_info == NULL) { return RET_FAIL; } nRel = GetAdaptersInfo(ip_adapter_info, &stSize); if (ERROR_BUFFER_OVERFLOW == nRel) { free(ip_adapter_info); ip_adapter_info = (PIP_ADAPTER_INFO)malloc(stSize); nRel = GetAdaptersInfo(ip_adapter_info, &stSize); } if (ERROR_SUCCESS == nRel) { char* dev_name = wchar_to_char(windows_network_interface->description_name); current_ip_adapter_info = ip_adapter_info; while (current_ip_adapter_info) { if (strcmp(current_ip_adapter_info->Description, dev_name) == 0) { if_found = TRUE; break; } current_ip_adapter_info = current_ip_adapter_info->Next; } if (if_found) { switch (info_type) { case LOCAL_IF_IP: if (windows_network_interface->ipaddr != NULL) { TKMEM_FREE(windows_network_interface->ipaddr); } windows_network_interface->ipaddr = tk_strdup(current_ip_adapter_info->IpAddressList.IpAddress.String); break; case LOCAL_IF_MAC: if (windows_network_interface->macaddr != NULL) { TKMEM_FREE(windows_network_interface->macaddr); } memcpy(m, current_ip_adapter_info->Address, 6); snprintf(macstr, sizeof(macstr), "%02x:%02x:%02x:%02x:%02x:%02x", m[0], m[1], m[2], m[3], m[4], m[5]); windows_network_interface->macaddr = tk_strdup(macstr); break; default: break; } ret = RET_OK; } else { ret = RET_FAIL; } free(dev_name); } else { ret = RET_FAIL; } //释放内存空间 if (ip_adapter_info) { free(ip_adapter_info); } return ret; } static bool_t NetCardStateChange(const wchar_t* dev_des, bool_t Enabled) { //--------------------------------------------------------------------------- //功能:NetCardStateChange 网卡的启用与禁用 //参数:NetCardPoint 是 PNetCardStruct 的指针. //参数:Enabled true = 启用 FALSE = 禁用 //--------------------------------------------------------------------------- DWORD device_id = 0; HDEVINFO dev_info = 0; char* dev_name = NULL; char dev_des_name[255]; bool_t is_found = FALSE; if (INVALID_HANDLE_VALUE == (dev_info = SetupDiGetClassDevs(NULL, NULL, 0, DIGCF_PRESENT | DIGCF_ALLCLASSES))) { log_debug("SetupDiGetClassDevs == INVALID_HANDLE_VALUE."); return FALSE; } SP_DEVINFO_DATA device_info_data = {sizeof(SP_DEVINFO_DATA)}; DWORD status, problem; if (!SetupDiEnumDeviceInfo(dev_info, device_id, &device_info_data)) { log_debug("SetupDiEnumDeviceInfo failed."); return FALSE; } dev_name = wchar_to_char(dev_des); while (SetupDiEnumDeviceInfo(dev_info, device_id++, &device_info_data)) { SetupDiGetDeviceRegistryProperty(dev_info, &device_info_data, SPDRP_DEVICEDESC, NULL, dev_des_name, 254, NULL); if (strcmp(dev_des_name, dev_name) == 0) { is_found = TRUE; break; } } free(dev_name); if (is_found == FALSE) { log_debug("dev not found."); return FALSE; } //读取网卡状态 if (CM_Get_DevNode_Status(&status, &problem, device_info_data.DevInst, 0) != CR_SUCCESS) { log_debug("CM_Get_DevNode_Status failed."); return FALSE; } SP_PROPCHANGE_PARAMS prop_change_params = {sizeof(SP_CLASSINSTALL_HEADER)}; prop_change_params.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE; prop_change_params.Scope = DICS_FLAG_GLOBAL; if (Enabled) { //如果网卡是启用中的,则不处理 if (!((status & DN_HAS_PROBLEM) && (CM_PROB_DISABLED == problem))) { log_debug("enable dev ok."); return TRUE; } prop_change_params.StateChange = DICS_ENABLE; } else { if ((status & DN_HAS_PROBLEM) && (CM_PROB_DISABLED == problem)) { log_debug("disable dev ok."); return TRUE; } if (!((status & DN_DISABLEABLE) && (CM_PROB_HARDWARE_DISABLED != problem))) { log_debug("(!((status & DN_DISABLEABLE) && (CM_PROB_HARDWARE_DISABLED != problem)))."); return FALSE; } prop_change_params.StateChange = DICS_DISABLE; } //功能:设置网卡有效或无效 if (!SetupDiSetClassInstallParams(dev_info, &device_info_data, (SP_CLASSINSTALL_HEADER*)&prop_change_params, sizeof(prop_change_params))) { log_debug("SetupDiSetClassInstallParams failed."); return FALSE; } if (!SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, dev_info, &device_info_data)) { log_debug("SetupDiCallClassInstaller failed."); return FALSE; } return TRUE; } static ret_t network_interface_windows_enable(network_interface_t* network_interface) { bool_t ret = FALSE; network_interface_windows_t* windows_network_interface = (network_interface_windows_t*)network_interface; return_value_if_fail( windows_network_interface != NULL && windows_network_interface->description_name != NULL, RET_FAIL); if (wcslen(windows_network_interface->description_name) != 0) { ret = NetCardStateChange(windows_network_interface->description_name, TRUE); } return ret ? RET_OK : RET_FAIL; } static ret_t network_interface_windows_disable(network_interface_t* network_interface) { bool_t ret = FALSE; network_interface_windows_t* windows_network_interface = (network_interface_windows_t*)network_interface; return_value_if_fail( windows_network_interface != NULL && windows_network_interface->description_name != NULL, RET_FAIL); if (wcslen(windows_network_interface->description_name) != 0) { ret = NetCardStateChange(windows_network_interface->description_name, FALSE); } return ret ? RET_OK : RET_FAIL; } static char* network_interface_windows_get_ipaddr(network_interface_t* network_interface) { ret_t ret = RET_FAIL; network_interface_windows_t* windows_network_interface = (network_interface_windows_t*)network_interface; return_value_if_fail(windows_network_interface != NULL, NULL); ret = get_adapter_info_by_dev_desc(windows_network_interface, LOCAL_IF_IP); if (ret == RET_OK) { return windows_network_interface->ipaddr; } else { return NULL; } } static char* network_interface_windows_get_macaddr(network_interface_t* network_interface) { ret_t ret = RET_FAIL; network_interface_windows_t* windows_network_interface = (network_interface_windows_t*)network_interface; return_value_if_fail(windows_network_interface != NULL, NULL); ret = get_adapter_info_by_dev_desc(windows_network_interface, LOCAL_IF_MAC); if (ret == RET_OK) { return windows_network_interface->macaddr; } else { return NULL; } } static int network_interface_windows_eth_get_status(network_interface_t* network_interface) { network_interface_windows_t* windows_network_interface = (network_interface_windows_t*)network_interface; return_value_if_fail(windows_network_interface != NULL, 0); if (RET_OK == get_ip_adapter_address_by_friendly_name(windows_network_interface, LOCAL_IF_STATUS)) { return windows_network_interface->status; } else { return 0; } } static int network_interface_windows_eth_get_quality(network_interface_t* network_interface) { network_interface_windows_t* windows_network_interface = (network_interface_windows_t*)network_interface; return_value_if_fail(windows_network_interface != NULL, -1); if (RET_OK == get_ip_adapter_address_by_friendly_name(windows_network_interface, LOCAL_IF_SPEED)) { return windows_network_interface->speed; } else { return -1; } } static bool_t init_com_for_service(network_interface_windows_t* network_interface) { wchar_t query_tmp[256] = {0}; return_value_if_fail(network_interface != NULL, FALSE); if (network_interface->is_init_) { return TRUE; } // Step 1: Initialize COM. HRESULT hres = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); if (FAILED(hres)) { log_debug("CoInitializeEx failed: %d", hres); return FALSE; } /* // Step 2: Set general COM security levels hres = CoInitializeSecurity( NULL, -1, // COM negotiates service NULL, // Authentication services NULL, // Reserved RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation NULL, // Authentication info EOAC_NONE, // Additional capabilities NULL // Reserved ); if (FAILED(hres)) { log_debug("CoInitializeSecurity failed: %d", hres); return FALSE; } */ // Step 3: Obtain the initial locator to WMI hres = CoCreateInstance(&CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, &IID_IWbemLocator, (LPVOID*)&network_interface->p_instance_); if (FAILED(hres)) { log_debug("CoCreateInstance failed: %d", hres); return FALSE; } // Step 4: Connect to the local root\cimv2 namespace and obtain pointer pSvc to make IWbemServices calls. hres = network_interface->p_instance_->lpVtbl->ConnectServer( network_interface->p_instance_, L"ROOT\\CIMV2", NULL, NULL, NULL, 0, NULL, NULL, &network_interface->p_service_); if (FAILED(hres)) { log_debug("ConnectServer failed: %d", hres); return FALSE; } // Step 5: Set security levels for the proxy hres = CoSetProxyBlanket((IUnknown*)network_interface->p_service_, // Indicates the proxy to set RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx NULL, // Server principal name RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx NULL, // client identity EOAC_NONE // proxy capabilities ); if (FAILED(hres)) { log_debug("CoSetProxyBlanket failed: %d", hres); return FALSE; } // 通过适配器名称来找到指定的适配器对象. swprintf_s(query_tmp, 256, L"SELECT * FROM Win32_NetworkAdapterConfiguration WHERE SettingID = \"%ls\"", network_interface->adapter_name); hres = network_interface->p_service_->lpVtbl->ExecQuery( network_interface->p_service_, //SysAllocString(L"WQL"), L"WQL", query_tmp, WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY, NULL, &network_interface->p_enum_); if (FAILED(hres)) { log_debug("ExecQuery failed: %d", hres); return FALSE; } // Get the adapter object. ULONG num = 0; hres = network_interface->p_enum_->lpVtbl->Next(network_interface->p_enum_, WBEM_INFINITE, 1, &network_interface->p_obj_, &num); if (FAILED(hres)) { log_debug("Next failed: %d", hres); return FALSE; } if (num < 1) { log_debug("Next failed num < 1"); return FALSE; } VariantInit(&network_interface->path_); hres = network_interface->p_obj_->lpVtbl->Get(network_interface->p_obj_, L"__PATH", 0, &network_interface->path_, NULL, NULL); if (FAILED(hres)) { log_debug("Get failed: %d", hres); return FALSE; } hres = network_interface->p_service_->lpVtbl->GetObject(network_interface->p_service_, L"Win32_NetworkAdapterConfiguration", 0, NULL, &network_interface->p_config, NULL); if (FAILED(hres)) { log_debug("GetObject failed: %d", hres); return FALSE; } network_interface->is_init_ = TRUE; return TRUE; } static bool_t local_exec_method(network_interface_windows_t* network_interface, const wchar_t* method, IWbemClassObject* params_instance) { return_value_if_fail(network_interface != NULL && method != NULL, FALSE); bool_t rt = FALSE; int last_error_code_ = 0; IWbemClassObject* results = NULL; auto res = network_interface->p_service_->lpVtbl->ExecMethod( network_interface->p_service_, network_interface->path_.bstrVal, method, 0, NULL, params_instance, &results, NULL); if (SUCCEEDED(res)) { VARIANT vtRet; VariantInit(&vtRet); if (!FAILED(results->lpVtbl->Get(results, L"ReturnValue", 0, &vtRet, NULL, 0))) { if (vtRet.uintVal == 0 || vtRet.uintVal == 1) { rt = TRUE; } else { last_error_code_ = vtRet.uintVal; log_debug("failed, result:: %d", last_error_code_); } } else { log_debug("ExecMethod Get ReturnValue failed: %d", res); } VariantClear(&vtRet); results->lpVtbl->Release(results); } else { log_debug("ExecMethod failed: %d", res); } if (params_instance) { params_instance->lpVtbl->Release(params_instance); } return rt; } static ret_t network_interface_windows_set_dhcp(network_interface_t* network_interface) { network_interface_windows_t* windows_network_interface = (network_interface_windows_t*)(network_interface); if (!init_com_for_service(windows_network_interface)) { return RET_FAIL; } return local_exec_method(windows_network_interface, L"EnableDHCP", NULL) ? RET_OK : RET_FAIL; } static SAFEARRAY* create_SAFEARRAY(darray_t* arg) { BSTR ip = NULL; return_value_if_fail(arg != NULL && arg->size > 0, NULL); SAFEARRAY* psa = SafeArrayCreateVector(VT_BSTR, 0, arg->size); long idx[] = {0}; for (int i = 0; i < arg->size; ++i) { wchar_t* tmp = char_to_wchar(darray_get(arg, i)); if (tmp != NULL) { ip = SysAllocString(tmp); if (FAILED(SafeArrayPutElement(psa, idx, ip))) { SafeArrayDestroy(psa); free(tmp); log_debug("SafeArrayPutElement failed."); return NULL; } SysFreeString(ip); free(tmp); } else { SafeArrayDestroy(psa); log_debug("tmp == NULL."); return NULL; } } return psa; } static void clear(network_interface_windows_t* network_interface) { if (network_interface->p_config) { network_interface->p_config->lpVtbl->Release(network_interface->p_config); network_interface->p_config = NULL; } if (network_interface->p_obj_) { network_interface->p_obj_->lpVtbl->Release(network_interface->p_obj_); network_interface->p_obj_ = NULL; } if (network_interface->p_enum_) { network_interface->p_enum_->lpVtbl->Release(network_interface->p_enum_); network_interface->p_enum_ = NULL; } if (network_interface->p_service_) { network_interface->p_service_->lpVtbl->Release(network_interface->p_service_); network_interface->p_service_ = NULL; } if (network_interface->p_instance_) { network_interface->p_instance_->lpVtbl->Release(network_interface->p_instance_); network_interface->p_instance_ = NULL; } if (network_interface->is_init_) { CoUninitialize(); } network_interface->is_init_ = FALSE; } static ret_t network_interface_windows_set_ipaddr(network_interface_t* network_interface, const char* ipaddr, const char* netmask) { bool_t rt = FALSE; network_interface_windows_t* windows_network_interface = (network_interface_windows_t*)(network_interface); if (!init_com_for_service(windows_network_interface)) return rt ? RET_OK : RET_FAIL; IWbemClassObject* params = NULL; IWbemClassObject* paramsInst = NULL; windows_network_interface->p_config->lpVtbl->GetMethod(windows_network_interface->p_config, L"EnableStatic", 0, &params, NULL); params->lpVtbl->SpawnInstance(params, 0, &paramsInst); darray_clear(windows_network_interface->arg); darray_push(windows_network_interface->arg, ipaddr); SAFEARRAY* p1 = create_SAFEARRAY(windows_network_interface->arg); VARIANT paramVt; paramVt.vt = VT_ARRAY | VT_BSTR; paramVt.parray = p1; paramsInst->lpVtbl->Put(paramsInst, L"IPAddress", 0, &paramVt, 0); SafeArrayDestroy(p1); darray_clear(windows_network_interface->arg); darray_push(windows_network_interface->arg, netmask); p1 = create_SAFEARRAY(windows_network_interface->arg); paramVt.parray = p1; paramsInst->lpVtbl->Put(paramsInst, L"SubnetMask", 0, &paramVt, 0); SafeArrayDestroy(p1); rt = local_exec_method(windows_network_interface, L"EnableStatic", paramsInst); if (params) { params->lpVtbl->Release(params); } return rt ? RET_OK : RET_FAIL; } static ret_t network_interface_windows_set_dns(network_interface_t* network_interface, const char* dns) { bool_t rt = FALSE; network_interface_windows_t* windows_network_interface = (network_interface_windows_t*)(network_interface); if (!init_com_for_service(windows_network_interface)) { return rt; } IWbemClassObject* params = NULL; IWbemClassObject* paramsInst = NULL; windows_network_interface->p_config->lpVtbl->GetMethod( windows_network_interface->p_config, L"SetDNSServerSearchOrder", 0, &params, NULL); params->lpVtbl->SpawnInstance(params, 0, &paramsInst); darray_clear(windows_network_interface->arg); darray_push(windows_network_interface->arg, dns); SAFEARRAY* p1 = create_SAFEARRAY(windows_network_interface->arg); VARIANT paramVt; paramVt.vt = VT_ARRAY | VT_BSTR; paramVt.parray = p1; paramsInst->lpVtbl->Put(paramsInst, L"DNSServerSearchOrder", 0, &paramVt, 0); SafeArrayDestroy(p1); rt = local_exec_method(windows_network_interface, L"SetDNSServerSearchOrder", paramsInst); if (params) { params->lpVtbl->Release(params); } return rt ? RET_OK : RET_FAIL; } static ret_t network_interface_windows_set_gateway(network_interface_t* network_interface, const char* gateway, const char* dev) { bool_t rt = FALSE; network_interface_windows_t* windows_network_interface = (network_interface_windows_t*)(network_interface); if (!init_com_for_service(windows_network_interface)) return rt; IWbemClassObject* params = NULL; IWbemClassObject* paramsInst = NULL; windows_network_interface->p_config->lpVtbl->GetMethod(windows_network_interface->p_config, L"SetGateways", 0, &params, NULL); params->lpVtbl->SpawnInstance(params, 0, &paramsInst); darray_clear(windows_network_interface->arg); darray_push(windows_network_interface->arg, gateway); SAFEARRAY* p1 = create_SAFEARRAY(windows_network_interface->arg); VARIANT paramVt; paramVt.vt = VT_ARRAY | VT_BSTR; paramVt.parray = p1; paramsInst->lpVtbl->Put(paramsInst, L"DefaultIPGateway", 0, &paramVt, 0); paramVt.vt = VT_UINT; paramVt.uintVal = 1; paramsInst->lpVtbl->Put(paramsInst, L"GatewayCostMetric", 0, &paramVt, 0); rt = local_exec_method(windows_network_interface, L"SetGateways", paramsInst); if (params) { params->lpVtbl->Release(params); } return rt ? RET_OK : RET_FAIL; } static ret_t network_interface_windows_set_wifi_sta(network_interface_t* network_interface, const char* essid, const char* passwd, network_interface_wifi_auth_t auth) { return RET_OK; } static ret_t network_interface_windows_set_wifi_ap(network_interface_t* network_interface, const char* essid, const char* passwd, network_interface_wifi_auth_t auth, uint8_t channel, network_interface_wifi_freq_t freq, uint8_t hidden) { return RET_OK; } static int network_interface_windows_wifi_get_status(network_interface_t* network_interface) { return 0; } static int network_interface_windows_wifi_get_quality(network_interface_t* network_interface) { return 0; } static int network_interface_windows_mobile_get_status(network_interface_t* network_interface) { return 0; } static int network_interface_windows_mobile_get_quality(network_interface_t* network_interface) { return 0; } static void network_interface_windows_destroy(network_interface_t* network_interface) { network_interface_windows_t* windows_network_interface = (network_interface_windows_t*)network_interface; TKMEM_FREE(network_interface->interface_name); TKMEM_FREE(network_interface); if (windows_network_interface->ipaddr != NULL) TKMEM_FREE(windows_network_interface->ipaddr); if (windows_network_interface->macaddr != NULL) TKMEM_FREE(windows_network_interface->macaddr); if (windows_network_interface->description_name != NULL) TKMEM_FREE(windows_network_interface->description_name); if (windows_network_interface->adapter_name != NULL) TKMEM_FREE(windows_network_interface->adapter_name); if (windows_network_interface->arg != NULL) darray_destroy(windows_network_interface->arg); clear(windows_network_interface); } static const network_interface_vtable_t s_windows_eth_vtable = { .type = "linux_eth", .desc = "vtable for linux eth device", .enable = network_interface_windows_enable, .disable = network_interface_windows_disable, .destroy = network_interface_windows_destroy, .get_ipaddr = network_interface_windows_get_ipaddr, .get_macaddr = network_interface_windows_get_macaddr, .get_quality = network_interface_windows_eth_get_quality, .get_status = network_interface_windows_eth_get_status, .set_ipaddr = network_interface_windows_set_ipaddr, .set_dhcp = network_interface_windows_set_dhcp, .set_dns = network_interface_windows_set_dns, .set_gateway = network_interface_windows_set_gateway, }; static const network_interface_vtable_t s_windows_wifi_vtable = { .type = "linux_wifi", .desc = "vtable for linux wifi device", .enable = network_interface_windows_enable, .disable = network_interface_windows_disable, .destroy = network_interface_windows_destroy, .get_ipaddr = network_interface_windows_get_ipaddr, .get_macaddr = network_interface_windows_get_macaddr, .get_quality = network_interface_windows_wifi_get_quality, .get_status = network_interface_windows_wifi_get_status, .set_ipaddr = network_interface_windows_set_ipaddr, .set_dns = network_interface_windows_set_dns, .set_dhcp = network_interface_windows_set_dhcp, .set_gateway = network_interface_windows_set_gateway, .set_wif_sta = network_interface_windows_set_wifi_sta, .set_wifi_ap = network_interface_windows_set_wifi_ap, }; static const network_interface_vtable_t s_windows_mobile_vtable = { .type = "linux_mobile", .desc = "vtable for linux mobile device", .enable = network_interface_windows_enable, .disable = network_interface_windows_disable, .destroy = network_interface_windows_destroy, .get_quality = network_interface_windows_mobile_get_quality, .get_status = network_interface_windows_mobile_get_status, }; static const network_interface_vtable_t s_windows_unknown_vtable = { .type = "linux_unknown_network", .desc = "vtable for linux common network", .get_ipaddr = network_interface_windows_get_ipaddr, .get_macaddr = network_interface_windows_get_macaddr, }; network_interface_t* network_interface_create(const char* interface_name, network_interface_type_t type) { ret_t ret = RET_OK; PIP_ADAPTER_ADDRESSES address = NULL; network_interface_windows_t* windows_network_interface = TKMEM_ZALLOC(network_interface_windows_t); return_value_if_fail(windows_network_interface != NULL, NULL); windows_network_interface->network_interface.interface_name = tk_strdup(interface_name); windows_network_interface->network_interface.type = type; windows_network_interface->ipaddr = NULL; windows_network_interface->macaddr = NULL; windows_network_interface->friendly_name = NULL; windows_network_interface->description_name = NULL; windows_network_interface->p_instance_ = NULL; windows_network_interface->p_service_ = NULL; windows_network_interface->p_enum_ = NULL; windows_network_interface->p_obj_ = NULL; windows_network_interface->p_config = NULL; windows_network_interface->is_init_ = FALSE; windows_network_interface->adapter_name = NULL; windows_network_interface->arg = darray_create(2, NULL, NULL); if (type == NETWORK_INTERFACE_TYPE_ETH) windows_network_interface->network_interface.vt = &s_windows_eth_vtable; else if (type == NETWORK_INTERFACE_TYPE_WIFI) windows_network_interface->network_interface.vt = &s_windows_wifi_vtable; else if (type == NETWORK_INTERFACE_TYPE_MOBILE) windows_network_interface->network_interface.vt = &s_windows_mobile_vtable; else if (type == NETWORK_INTERFACE_TYPE_UNKNOWN) windows_network_interface->network_interface.vt = &s_windows_unknown_vtable; // 获取接口描述名 ret = get_ip_adapter_address_by_friendly_name(windows_network_interface, LOCAL_IF_DESC); if (ret != RET_OK) { TKMEM_FREE(windows_network_interface); return NULL; } return (network_interface_t*)windows_network_interface; } #endif /*WIN*/
0
repos/awtk/src/hal
repos/awtk/src/hal/macos/network_interface_macos.c
/** * File: network_interface_macos.c * Author: AWTK Develop Team * Brief: network_interface for macos * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-02-3 pengguowen<[email protected]> created * */ #include "hal/network_interface.h" network_interface_t* network_interface_create(const char* interface, network_interface_type_t type) { /*TODO*/ return NULL; }
0
repos/awtk/src/hal/tools
repos/awtk/src/hal/tools/network_shell/network_shell.c
/** * File: network_shell.c * Author: AWTK Develop Team * Brief: awtk hal shell * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-04-19 Zhang Zhongji <[email protected]> created * */ #include "tkc/fs.h" #include "tkc/mem.h" #include "tkc/thread.h" #include "tkc/utils.h" #include "tkc/object_default.h" #include "tkc/tokenizer.h" #include "network_shell.h" #ifndef WIN32 #include <readline/history.h> #include <readline/readline.h> static char* command_generator(const char* text, int state); static char** command_completion(const char* text, int start, int end) { char** matches = NULL; if (start == 0) { matches = rl_completion_matches(text, command_generator); } return (matches); } static ret_t aw_read_line_init(void) { rl_readline_name = "awtk"; rl_attempted_completion_function = command_completion; return RET_OK; } static char* aw_read_line(const char* tips) { return readline(tips); } static ret_t aw_read_line_free(char* line) { free(line); return RET_OK; } static ret_t aw_read_line_add_history(char* line) { add_history(line); return RET_OK; } #else static char s_line[1024]; static ret_t aw_read_line_init(void) { return RET_OK; } static char* aw_read_line(const char* tips) { printf("%s", tips); fflush(stdout); fgets(s_line, sizeof(s_line) - 1, stdin); return s_line; } static ret_t aw_read_line_free(char* line) { return RET_OK; } static ret_t aw_read_line_add_history(char* line) { return RET_OK; } #endif /**/ #include "tkc/data_reader_mem.h" #include "conf_io/conf_ubjson.h" #define KNRM "\x1B[0m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KMAG "\x1B[35m" typedef ret_t (*cmd_line_func_t)(network_interface_t* network_interface, tokenizer_t* tokenizer); typedef struct _cmd_entry_t { const char* name; const char* alias; const char* desc; const char* help; cmd_line_func_t func; } cmd_entry_t; //网卡接口使能函数。 static ret_t func_network_interface_enable(network_interface_t* interface, tokenizer_t* tokenizer) { ret_t ret = RET_FAIL; ret = network_interface_enable(interface); log_debug("%s:%s\n", __FUNCTION__, ret == RET_OK ? "OK" : "FAIL"); return RET_OK; } //网卡接口禁能函数。 static ret_t func_network_interface_disable(network_interface_t* interface, tokenizer_t* tokenizer) { ret_t ret = RET_FAIL; ret = network_interface_disable(interface); log_debug("%s:%s\n", __FUNCTION__, ret == RET_OK ? "OK" : "FAIL"); return RET_OK; } //网卡接口获取IP地址。 static ret_t func_network_interface_get_ipaddr(network_interface_t* interface, tokenizer_t* tokenizer) { char* ip = NULL; ip = network_interface_get_ipaddr(interface); log_debug("%s:%s\n", __FUNCTION__, ip != NULL ? ip : "FAIL"); return RET_OK; } //网卡接口获取MAC地址。 static ret_t func_network_interface_get_macaddr(network_interface_t* interface, tokenizer_t* tokenizer) { char* mac = NULL; mac = network_interface_get_macaddr(interface); log_debug("%s:%s\n", __FUNCTION__, mac != NULL ? mac : "FAIL"); return RET_OK; } //网卡接口获取状态。 static ret_t func_network_interface_get_status(network_interface_t* interface, tokenizer_t* tokenizer) { int status = 0; status = network_interface_get_status(interface); log_debug("%s:%d\n", __FUNCTION__, status); return RET_OK; } //网卡接口获取通信质量。 static ret_t func_network_interface_get_quality(network_interface_t* interface, tokenizer_t* tokenizer) { int quality = 0; quality = network_interface_get_quality(interface); log_debug("%s:%d\n", __FUNCTION__, quality); return RET_OK; } //网卡接口设置IP地址。 static ret_t func_network_interface_set_ipaddr(network_interface_t* interface, tokenizer_t* tokenizer) { ret_t ret = RET_FAIL; char* ipaddr = tk_strdup(tokenizer_next(tokenizer)); char* netmask = tk_strdup(tokenizer_next(tokenizer)); return_value_if_fail(ipaddr != NULL && netmask != NULL, RET_BAD_PARAMS); ret = network_interface_set_ipaddr(interface, ipaddr, netmask); log_debug("%s:%s\n", __FUNCTION__, ret == RET_OK ? "OK" : "FAIL"); TKMEM_FREE(ipaddr); TKMEM_FREE(netmask); return RET_OK; } //网卡接口设置DNS。 static ret_t func_network_interface_set_dns(network_interface_t* interface, tokenizer_t* tokenizer) { ret_t ret = RET_FAIL; char* dns = tk_strdup(tokenizer_next(tokenizer)); return_value_if_fail(dns != NULL, RET_BAD_PARAMS); ret = network_interface_set_dns(interface, dns); log_debug("%s:%s\n", __FUNCTION__, ret == RET_OK ? "OK" : "FAIL"); TKMEM_FREE(dns); return RET_OK; } //网卡接口设置dhcp。 static ret_t func_network_interface_set_dhcp(network_interface_t* interface, tokenizer_t* tokenizer) { ret_t ret = RET_FAIL; ret = network_interface_set_dhcp(interface); log_debug("%s:%s\n", __FUNCTION__, ret == RET_OK ? "OK" : "FAIL"); return RET_OK; } //网卡接口设置网关 static ret_t func_network_interface_set_gateway(network_interface_t* interface, tokenizer_t* tokenizer) { ret_t ret = RET_FAIL; char* gateway = tk_strdup(tokenizer_next(tokenizer)); char* dev = tk_strdup(tokenizer_next(tokenizer)); return_value_if_fail(gateway != NULL && dev != NULL, RET_BAD_PARAMS); ret = network_interface_set_gateway(interface, gateway, dev); log_debug("%s:%s\n", __FUNCTION__, ret == RET_OK ? "OK" : "FAIL"); TKMEM_FREE(gateway); TKMEM_FREE(dev); return RET_OK; } //网卡接口设置WIFI STA模式。 static ret_t func_network_interface_set_wifi_sta(network_interface_t* interface, tokenizer_t* tokenizer) { ret_t ret = RET_FAIL; char* essid = tk_strdup(tokenizer_next(tokenizer)); char* passwd = tk_strdup(tokenizer_next(tokenizer)); char* auth = tk_strdup(tokenizer_next(tokenizer)); return_value_if_fail(essid != NULL && passwd && auth != NULL, RET_BAD_PARAMS); ret = network_interface_set_wifi_sta(interface, essid, passwd, tk_atoi(auth)); log_debug("%s:%s\n", __FUNCTION__, ret == RET_OK ? "OK" : "FAIL"); TKMEM_FREE(essid); TKMEM_FREE(passwd); TKMEM_FREE(auth); return RET_OK; } //网卡接口设置WIFI AP模式。 static ret_t func_network_interface_set_wifi_ap(network_interface_t* interface, tokenizer_t* tokenizer) { ret_t ret = RET_FAIL; char* essid = tk_strdup(tokenizer_next(tokenizer)); char* passwd = tk_strdup(tokenizer_next(tokenizer)); char* auth = tk_strdup(tokenizer_next(tokenizer)); char* channel = tk_strdup(tokenizer_next(tokenizer)); char* freq = tk_strdup(tokenizer_next(tokenizer)); char* hidden = tk_strdup(tokenizer_next(tokenizer)); return_value_if_fail(essid != NULL && passwd != NULL && auth != NULL && channel != NULL && freq != NULL && hidden != NULL, RET_BAD_PARAMS); ret = network_interface_set_wifi_ap(interface, essid, passwd, tk_atoi(auth), tk_atoi(channel), tk_atoi(freq), tk_atoi(hidden)); log_debug("%s:%s\n", __FUNCTION__, ret == RET_OK ? "OK" : "FAIL"); TKMEM_FREE(essid); TKMEM_FREE(passwd); TKMEM_FREE(auth); TKMEM_FREE(channel); TKMEM_FREE(freq); TKMEM_FREE(hidden); return RET_OK; } static ret_t func_quit(network_interface_t* interface, tokenizer_t* tokenizer) { return RET_STOP; } static ret_t func_help(network_interface_t* interface, tokenizer_t* tokenizer); static const cmd_entry_t s_cmds[] = { {"enable", "e", "Enable network interface", "enable", func_network_interface_enable}, {"disable", "d", "Disable network interface", "disable", func_network_interface_disable}, {"get_ip", "ip", "Get IP address of network interface", "get_ip", func_network_interface_get_ipaddr}, {"get_mac", "mac", "Get mac address of network interface", "get_mac", func_network_interface_get_macaddr}, {"get_status", "s", "Get status of network interface", "get_status", func_network_interface_get_status}, {"get_quality", "qua", "Get quality of network interface", "get_quality", func_network_interface_get_quality}, {"set_ip", "sip", "Set IP address of network interface", "set_ip ip_address netmask", func_network_interface_set_ipaddr}, {"set_dns", "sdns", "Set dns of network interface", "set_dns dns", func_network_interface_set_dns}, {"set_dhcp", "dhcp", "Enable dhcp of network interface", "set_dhcp", func_network_interface_set_dhcp}, {"set_gateway", "sgw", "Set gateway of network interface", "set_gateway gateway dev_name", func_network_interface_set_gateway}, {"set_wifi_sta", "ssta", "Set wifi sta of network interface", "set_wifi_sta essid passwd auth", func_network_interface_set_wifi_sta}, {"set_wifi_ap", "sap", "Set wifi ap of network interface", "set_wifi_ap essid passwd auth channel freq hidden", func_network_interface_set_wifi_ap}, {"quit", "q", "Quit loop", "quit", func_quit}, {NULL, NULL, NULL}}; static char* command_generator(const char* text, int state) { static int list_index, len; if (!state) { list_index = 0; len = strlen(text); } while (s_cmds[list_index].name != NULL) { const cmd_entry_t* iter = s_cmds + list_index; list_index++; if (iter->name == NULL) { break; } if (strncmp(iter->name, text, len) == 0) { return strdup(iter->name); } if (strncmp(iter->help, text, len) == 0) { return strdup(iter->help); } } return ((char*)NULL); } static ret_t func_help(network_interface_t* interface, tokenizer_t* tokenizer) { uint32_t i = 0; printf(KMAG "================================================\n" KNRM); while (s_cmds[i].name != NULL) { const cmd_entry_t* iter = s_cmds + i; printf(KYEL "%u: %s(%s)\n" KNRM, i, iter->desc, iter->alias); printf("------------------------------\n"); printf(" # %s\n", iter->help); printf(KGRN "------------------------------------------------\n" KNRM); i++; } printf(KMAG "================================================\n" KNRM); return RET_OK; } static ret_t register_functions(tk_object_t* obj) { uint32_t i = 0; while (s_cmds[i].name != NULL) { const cmd_entry_t* iter = s_cmds + i; tk_object_set_prop_pointer(obj, iter->alias, iter->func); tk_object_set_prop_pointer(obj, iter->name, iter->func); i++; } return RET_OK; } static ret_t network_shell_exec(network_interface_t* network_interface, tk_object_t* obj, const char* line) { tokenizer_t t; ret_t ret = RET_OK; const char* name = NULL; cmd_line_func_t func = NULL; return_value_if_fail(network_interface != NULL && network_interface->vt != NULL && line != NULL, RET_BAD_PARAMS); tokenizer_init(&t, line, strlen(line), " \t\r\n"); name = tokenizer_next(&t); if (name == NULL || *name == '\0') { return RET_OK; } func = (cmd_line_func_t)tk_object_get_prop_pointer(obj, name); if (func == NULL) { func = func_help; } ret = func(network_interface, &t); if (ret == RET_BAD_PARAMS) { func_help(network_interface, &t); } return ret; } ret_t network_shell_run(network_interface_t* network_interface) { tk_object_t* obj = object_default_create(); return_value_if_fail(network_interface != NULL, RET_BAD_PARAMS); aw_read_line_init(); register_functions(obj); while (network_interface != NULL) { char* line = aw_read_line(KMAG "[hal] # " KNRM); if (line == NULL) { break; } if (network_shell_exec(network_interface, obj, line) == RET_STOP) { aw_read_line_free(line); break; } aw_read_line_add_history(line); aw_read_line_free(line); } return RET_OK; }
0
repos/awtk/src/hal/tools
repos/awtk/src/hal/tools/network_shell/main.c
#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /*WIN32_LEAN_AND_MEAN*/ #include "tkc/fs.h" #include "tkc/mem.h" #include "tkc/url.h" #include "tkc/utils.h" #include "tkc/platform.h" #include "tkc/func_call_parser.h" #include "network_shell.h" static ret_t show_help(int argc, char* argv[]) { log_debug("Usage: %s protocl args\n", argv[0]); log_debug("Format: %s interface_name interface_type\n", argv[0]); log_debug("ex: %s eth0 1\n", argv[0]); return RET_OK; } static network_interface_t* network_interface_create_with_args(int argc, char* argv[]) { int interface_type = 0; network_interface_t* network_interface = NULL; if (argc < 3) { show_help(argc, argv); exit(0); return NULL; } interface_type = tk_atoi(argv[2]); network_interface = network_interface_create(argv[1], (network_interface_type_t)(interface_type)); return_value_if_fail(network_interface != NULL && network_interface->vt != NULL, NULL); return network_interface; } #include "tkc/data_reader_factory.h" #include "tkc/data_writer_factory.h" #include "tkc/data_writer_file.h" #include "tkc/data_writer_wbuffer.h" #include "tkc/data_reader_file.h" #include "tkc/data_reader_mem.h" static ret_t network_shell_init(void) { TK_ENABLE_CONSOLE(); platform_prepare(); data_writer_factory_set(data_writer_factory_create()); data_reader_factory_set(data_reader_factory_create()); data_writer_factory_register(data_writer_factory(), "file", data_writer_file_create); data_reader_factory_register(data_reader_factory(), "file", data_reader_file_create); data_reader_factory_register(data_reader_factory(), "mem", data_reader_mem_create); data_writer_factory_register(data_writer_factory(), "wbuffer", data_writer_wbuffer_create); return RET_OK; } int main(int argc, char* argv[]) { network_interface_t* network_interface = NULL; network_shell_init(); network_interface = network_interface_create_with_args(argc, argv); return_value_if_fail(network_interface != NULL, 0); network_shell_run(network_interface); network_interface_destroy(network_interface); return 0; }
0
repos/awtk/src/hal/tools
repos/awtk/src/hal/tools/network_shell/network_shell.h
/** * File: hal_shell.h * Author: AWTK Develop Team * Brief: shell of hal * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2021-04-19 Zhang Zhongji <[email protected]> created * */ #ifndef NETWORK_SHELL_H #define NETWORK_SHELL_H #include "tkc/types_def.h" #include "hal/network_interface.h" BEGIN_C_DECLS /** * @class hal_shell_t * @annotation ["fake"] * a shell to access network interface */ /** * @method network_shell_run * @export none * 运行shell。 * @param {network_interface_t*} network_interface 网口对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t network_shell_run(network_interface_t* network_interface); END_C_DECLS #endif /*NETWORK_SHELL_H*/
0
repos/awtk/src
repos/awtk/src/misc/test_cpp.cpp
// Used to test if target platform support cpp #include "tkc/mem.h" #include "misc/new.hpp" class Test { public: int count; Test() { this->count = 0; } ~Test() { this->count = 0; } void inc() { this->count++; } void dec() { this->count--; } }; extern "C" void runCppTest() { Test* t = new Test(); t->inc(); t->dec(); delete t; }
0
repos/awtk/src
repos/awtk/src/misc/new.cpp
#include "misc/new.hpp" /* * 由于mem.c中导出了malloc等函数,没有必要重载new/delete等操作符,所以去掉misc/new.cpp|.hpp中的代码,但为了兼容保留文件。 */ #if 0 #define MAX_SIZE 2 * 1024 * 1024 #ifndef WITH_SDL void* operator new(std::size_t size) __TK_THROW_BAD_ALLOC { if (size >= MAX_SIZE) { log_debug("size is too large\n"); } return TKMEM_ALLOC(size); } void* operator new[](std::size_t size) __TK_THROW_BAD_ALLOC { if (size >= MAX_SIZE) { log_debug("size is too large\n"); } return TKMEM_ALLOC(size); } void operator delete(void* obj) throw() { TKMEM_FREE(obj); } void operator delete[](void* obj) throw() { TKMEM_FREE(obj); } #endif /*WITH_SDL*/ #endif /*HAS_STD_MALLOC*/
0
repos/awtk/src
repos/awtk/src/misc/new.hpp
#ifndef TK_NEW_H #define TK_NEW_H #include <new> #include <cstddef> #include "tkc/mem.h" /* * 由于mem.c中导出了malloc等函数,没有必要重载new/delete等操作符,所以去掉misc/new.cpp|.hpp中的代码,但为了兼容保留文件。 */ #if 0 #if __cplusplus < 201103L || defined(__ARMCC_VERSION) #define __TK_THROW_BAD_ALLOC throw(std::bad_alloc) #else #define __TK_THROW_BAD_ALLOC #endif void* operator new(std::size_t size) __TK_THROW_BAD_ALLOC; void* operator new[](std::size_t size) __TK_THROW_BAD_ALLOC; void operator delete(void* obj) throw(); void operator delete[](void* obj) throw(); #endif/*HAS_STD_MALLOC*/ #endif/*TK_NEW_H*/
0
repos/awtk/src
repos/awtk/src/csv/csv_file_object.h
/** * File: csv_file_object.h * Author: AWTK Develop Team * Brief: csv file object * * Copyright (c) 2020 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2020-07-19 Li XianJing <[email protected]> created * */ #ifndef TK_CSV_FILE_OBJECT_H #define TK_CSV_FILE_OBJECT_H #include "tkc/object.h" #include "csv_file.h" BEGIN_C_DECLS /** * 返回值: * RET_OK: 保留 * RET_STOP: 停止解析 * RET_FAIL: 忽略此行 */ typedef ret_t (*csv_file_object_filter_t)(void* ctx, tk_object_t* args, uint32_t index, csv_row_t* row); /** * 返回值: * RET_OK: 数据有效 * RET_FAIL:数据无效 */ typedef ret_t (*csv_filter_object_check_new_row_t)(void* ctx, csv_row_t* row); /** * @class csv_file_object_t * @parent tk_object_t * 将cvs file包装成object对象。 * * 示例 * * ```c * char filename[MAX_PATH + 1] = {0}; * path_prepend_temp_path(filename, "test.csv"); * * const char *csv_data1 = "name,age,weight\n" * "awplc,18,60.5\n"; * ENSURE(file_write(filename, csv_data1, strlen(csv_data1)) == RET_OK); * * // 从文件加载 * tk_object_t *csv = csv_file_object_load(filename, ','); * * // 获取数据: 通过属性名 * ENSURE(tk_str_eq(tk_object_get_prop_str(csv, "[1].name"), "awplc")); * ENSURE(tk_object_get_prop_int(csv, "[1].age", 0) == 18); * ENSURE(tk_object_get_prop_double(csv, "[1].weight", 0) == 60.5); * * // 获取数据: 通过属性索引 * ENSURE(tk_str_eq(tk_object_get_prop_str(csv, "[1].0"), "awplc")); * ENSURE(tk_object_get_prop_int(csv, "[1].1", 0) == 18); * ENSURE(tk_object_get_prop_double(csv, "[1].2", 0) == 60.5); * * // 销毁对象 * TK_OBJECT_UNREF(csv); * * // 从内存加载 * csv = csv_file_object_load_from_buff(csv_data1, strlen(csv_data1), ','); * * // 获取数据: 通过属性名 * ENSURE(tk_str_eq(tk_object_get_prop_str(csv, "[1].name"), "awplc")); * ENSURE(tk_object_get_prop_int(csv, "[1].age", 0) == 18); * ENSURE(tk_object_get_prop_double(csv, "[1].weight", 0) == 60.5); * * // 获取数据: 通过属性索引 * ENSURE(tk_str_eq(tk_object_get_prop_str(csv, "[1].0"), "awplc")); * ENSURE(tk_object_get_prop_int(csv, "[1].1", 0) == 18); * ENSURE(tk_object_get_prop_double(csv, "[1].2", 0) == 60.5); * * // 设置数据 * ENSURE(tk_object_set_prop_int(csv, "[1].age", 20) == RET_OK); * ENSURE(tk_object_get_prop_int(csv, "[1].age", 0) == 20); * * // 保存到文件 * ENSURE(csv_file_object_save_as(csv, filename) == RET_OK); * ENSURE(file_exist(filename) == TRUE); * * // 销毁对象 * TK_OBJECT_UNREF(csv); * ``` */ typedef struct _csv_file_object_t { tk_object_t object; /*private*/ csv_file_t* csv; str_t str; tk_object_t* query_args; uint32_t* rows_map; uint32_t rows_map_size; uint32_t rows_map_capacity; csv_file_object_filter_t filter; void* filter_ctx; bool_t is_dirty; csv_filter_object_check_new_row_t check_new_row; void* check_new_row_ctx; csv_row_t col_names; } csv_file_object_t; /** * @method csv_file_object_create * * 将csv_file对象包装成object。 * * @param {csv_file_t*} csv csv对象(由object释放)。 * * @return {tk_object_t*} 返回对象。 */ tk_object_t* csv_file_object_create(csv_file_t* csv); /** * @method csv_file_object_get_csv * * 获取csv对象。 * * @param {tk_object_t*} obj obj对象。 * * @return {csv_file_t*} 返回csv对象。 */ csv_file_t* csv_file_object_get_csv(tk_object_t* obj); /** * @method csv_file_object_load * 从指定文件加载CSV对象。 * * @annotation ["constructor"] * * @param {const char*} filename 文件名。 * @param {char} sep 分隔符。 * * @return {tk_object_t*} 返回配置对象。 */ tk_object_t* csv_file_object_load(const char* filename, char sep); /** * @method csv_file_object_load_from_buff * 从内存加载CSV对象。 * @annotation ["constructor"] * * @param {const void*} buff 数据。 * @param {uint32_t} size 数据长度。 * @param {char} sep 分隔符。 * * @return {tk_object_t*} 返回配置对象。 */ tk_object_t* csv_file_object_load_from_buff(const void* buff, uint32_t size, char sep); /** * @method csv_file_object_save_to_buff * 将obj保存为CSV格式到内存。 * * @param {tk_object_t*} obj doc对象。 * @param {wbuffer_t*} wb 返回结果(不要初始化,使用完成后要调用wbuffer_deinit)。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败 */ ret_t csv_file_object_save_to_buff(tk_object_t* obj, wbuffer_t* wb); /** * @method csv_file_object_set_filter * 设置过滤器。 * * @param {tk_object_t*} obj doc对象。 * @param {csv_file_object_filter_t} filter 过滤器。 * @param {void*} ctx 上下文。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败 */ ret_t csv_file_object_set_filter(tk_object_t* obj, csv_file_object_filter_t filter, void* ctx); /** * @method csv_file_object_save_as * 将doc对象保存到指定文件。 * @annotation ["static"] * * @param {tk_object_t*} obj doc对象。 * @param {const char*} filename 文件名。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败 */ ret_t csv_file_object_save_as(tk_object_t* obj, const char* filename); /** * @method csv_file_object_find_first * 查找第一个满足条件的行。 * * @param {tk_object_t*} obj doc对象。 * @param {tk_compare_t} compare 比较函数。 * @param {void*} ctx 上下文。 * * @return {csv_row_t*} 返回行对象。 */ csv_row_t* csv_file_object_find_first(tk_object_t* obj, tk_compare_t compare, void* ctx); /** * @method csv_file_object_set_check_new_row * 设置检查新行的回调。 * * @param {tk_object_t*} obj doc对象。 * @param {csv_filter_object_check_new_row_t} check_new_row 检查新行的回调。 * @param {void*} ctx 上下文。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败 */ ret_t csv_file_object_set_check_new_row(tk_object_t* obj, csv_filter_object_check_new_row_t check_new_row, void* ctx); /** * @method csv_file_object_parse_col * 解析列名。 * @param {csv_file_object_t*} o csv_file_object_t对象。 * @param {const char*} name 列名。 * * @return {int32_t} 返回列索引。 */ int32_t csv_file_object_parse_col(csv_file_object_t* o, const char* name); /** * @method csv_file_object_cast * 转换为csv_file_object_t。 * @annotation ["cast", "scriptable"] * * @param {tk_object_t*} obj doc对象。 * * @return {csv_file_object_t*} 返回csv_file_object_t对象。 */ csv_file_object_t* csv_file_object_cast(tk_object_t* obj); #define CSV_FILE_OBJECT(obj) csv_file_object_cast((tk_object_t*)obj) #define CSV_QUERY_PREFIX "query." #define CSV_CMD_QUERY "query" #define CSV_CMD_QUERY_ARG_CLEAR "clear" #define CSV_PROP_COL_NAMES "col_names" END_C_DECLS #endif /*TK_CSV_FILE_OBJECT_H*/
0
repos/awtk/src
repos/awtk/src/csv/csv_file.h
/** * File: csv_file.h * Author: AWTK Develop Team * Brief: csv file * * Copyright (c) 2020 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2020-06-08 Li XianJing <[email protected]> created * */ #ifndef TK_CSV_FILE_H #define TK_CSV_FILE_H #include "tkc/istream.h" #include "tkc/buffer.h" BEGIN_C_DECLS typedef struct _csv_row_t { char* buff; uint32_t size : 30; uint32_t checked : 1; uint32_t should_free_buff : 1; } csv_row_t; typedef struct _csv_rows_t { csv_row_t* rows; uint32_t size; uint32_t capacity; } csv_rows_t; struct _csv_file_t; typedef struct _csv_file_t csv_file_t; /** * 返回值: * RET_OK: 保留 * RET_STOP: 停止解析 * RET_FAIL: 忽略此行 */ typedef ret_t (*csv_file_filter_t)(void* ctx, csv_file_t* csv, uint32_t index, csv_row_t* row); /** * @class csv_file_t * 操作CSV文件。 */ struct _csv_file_t { /** * @property {bool_t} has_title * 是否有标题。 */ bool_t has_title; /** * @property {bool_t} single_select * 是否单选。 */ bool_t single_select; /*private*/ char sep; uint32_t cols; char* filename; csv_rows_t rows; void* filter_ctx; uint32_t max_rows; csv_file_filter_t filter; }; /** * @method csv_file_create_empty * * 创建空的csv对象。 * * @param {char} sep 分隔符。 * @param {csv_file_filter_t} filter 过滤函数。 * @param {void*} ctx 过滤函数的上下文。 * * @return {csv_file_t*} 返回csv对象。 */ csv_file_t* csv_file_create_empty(char sep, csv_file_filter_t filter, void* ctx); /** * @method csv_file_set_filter * * 设置过滤函数。 * * @param {csv_file_t*} csv csv对象。 * @param {csv_file_filter_t} filter 过滤函数。 * @param {void*} ctx 过滤函数的上下文。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_set_filter(csv_file_t* csv, csv_file_filter_t filter, void* ctx); /** * @method csv_file_create * * 根据文件创建csv对象。 * * @param {const char*} filename 文件名。 * @param {char} sep 分隔符。 * * @return {csv_file_t*} 返回csv对象。 */ csv_file_t* csv_file_create(const char* filename, char sep); /** * @method csv_file_create_with_buff * * 根据buff创建csv对象。 * * @param {const char*} buff 数据。 * @param {uint32_t} size 数据长度。 * @param {char} sep 分隔符。 * * @return {csv_file_t*} 返回csv对象。 */ csv_file_t* csv_file_create_with_buff(const char* buff, uint32_t size, char sep); /** * @method csv_file_load_file * * 从文件加载csv。 * * @param {csv_file_t*} csv csv对象。 * @param {const char*} filename 文件名。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_load_file(csv_file_t* csv, const char* filename); /** * @method csv_file_load_buff * * 从内存加载csv。 * * @param {csv_file_t*} csv csv对象。 * @param {const char*} buff 数据。 * @param {uint32_t} size 数据长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_load_buff(csv_file_t* csv, const char* buff, uint32_t size); /** * @method csv_file_reload * * 丢弃内存中的修改,重新加载当前文件。 * * @param {csv_file_t*} csv csv对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_reload(csv_file_t* csv); /** * @method csv_file_get * * 获取指定行列的数据。 * * @param {csv_file_t*} csv csv对象。 * @param {uint32_t} row 行号。 * @param {uint32_t} col 列号。 * * @return {const char*} 返回数据。 */ const char* csv_file_get(csv_file_t* csv, uint32_t row, uint32_t col); /** * @method csv_file_set * * 修改指定行列的数据。 * * @param {csv_file_t*} csv csv对象。 * @param {uint32_t} row 行号。 * @param {uint32_t} col 列号。 * @param {const char*} value 值。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_set(csv_file_t* csv, uint32_t row, uint32_t col, const char* value); /** * @method csv_file_uncheck_all * 取消勾选全部行。 * @param {csv_file_t*} csv csv对象。 * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_uncheck_all(csv_file_t* csv); /** * @method csv_file_get_first_checked * * 获取第一个勾选的行。 * * @param {csv_file_t*} csv csv对象。 * * @return {int32_t} 返回行号。 */ int32_t csv_file_get_first_checked(csv_file_t* csv); /** * @method csv_file_set_row_checked * * 勾选指定行。 * * @param {csv_file_t*} csv csv对象。 * @param {uint32_t} row 行号。 * @param {bool_t} checked 是否勾选。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_set_row_checked(csv_file_t* csv, uint32_t row, bool_t checked); /** * @method csv_file_set_max_rows * * 设置最大行数。 * * @param {csv_file_t*} csv csv对象。 * @param {uint32_t} max_rows 最大行数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_set_max_rows(csv_file_t* csv, uint32_t max_rows); /** * @method csv_file_set_single_select * 设置是否单选。 * @param {csv_file_t*} csv csv对象。 * @param {bool_t} single_select 是否单选。 * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 * */ ret_t csv_file_set_single_select(csv_file_t* csv, bool_t single_select); /** * @method csv_file_is_row_checked * * 判断指定行是否勾选。 * * @param {csv_file_t*} csv csv对象。 * @param {uint32_t} row 行号。 * * @return {bool_t} 返回TRUE表示勾选,否则表示没勾选。 */ bool_t csv_file_is_row_checked(csv_file_t* csv, uint32_t row); /** * @method csv_file_remove_checked_rows * * 删除全部勾选的行。 * * @param {csv_file_t*} csv csv对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_remove_checked_rows(csv_file_t* csv); /** * @method csv_file_get_title * * 获取标题(不存在则返回NULL)。 * * @param {csv_file_t*} csv csv对象。 * * @return {const char*} 返回标题。 */ const char* csv_file_get_title(csv_file_t* csv); /** * @method csv_file_get_rows * * 获取行数(包括标题)。 * * @param {csv_file_t*} csv csv对象。 * * @return {uint32_t} 返回行数。 */ uint32_t csv_file_get_rows(csv_file_t* csv); /** * @method csv_file_get_checked_rows * * 获取checked行数(包括标题)。 * * @param {csv_file_t*} csv csv对象。 * * @return {uint32_t} 返回checked行数。 */ uint32_t csv_file_get_checked_rows(csv_file_t* csv); /** * @method csv_file_get_cols * * 获取列数。 * * @param {csv_file_t*} csv csv对象。 * * @return {uint32_t} 返回列数。 */ uint32_t csv_file_get_cols(csv_file_t* csv); /** * @method csv_file_remove_row * * 删除指定行。 * * @param {csv_file_t*} csv csv对象。 * @param {uint32_t} row 行号。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_remove_row(csv_file_t* csv, uint32_t row); /** * @method csv_file_append_row * * 追加一行。 * * @param {csv_file_t*} csv csv对象。 * @param {const char*} data 数据。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_append_row(csv_file_t* csv, const char* data); /** * @method csv_file_insert_row * * 插入一行。 * * @param {csv_file_t*} csv csv对象。 * @param {uint32_t} row 行号。 * @param {const char*} data 数据。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_insert_row(csv_file_t* csv, uint32_t row, const char* data); /** * @method csv_file_save * * 保存。 * * @param {csv_file_t*} csv csv对象。 * @param {const char*} filename 文件名。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_save(csv_file_t* csv, const char* filename); /** * @method csv_file_save_to_buff * * 保存。 * * @param {csv_file_t*} csv csv对象。 * @param {wbuffer_t*} buff 保存结果数据。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_save_to_buff(csv_file_t* csv, wbuffer_t* buff); /** * @method csv_file_clear * * 保存。 * * @param {csv_file_t*} csv csv对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_clear(csv_file_t* csv); /** * @method csv_file_load_file * * 保存。 * * @param {csv_file_t*} csv csv对象。 * @param {const char*} filename 文件名。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_load_file(csv_file_t* csv, const char* filename); /** * @method csv_file_find_first * * 查找第一个满足条件的行。 * * @param {csv_file_t*} csv csv对象。 * @param {tk_compare_t} compare 比较函数。 * @param {void*} ctx 比较函数的上下文。 * * @return {csv_row_t*} 返回行对象。 */ csv_row_t* csv_file_find_first(csv_file_t* csv, tk_compare_t compare, void* ctx); /** * @method csv_file_destroy * * 销毁csv对象。 * * @param {csv_file_t*} csv csv对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_file_destroy(csv_file_t* csv); /** * @method csv_file_get_by_name * * 根据列名获取数据。 * * @param {csv_file_t*} csv csv对象。 * @param {uint32_t} row 行号。 * @param {const char*} name 列名。 * * @return {const char*} 返回数据。 */ const char* csv_file_get_by_name(csv_file_t* csv, uint32_t row, const char* name); /** * @method csv_file_get_col_of_name * * 根据列名获取列号。 * * @param {csv_file_t*} csv csv对象。 * @param {const char*} name 列名。 * * @return {int32_t} 返回列号。 */ int32_t csv_file_get_col_of_name(csv_file_t* csv, const char* name); /** * @method csv_file_get_row * * 获取指定行。 * * @param {csv_file_t*} csv csv对象。 * @param {uint32_t} row 行号。 * * @return {csv_row_t*} 返回行对象。 */ csv_row_t* csv_file_get_row(csv_file_t* csv, uint32_t row); /** * @class csv_row_t * 行对象。 */ /** * @method csv_row_count_cols * 获取列数。 * @param {csv_row_t*} row 行对象。 * @return {uint32_t} 返回列数。 */ uint32_t csv_row_count_cols(csv_row_t* row); /** * @method csv_row_get * * 获取指定列的数据。 * * @param {csv_row_t*} row 行对象。 * @param {uint32_t} col 列号。 * * @return {const char*} 返回数据。 */ const char* csv_row_get(csv_row_t* row, uint32_t col); /** * @method csv_row_set * * 修改指定列的数据。 * * @param {csv_row_t*} row 行对象。 * @param {uint32_t} col 列号。 * @param {const char*} value 值。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t csv_row_set(csv_row_t* row, uint32_t col, const char* value); /** * @method csv_row_get_col * * 根据列名获取列号。 * * @param {csv_row_t*} row 行对象。 * @param {const char*} value 列名。 * * @return {int32_t} 返回列号。 */ int32_t csv_row_get_col(csv_row_t* row, const char* value); /*public for test*/ ret_t csv_row_init(csv_row_t* row, char* buff, uint32_t size, bool_t should_free_buff); ret_t csv_row_reset(csv_row_t* row); ret_t csv_rows_init(csv_rows_t* rows, uint32_t init_capacity); ret_t csv_rows_remove(csv_rows_t* rows, uint32_t row); csv_row_t* csv_rows_append(csv_rows_t* rows); csv_row_t* csv_rows_insert(csv_rows_t* rows, uint32_t row); csv_row_t* csv_rows_get(csv_rows_t* rows, uint32_t row); ret_t csv_rows_reset(csv_rows_t* rows); ret_t csv_row_to_str(csv_row_t* row, str_t* str, char sep); ret_t csv_row_set_data(csv_row_t* row, const char* data, char sep); END_C_DECLS #endif /*TK_CSV_FILE_H*/
0
repos/awtk/src
repos/awtk/src/csv/csv_file.c
/** * File: csv_file.c * Author: AWTK Develop Team * Brief: csv file * * Copyright (c) 2020 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2020-06-08 Li XianJing <[email protected]> created * */ #include "tkc/mem.h" #include "tkc/utils.h" #include "tkc/data_writer.h" #include "tkc/data_writer_factory.h" #include "csv_file.h" #include "streams/mem/istream_mem.h" #include "streams/file/istream_file.h" static const uint8_t s_utf8_bom[3] = {0xEF, 0xBB, 0xBF}; ret_t csv_file_reset(csv_file_t* csv); ret_t csv_file_clear(csv_file_t* csv); static ret_t csv_rows_extend_rows(csv_rows_t* rows, uint32_t delta); static csv_file_t* csv_file_load_input(csv_file_t* csv, tk_istream_t* input); const char* csv_row_get(csv_row_t* row, uint32_t col) { uint32_t i = 0; uint32_t c = 0; return_value_if_fail(row != NULL, NULL); while (i < row->size) { const char* p = row->buff + i; if (c == col) { return p; } c++; i += strlen(p) + 1; } return NULL; } int32_t csv_row_get_col(csv_row_t* row, const char* value) { uint32_t i = 0; uint32_t col = 0; return_value_if_fail(row != NULL && value != NULL, -1); while (i < row->size) { const char* p = row->buff + i; if (tk_str_eq(p, value)) { return col; } col++; i += strlen(p) + 1; } return -1; } static ret_t csv_col_to_str(str_t* str, const char* data, char sep) { const char* p = data; bool_t need_escape = strchr(p, sep) != NULL || strchr(p, '\"') != NULL; if (need_escape) { str_append_char(str, '\"'); while (*p) { if (*p == '\\' || *p == '\"') { str_append_char(str, '\\'); } str_append_char(str, *p); p++; } str_append_char(str, '\"'); } else { str_append(str, data); } return RET_OK; } ret_t csv_row_to_str(csv_row_t* row, str_t* str, char sep) { uint32_t i = 0; return_value_if_fail(row != NULL && str != NULL, RET_BAD_PARAMS); str_set(str, ""); while (i < row->size) { const char* p = row->buff + i; csv_col_to_str(str, p, sep); str_append_char(str, sep); i += strlen(p) + 1; } if (str->size > 0) { /*remove last seperator*/ str->size--; str->str[str->size] = '\0'; } str_append(str, "\r\n"); return RET_OK; } uint32_t csv_row_count_cols(csv_row_t* row) { uint32_t i = 0; uint32_t cols = 0; return_value_if_fail(row != NULL, 0); while (i < row->size) { const char* p = row->buff + i; cols++; i += strlen(p) + 1; } return cols; } ret_t csv_row_set(csv_row_t* row, uint32_t col, const char* value) { char* p = NULL; uint32_t old_len = 0; uint32_t new_len = 0; return_value_if_fail(row != NULL && value != NULL, RET_BAD_PARAMS); return_value_if_fail(row->buff != NULL, RET_BAD_PARAMS); p = (char*)csv_row_get(row, col); return_value_if_fail(p != NULL, RET_BAD_PARAMS); old_len = strlen(p); new_len = strlen(value); if (old_len == new_len) { strcpy(p, value); return RET_OK; } else if (old_len > new_len) { uint32_t len = row->size - (p + old_len - row->buff); strcpy(p, value); memmove(p + new_len, p + old_len, len); row->size = row->size + new_len - old_len; return RET_OK; } else { uint32_t d = 0; uint32_t s = 0; uint32_t size = 0; uint32_t len = row->size + new_len - old_len; char* buff = TKMEM_ALLOC(len); return_value_if_fail(buff != NULL, RET_OOM); memset(buff, 0x00, len); size = p - row->buff; memcpy(buff, row->buff, size); d = size; s = size; memcpy(buff + d, value, new_len + 1); d += new_len + 1; s += old_len + 1; size = row->size - s; memcpy(buff + d, row->buff + s, size); csv_row_reset(row); row->buff = buff; row->size = len; row->should_free_buff = TRUE; return RET_OK; } } ret_t csv_row_init(csv_row_t* row, char* buff, uint32_t size, bool_t should_free_buff) { return_value_if_fail(row != NULL && buff != NULL, RET_BAD_PARAMS); row->buff = buff; row->size = size; row->should_free_buff = should_free_buff; return RET_OK; } static ret_t csv_row_parse(csv_row_t* row, char sep) { char* s = row->buff; char* d = row->buff; bool_t escape = FALSE; bool_t in_quota = FALSE; while (*s) { char c = *s; s++; if (in_quota) { if (escape) { *d++ = c; escape = FALSE; } else { if (c == '\"') { in_quota = FALSE; } else if (c == '\\') { escape = TRUE; } else { *d++ = c; } } } else { if (c == sep) { *d++ = '\0'; } else if (c == '\"') { in_quota = TRUE; } else { *d++ = c; } } } *d = '\0'; row->size = d - row->buff + 1; return RET_OK; } ret_t csv_row_set_data(csv_row_t* row, const char* data, char sep) { csv_row_reset(row); row->buff = tk_strdup(data); return_value_if_fail(row->buff != NULL, RET_OOM); row->should_free_buff = TRUE; row->size = strlen(data) + 1; return csv_row_parse(row, sep); } ret_t csv_row_reset(csv_row_t* row) { return_value_if_fail(row != NULL, RET_BAD_PARAMS); if (row->should_free_buff) { TKMEM_FREE(row->buff); } memset(row, 0x00, sizeof(*row)); return RET_OK; } static ret_t csv_rows_extend_rows(csv_rows_t* rows, uint32_t delta) { uint32_t capacity = 0; csv_row_t* first = NULL; return_value_if_fail(rows != NULL, RET_BAD_PARAMS); if ((rows->size + delta) < rows->capacity) { return RET_OK; } first = rows->rows; capacity = rows->capacity * 1.5 + delta; first = TKMEM_REALLOC(first, capacity * sizeof(csv_row_t)); return_value_if_fail(first != NULL, RET_OOM); rows->rows = first; rows->capacity = capacity; return RET_OK; } ret_t csv_rows_remove(csv_rows_t* rows, uint32_t row) { uint32_t i = 0; csv_row_t* r = NULL; return_value_if_fail(rows != NULL && row < rows->size, RET_BAD_PARAMS); csv_row_reset(rows->rows + row); r = rows->rows; for (i = row; i < rows->size; i++) { r[i] = r[i + 1]; } rows->size--; return RET_OK; } csv_row_t* csv_rows_append(csv_rows_t* rows) { csv_row_t* r = NULL; return_value_if_fail(csv_rows_extend_rows(rows, 1) == RET_OK, NULL); r = rows->rows + rows->size++; memset(r, 0x00, sizeof(*r)); return r; } csv_row_t* csv_rows_insert(csv_rows_t* rows, uint32_t row) { uint32_t i = 0; csv_row_t* r = NULL; return_value_if_fail(rows != NULL, NULL); return_value_if_fail(csv_rows_extend_rows(rows, 1) == RET_OK, NULL); if (row >= rows->size) { return csv_rows_append(rows); } r = rows->rows; for (i = rows->size; i > row; i--) { r[i] = r[i - 1]; } r = r + row; memset(r, 0x00, sizeof(*r)); rows->size++; return r; } csv_row_t* csv_rows_get(csv_rows_t* rows, uint32_t row) { return_value_if_fail(rows != NULL && row < rows->size, NULL); return rows->rows + row; } ret_t csv_rows_reset(csv_rows_t* rows) { return_value_if_fail(rows != NULL && rows->rows != NULL, RET_BAD_PARAMS); TKMEM_FREE(rows->rows); memset(rows, 0x00, sizeof(*rows)); return RET_OK; } ret_t csv_rows_init(csv_rows_t* rows, uint32_t init_capacity) { return_value_if_fail(rows != NULL, RET_BAD_PARAMS); init_capacity = tk_max(10, init_capacity); rows->size = 0; rows->capacity = init_capacity; rows->rows = TKMEM_ZALLOCN(csv_row_t, init_capacity); return rows->rows != NULL ? RET_OK : RET_OOM; } csv_file_t* csv_file_load(csv_file_t* csv) { tk_istream_t* input = NULL; return_value_if_fail(csv != NULL && csv->filename != NULL, NULL); input = tk_istream_file_create(csv->filename); return_value_if_fail(input != NULL, NULL); csv_file_load_input(csv, input); TK_OBJECT_UNREF(input); return csv; } static csv_file_t* csv_file_load_input(csv_file_t* csv, tk_istream_t* input) { str_t str; char* p = NULL; uint32_t index = 0; csv_row_t* r = NULL; char sep = csv->sep; str_init(&str, 2048); while (tk_istream_read_line_str(input, &str) == RET_OK) { p = str.str; if (csv->rows.size == 0) { if (memcmp(p, s_utf8_bom, sizeof(s_utf8_bom)) == 0) { p += sizeof(s_utf8_bom); log_debug("skip utf-8 bom\n"); } } /*skip malformed data*/ while ((p - str.str) < str.size) { if (*p == '\0') { p++; } else { break; } } if (*p == '\0') { log_debug("skip empty line\n"); continue; } r = csv_rows_append(&(csv->rows)); goto_error_if_fail(r != NULL); goto_error_if_fail(csv_row_init(r, tk_strdup(p), str.size + 1, TRUE) == RET_OK); csv_row_parse(r, sep); if (csv->filter != NULL) { ret_t ret = csv->filter(csv->filter_ctx, csv, index, r); if (ret == RET_STOP) { break; } else if (ret == RET_FAIL) { csv_row_reset(r); csv->rows.size--; } } index++; } str_reset(&str); r = csv_file_get_row(csv, 0); if (r != NULL) { uint32_t cols1 = 0; uint32_t cols0 = csv_row_count_cols(r); if (cols0 == 1) { r = csv_file_get_row(csv, 1); cols1 = csv_row_count_cols(r); if (cols1 > cols0) { csv->has_title = TRUE; } csv->cols = tk_max(cols0, cols1); } else { csv->cols = csv_row_count_cols(r); } } str_reset(&str); return csv; error: str_reset(&str); return NULL; } csv_file_t* csv_file_create_empty(char sep, csv_file_filter_t filter, void* ctx) { csv_file_t* csv = TKMEM_ZALLOC(csv_file_t); return_value_if_fail(csv != NULL, NULL); if (csv_rows_init(&(csv->rows), 100) == RET_OK) { csv->sep = sep; csv->filter = filter; csv->filter_ctx = ctx; } else { TKMEM_FREE(csv); } return csv; } ret_t csv_file_set_filter(csv_file_t* csv, csv_file_filter_t filter, void* ctx) { return_value_if_fail(csv != NULL, RET_BAD_PARAMS); csv->filter = filter; csv->filter_ctx = ctx; return RET_OK; } csv_file_t* csv_file_create(const char* filename, char sep) { csv_file_t* csv = NULL; return_value_if_fail(filename != NULL, NULL); csv = csv_file_create_empty(sep, NULL, NULL); return_value_if_fail(csv != NULL, NULL); if (csv_file_load_file(csv, filename) != RET_OK) { csv_file_destroy(csv); csv = NULL; } return csv; } ret_t csv_file_load_buff(csv_file_t* csv, const char* buff, uint32_t size) { ret_t ret = RET_OK; tk_istream_t* input = NULL; return_value_if_fail(csv != NULL && buff != NULL && size > 0, RET_BAD_PARAMS); input = tk_istream_mem_create((uint8_t*)buff, size, 0, FALSE); return_value_if_fail(input != NULL, RET_BAD_PARAMS); csv_file_clear(csv); ret = csv_file_load_input(csv, input) != NULL ? RET_OK : RET_FAIL; TK_OBJECT_UNREF(input); return ret; } csv_file_t* csv_file_create_with_buff(const char* buff, uint32_t size, char sep) { csv_file_t* csv = NULL; csv = csv_file_create_empty(sep, NULL, NULL); return_value_if_fail(csv != NULL, NULL); if (csv_file_load_buff(csv, buff, size) != RET_OK) { csv_file_destroy(csv); csv = NULL; } return csv; } const char* csv_file_get(csv_file_t* csv, uint32_t row, uint32_t col) { csv_row_t* r = csv_file_get_row(csv, row); return_value_if_fail(r != NULL, NULL); return_value_if_fail(col < csv_file_get_cols(csv), NULL); return csv_row_get(r, col); } int32_t csv_file_get_col_of_name(csv_file_t* csv, const char* name) { return csv_row_get_col(csv_file_get_row(csv, 0), name); } const char* csv_file_get_by_name(csv_file_t* csv, uint32_t row, const char* name) { int32_t col = csv_file_get_col_of_name(csv, name); return_value_if_fail(col >= 0, NULL); return csv_file_get(csv, row, col); } uint32_t csv_file_get_rows(csv_file_t* csv) { return_value_if_fail(csv != NULL, 0); return csv->rows.size; } uint32_t csv_file_get_checked_rows(csv_file_t* csv) { uint32_t i = 0; uint32_t nr = 0; csv_row_t* r = NULL; csv_rows_t* rows = NULL; return_value_if_fail(csv != NULL, 0); rows = &(csv->rows); for (i = 0; i < rows->size; i++) { r = rows->rows + i; if (r->checked) { nr++; } } return nr; } uint32_t csv_file_get_cols(csv_file_t* csv) { return_value_if_fail(csv != NULL, 0); return csv->cols; } ret_t csv_file_set(csv_file_t* csv, uint32_t row, uint32_t col, const char* value) { csv_row_t* r = csv_file_get_row(csv, row); return_value_if_fail(r != NULL, RET_BAD_PARAMS); return_value_if_fail(col < csv_file_get_cols(csv), RET_BAD_PARAMS); return csv_row_set(r, col, value); } ret_t csv_file_uncheck_all(csv_file_t* csv) { uint32_t i = 0; return_value_if_fail(csv != NULL, RET_BAD_PARAMS); for (i = 0; i < csv->rows.size; i++) { csv_row_t* r = csv->rows.rows + i; r->checked = FALSE; } return RET_OK; } int32_t csv_file_get_first_checked(csv_file_t* csv) { uint32_t i = 0; return_value_if_fail(csv != NULL, RET_BAD_PARAMS); for (i = 0; i < csv->rows.size; i++) { csv_row_t* r = csv->rows.rows + i; if (r->checked) { return i; } } return -1; } ret_t csv_file_set_row_checked(csv_file_t* csv, uint32_t row, bool_t checked) { csv_row_t* r = csv_file_get_row(csv, row); return_value_if_fail(r != NULL, RET_BAD_PARAMS); if (csv->single_select) { csv_file_uncheck_all(csv); } r->checked = checked; return RET_OK; } ret_t csv_file_set_max_rows(csv_file_t* csv, uint32_t max_rows) { return_value_if_fail(csv != NULL, RET_BAD_PARAMS); csv->max_rows = max_rows; return RET_OK; } ret_t csv_file_set_single_select(csv_file_t* csv, bool_t single_select) { return_value_if_fail(csv != NULL, RET_BAD_PARAMS); csv->single_select = single_select; return RET_OK; } bool_t csv_file_is_row_checked(csv_file_t* csv, uint32_t row) { csv_row_t* r = csv_file_get_row(csv, row); return_value_if_fail(r != NULL, FALSE); return r->checked; } ret_t csv_file_remove_checked_rows(csv_file_t* csv) { uint32_t i = 0; uint32_t d = 0; csv_row_t* r = NULL; csv_rows_t* rows = NULL; return_value_if_fail(csv != NULL, RET_BAD_PARAMS); rows = &(csv->rows); for (i = 0; i < rows->size; i++) { r = rows->rows + i; if (r->checked) { csv_row_reset(r); } else { rows->rows[d++] = rows->rows[i]; } } rows->size = d; return RET_OK; } csv_row_t* csv_file_get_row(csv_file_t* csv, uint32_t row) { return_value_if_fail(csv != NULL, NULL); return csv_rows_get(&(csv->rows), row); } ret_t csv_file_insert_row(csv_file_t* csv, uint32_t row, const char* data) { csv_row_t* r = NULL; return_value_if_fail(csv != NULL && data != NULL, RET_BAD_PARAMS); r = csv_rows_insert(&(csv->rows), row); return_value_if_fail(r != NULL, RET_OOM); return csv_row_set_data(r, data, csv->sep); } ret_t csv_file_append_row(csv_file_t* csv, const char* data) { csv_row_t* r = NULL; return_value_if_fail(csv != NULL && data != NULL, RET_BAD_PARAMS); if (csv->max_rows > 0 && csv->rows.size >= csv->max_rows) { csv_file_remove_row(csv, 0); } r = csv_rows_append(&(csv->rows)); return_value_if_fail(r != NULL, RET_OOM); return csv_row_set_data(r, data, csv->sep); } ret_t csv_file_remove_row(csv_file_t* csv, uint32_t row) { return_value_if_fail(csv != NULL, RET_BAD_PARAMS); return csv_rows_remove(&(csv->rows), row); } ret_t csv_file_save_to_buff(csv_file_t* csv, wbuffer_t* buff) { str_t str; uint32_t i = 0; csv_row_t* r = NULL; return_value_if_fail(csv != NULL, RET_BAD_PARAMS); return_value_if_fail(buff != NULL, RET_BAD_PARAMS); return_value_if_fail(str_init(&str, 512) != NULL, RET_OOM); for (i = 0; i < csv->rows.size; i++) { r = csv->rows.rows + i; csv_row_to_str(r, &str, csv->sep); ENSURE(wbuffer_write_binary(buff, str.str, str.size) == RET_OK); } str_reset(&str); return RET_OK; } ret_t csv_file_save(csv_file_t* csv, const char* filename) { str_t str; uint32_t i = 0; csv_row_t* r = NULL; fs_file_t* f = NULL; return_value_if_fail(csv != NULL, RET_BAD_PARAMS); filename = filename != NULL ? filename : csv->filename; return_value_if_fail(filename != NULL, RET_BAD_PARAMS); return_value_if_fail(str_init(&str, 512) != NULL, RET_OOM); f = fs_open_file(os_fs(), filename, "wb+"); if (f != NULL) { ENSURE(fs_file_write(f, s_utf8_bom, sizeof(s_utf8_bom)) == sizeof(s_utf8_bom)); for (i = 0; i < csv->rows.size; i++) { r = csv->rows.rows + i; csv_row_to_str(r, &str, csv->sep); ENSURE(fs_file_write(f, str.str, str.size) == str.size); } fs_file_close(f); if (csv->filename != filename) { TKMEM_FREE(csv->filename); csv->filename = tk_strdup(filename); } } str_reset(&str); return RET_OK; } const char* csv_file_get_title(csv_file_t* csv) { csv_row_t* r = NULL; return_value_if_fail(csv != NULL && csv->has_title, NULL); r = csv_file_get_row(csv, 0); return_value_if_fail(r != NULL, NULL); return r->buff; } ret_t csv_file_clear(csv_file_t* csv) { uint32_t i = 0; return_value_if_fail(csv != NULL, RET_BAD_PARAMS); for (i = 0; i < csv->rows.size; i++) { csv_row_t* r = csv->rows.rows + i; csv_row_reset(r); } csv->rows.size = 0; return RET_OK; } ret_t csv_file_reset(csv_file_t* csv) { return_value_if_fail(csv != NULL, RET_BAD_PARAMS); csv_file_clear(csv); TKMEM_FREE(csv->filename); TKMEM_FREE(csv->rows.rows); memset(csv, 0x00, sizeof(*csv)); return RET_OK; } ret_t csv_file_destroy(csv_file_t* csv) { if (csv_file_reset(csv) == RET_OK) { TKMEM_FREE(csv); } return RET_OK; } ret_t csv_file_reload(csv_file_t* csv) { return_value_if_fail(csv != NULL && csv->filename != NULL, RET_BAD_PARAMS); csv_file_clear(csv); return (csv_file_load(csv) != NULL) ? RET_OK : RET_FAIL; } ret_t csv_file_load_file(csv_file_t* csv, const char* filename) { return_value_if_fail(csv != NULL && filename != NULL, RET_BAD_PARAMS); csv_file_clear(csv); csv->filename = tk_str_copy(csv->filename, filename); return (csv_file_load(csv) != NULL) ? RET_OK : RET_FAIL; } csv_row_t* csv_file_find_first(csv_file_t* csv, tk_compare_t compare, void* ctx) { uint32_t i = 0; csv_row_t* r = NULL; return_value_if_fail(csv != NULL && compare != NULL, NULL); for (i = 0; i < csv->rows.size; i++) { r = csv->rows.rows + i; if (compare(ctx, r) == 0) { return r; } } return NULL; }
0
repos/awtk/src
repos/awtk/src/csv/README.md
# csv 文件 > 本目录的文件从 [awtk-csv-file](https://github.com/zlgopen/awtk-csv-file) 拷贝而来。如果需要修改,请先修改 [awtk-csv-file](https://github.com/zlgopen/awtk-csv-file),再拷贝过来。 csv 为可选组件,需要自己包含头文件 ```c #include "csv/csv_file.h" #include "csv/csv_file_object.h" ``` ## 示例: * 普通方式访问 ```c const char* str = "11,12,13\n21,22,23"; csv_file_t* csv = csv_file_create_with_buff(str, strlen(str), ','); ASSERT_EQ(csv_file_get_rows(csv), 2); ASSERT_EQ(csv_file_get_cols(csv), 3); ASSERT_STREQ(csv_file_get(csv, 0, 0), "11"); ASSERT_STREQ(csv_file_get(csv, 0, 1), "12"); ASSERT_STREQ(csv_file_get(csv, 0, 2), "13"); ASSERT_STREQ(csv_file_get(csv, 1, 0), "21"); ASSERT_STREQ(csv_file_get(csv, 1, 1), "22"); ASSERT_STREQ(csv_file_get(csv, 1, 2), "23"); csv_file_destroy(csv); ``` ```c TEST(csv_file, title) { const char* str = "aa,bb,cc\n11,12,13\n21,22,23"; csv_file_t* csv = csv_file_create_with_buff(str, strlen(str), ','); ASSERT_EQ(csv_file_get_rows(csv), 3); ASSERT_EQ(csv_file_get_cols(csv), 3); ASSERT_STREQ(csv_file_get(csv, 0, 0), "aa"); ASSERT_STREQ(csv_file_get(csv, 0, 1), "bb"); ASSERT_STREQ(csv_file_get(csv, 0, 2), "cc"); ASSERT_STREQ(csv_file_get(csv, 1, 0), "11"); ASSERT_STREQ(csv_file_get(csv, 1, 1), "12"); ASSERT_STREQ(csv_file_get(csv, 1, 2), "13"); ASSERT_STREQ(csv_file_get(csv, 2, 0), "21"); ASSERT_STREQ(csv_file_get(csv, 2, 1), "22"); ASSERT_STREQ(csv_file_get(csv, 2, 2), "23"); ASSERT_STREQ(csv_file_get_by_name(csv, 1, "aa"), "11"); ASSERT_STREQ(csv_file_get_by_name(csv, 1, "bb"), "12"); ASSERT_STREQ(csv_file_get_by_name(csv, 1, "cc"), "13"); ASSERT_STREQ(csv_file_get_by_name(csv, 2, "aa"), "21"); ASSERT_STREQ(csv_file_get_by_name(csv, 2, "bb"), "22"); ASSERT_STREQ(csv_file_get_by_name(csv, 2, "cc"), "23"); ASSERT_EQ(csv_file_get_col_of_name(csv, "aa"), 0); ASSERT_EQ(csv_file_get_col_of_name(csv, "bb"), 1); ASSERT_EQ(csv_file_get_col_of_name(csv, "cc"), 2); csv_file_destroy(csv); } ``` * 以对象的方式访问: ```c const char* str = "aa,bb,cc\n11,12,13\n21,22,23"; csv_file_t* csv = csv_file_create_with_buff(str, strlen(str), ','); object_t* obj = csv_file_object_create(csv); ASSERT_EQ(object_get_prop_int(obj, "#size", 0), 3); ASSERT_STREQ(object_get_prop_str(obj, "[0].[0]"), "aa"); ASSERT_STREQ(object_get_prop_str(obj, "[0].[1]"), "bb"); ASSERT_STREQ(object_get_prop_str(obj, "[0].[2]"), "cc"); ASSERT_STREQ(object_get_prop_str(obj, "[1].[0]"), "11"); ASSERT_STREQ(object_get_prop_str(obj, "[1].[1]"), "12"); ASSERT_STREQ(object_get_prop_str(obj, "[1].[2]"), "13"); OBJECT_UNREF(obj); ``` ## 具体用法请参考: * https://github.com/zlgopen/awtk-csv-file/blob/master/tests/csv_file_test.cc * https://github.com/zlgopen/awtk-csv-file/blob/master/tests/csv_file_object_test.cc
0
repos/awtk/src
repos/awtk/src/csv/csv_row_object.h
/** * File: csv_row_object.h * Author: AWTK Develop Team * Brief: csv row object * * Copyright (c) 2020 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License row for more details. * */ /** * History: * ================================================================ * 2023-12-12 Li XianJing <[email protected]> created * */ #ifndef TK_CSV_ROW_OBJECT_H #define TK_CSV_ROW_OBJECT_H #include "tkc/object.h" #include "csv_file_object.h" BEGIN_C_DECLS /** * @class csv_row_object_t * @parent tk_object_t * 将cvs row包装成object对象。 * */ typedef struct _csv_row_object_t { tk_object_t object; /*private*/ csv_row_t row; tk_object_t* csv; } csv_row_object_t; /** * @method csv_row_object_create * * 将csv_row对象包装成object。 * * @param {tk_object_t*} csv csv对象。 * @param {const char*} init 初始化数据。 * * @return {tk_object_t*} 返回对象。 */ tk_object_t* csv_row_object_create(tk_object_t* csv, const char* init); END_C_DECLS #endif /*TK_CSV_ROW_OBJECT_H*/
0
repos/awtk/src
repos/awtk/src/csv/csv_row_object.c
/** * File: csv_row_object.h * Author: AWTK Develop Team * Brief: csv row object * * Copyright (c) 2020 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License row for more details. * */ /** * History: * ================================================================ * 2023-12-12 Li XianJing <[email protected]> created * */ #include "tkc/str.h" #include "tkc/mem.h" #include "tkc/utils.h" #include "csv_file_object.h" #include "csv_row_object.h" static csv_row_object_t* csv_row_object_cast(tk_object_t* obj); #define CSV_ROW_OBJECT(obj) csv_row_object_cast((tk_object_t*)obj) static ret_t csv_row_object_set_prop(tk_object_t* obj, const char* name, const value_t* v) { uint32_t col = 0; char buff[64] = {0}; csv_row_object_t* o = CSV_ROW_OBJECT(obj); return_value_if_fail(o != NULL && name != NULL, RET_BAD_PARAMS); col = csv_file_object_parse_col(CSV_FILE_OBJECT(o->csv), name); return csv_row_set(&(o->row), col, value_str_ex(v, buff, sizeof(buff) - 1)); } static ret_t csv_row_object_get_prop(tk_object_t* obj, const char* name, value_t* v) { uint32_t col = 0; csv_row_object_t* o = CSV_ROW_OBJECT(obj); return_value_if_fail(o != NULL && name != NULL, RET_BAD_PARAMS); col = csv_file_object_parse_col(CSV_FILE_OBJECT(o->csv), name); value_set_str(v, csv_row_get(&(o->row), col)); return RET_OK; } static bool_t csv_row_object_can_exec(tk_object_t* obj, const char* name, const char* args) { csv_row_object_t* o = CSV_ROW_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); if (tk_str_ieq(name, TK_OBJECT_CMD_SAVE) || tk_str_ieq(name, TK_OBJECT_CMD_ADD)) { csv_file_object_t* csv_file_object = CSV_FILE_OBJECT(o->csv); if (csv_file_object->check_new_row != NULL) { return csv_file_object->check_new_row(csv_file_object, &(o->row)) == RET_OK; } return TRUE; } return FALSE; } static ret_t csv_row_object_exec(tk_object_t* obj, const char* name, const char* args) { ret_t ret = RET_NOT_IMPL; csv_row_object_t* o = CSV_ROW_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); if (tk_str_ieq(name, TK_OBJECT_CMD_SAVE) || tk_str_ieq(name, TK_OBJECT_CMD_ADD)) { str_t str; csv_row_t* row = &(o->row); csv_file_object_t* csv_file_object = CSV_FILE_OBJECT(o->csv); str_init(&str, 128); csv_row_to_str(row, &str, csv_file_object->csv->sep); tk_object_exec(TK_OBJECT(csv_file_object), TK_OBJECT_CMD_ADD, str.str); str_reset(&str); ret = RET_OK; } return ret; } static ret_t csv_row_object_destroy(tk_object_t* obj) { csv_row_object_t* o = CSV_ROW_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); csv_row_reset(&(o->row)); o->csv = NULL; return RET_OK; } static const object_vtable_t s_csv_row_object_vtable = {.type = "csv_row_object", .desc = "csv_row_object", .size = sizeof(csv_row_object_t), .is_collection = TRUE, .exec = csv_row_object_exec, .can_exec = csv_row_object_can_exec, .get_prop = csv_row_object_get_prop, .set_prop = csv_row_object_set_prop, .on_destroy = csv_row_object_destroy}; static csv_row_object_t* csv_row_object_cast(tk_object_t* obj) { return_value_if_fail(obj != NULL && obj->vt == &s_csv_row_object_vtable, NULL); return (csv_row_object_t*)obj; } tk_object_t* csv_row_object_create(tk_object_t* csv, const char* init) { tk_object_t* obj = NULL; csv_row_object_t* o = NULL; csv_file_object_t* csv_file_object = CSV_FILE_OBJECT(csv); return_value_if_fail(csv_file_object != NULL, NULL); obj = tk_object_create(&s_csv_row_object_vtable); o = CSV_ROW_OBJECT(obj); return_value_if_fail(o != NULL, NULL); o->csv = csv; csv_row_set_data(&(o->row), init, csv_file_object->csv->sep); return obj; }
0
repos/awtk/src
repos/awtk/src/csv/csv_file_object.c
/** * File: csv_file_object.h * Author: AWTK Develop Team * Brief: csv file object * * Copyright (c) 2020 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2020-07-19 Li XianJing <[email protected]> created * */ #include "tkc/str.h" #include "tkc/mem.h" #include "tkc/utils.h" #include "tkc/object.h" #include "tkc/object_default.h" #include "tkc/data_reader.h" #include "csv_file.h" #include "csv_file_object.h" typedef struct _csv_path_t { int32_t row; int32_t col; const char* col_name; } csv_path_t; int32_t csv_file_object_parse_col(csv_file_object_t* o, const char* name) { int32_t col = -1; const char* p = name; return_value_if_fail(p != NULL && o != NULL, -1); if (*p == '[') { return_value_if_fail(tk_isdigit(p[1]), -1); col = tk_atoi(p + 1); } else if (tk_isdigit(*p)) { col = tk_atoi(p); } else { if (o->col_names.size > 0) { col = csv_row_get_col(&(o->col_names), p); } else { col = csv_file_get_col_of_name(o->csv, p); } if (col < 0) { return_value_if_fail(tk_isdigit(p[0]), -1); col = tk_atoi(p); } } return col; } static ret_t csv_path_parse_impl(csv_file_object_t* o, csv_path_t* path, const char* name) { const char* p = name; csv_file_t* csv = NULL; return_value_if_fail(path != NULL && o != NULL && o->csv != NULL && name != NULL, RET_BAD_PARAMS); csv = o->csv; memset(path, 0x00, sizeof(*path)); while (tk_isspace(*p)) p++; if (tk_isdigit(*p)) { path->row = tk_atoi(p); } else if (*p != '[') { return RET_BAD_PARAMS; } else { p++; /* skip '[' */ if (tk_isdigit(*p)) { path->row = tk_atoi(p); } else { return RET_BAD_PARAMS; } } p = strchr(p, '.'); if (p == NULL) { return RET_OK; } else { p++; } if (tk_str_eq(p, TK_OBJECT_PROP_CHECKED)) { path->col_name = p; return RET_OK; } path->col = csv_file_object_parse_col(o, p); return_value_if_fail((path->col >= 0) && (path->col < csv_file_get_cols(csv)), RET_BAD_PARAMS); return_value_if_fail((path->row >= 0) && (path->row < csv_file_get_rows(csv)), RET_BAD_PARAMS); return RET_OK; } static ret_t csv_file_object_remove_map(csv_file_object_t* o, uint32_t index) { uint32_t i = 0; uint32_t n = 0; uint32_t row = 0; uint32_t* rows_map = NULL; return_value_if_fail(o != NULL, RET_BAD_PARAMS); rows_map = o->rows_map; n = o->rows_map_size; row = rows_map[index]; for (i = index; i < n - 1; i++) { rows_map[i] = rows_map[i + 1]; } o->rows_map_size--; n = o->rows_map_size; /*因为对应的row删除了,比row大的序号必须减1*/ for (i = 0; i < n; i++) { if (rows_map[i] > row) { rows_map[i] = rows_map[i] - 1; } } return RET_OK; } static ret_t csv_path_parse_ex(csv_file_object_t* o, csv_path_t* path, const char* name, bool_t for_remove) { ret_t ret = RET_BAD_PARAMS; return_value_if_fail(o != NULL && path != NULL && name != NULL, RET_BAD_PARAMS); ret = csv_path_parse_impl(o, path, name); if (ret == RET_OK) { if (o->rows_map != NULL) { uint32_t index = path->row; path->row = o->rows_map[path->row]; if (for_remove) { csv_file_object_remove_map(o, index); } } return RET_OK; } else { return ret; } } static ret_t csv_path_parse(csv_file_object_t* o, csv_path_t* path, const char* name) { return csv_path_parse_ex(o, path, name, FALSE); } static ret_t csv_file_object_remove_prop(tk_object_t* obj, const char* name) { csv_path_t p; csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); if (tk_str_start_with(name, CSV_QUERY_PREFIX)) { return tk_object_remove_prop(o->query_args, name); } return_value_if_fail(csv_path_parse_ex(o, &p, name, TRUE) == RET_OK, RET_FAIL); o->is_dirty = TRUE; return csv_file_remove_row(o->csv, p.row); } static ret_t csv_file_object_set_prop(tk_object_t* obj, const char* name, const value_t* v) { csv_path_t p; uint32_t rows = 0; csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); if (tk_str_start_with(name, CSV_QUERY_PREFIX)) { return tk_object_set_prop(o->query_args, name, v); } else if (tk_str_eq(name, CSV_PROP_COL_NAMES)) { csv_row_set_data(&(o->col_names), value_str(v), o->csv->sep); return RET_OK; } rows = csv_file_get_rows(o->csv); if (rows <= 0) { return RET_NOT_FOUND; } return_value_if_fail(csv_path_parse(o, &p, name) == RET_OK, RET_FAIL); if (p.col_name != NULL && tk_str_ieq(p.col_name, TK_OBJECT_PROP_CHECKED)) { return csv_file_set_row_checked(o->csv, p.row, value_bool(v)); } o->is_dirty = TRUE; str_from_value(&(o->str), v); return csv_file_set(o->csv, p.row, p.col, o->str.str); } static ret_t csv_file_object_get_prop(tk_object_t* obj, const char* name, value_t* v) { csv_path_t p; uint32_t rows = 0; const char* str = NULL; csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); if (tk_str_start_with(name, CSV_QUERY_PREFIX)) { return tk_object_get_prop(o->query_args, name, v); } rows = csv_file_get_rows(o->csv); if (tk_str_ieq(name, TK_OBJECT_PROP_SIZE)) { if (o->rows_map != NULL) { value_set_int(v, o->rows_map_size); } else { value_set_int(v, rows); } return RET_OK; } else if (tk_str_eq(name, TK_OBJECT_PROP_SELECTED_INDEX)) { value_set_int(v, csv_file_get_first_checked(o->csv)); return RET_OK; } if (rows <= 0) { return RET_NOT_FOUND; } return_value_if_fail(csv_path_parse(o, &p, name) == RET_OK, RET_FAIL); if (p.col_name != NULL && tk_str_ieq(p.col_name, TK_OBJECT_PROP_CHECKED)) { return_value_if_fail(p.row < rows, RET_FAIL); value_set_bool(v, csv_file_is_row_checked(o->csv, p.row)); return RET_OK; } value_set_str(v, ""); str = csv_file_get(o->csv, p.row, p.col); return_value_if_fail(str != NULL, RET_FAIL); value_set_str(v, str); return RET_OK; } static bool_t csv_file_object_can_exec(tk_object_t* obj, const char* name, const char* args) { csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); if (tk_str_ieq(name, TK_OBJECT_CMD_SAVE)) { return o->is_dirty; } else if (tk_str_ieq(name, TK_OBJECT_CMD_RELOAD)) { return TRUE; } else if (tk_str_ieq(name, TK_OBJECT_CMD_CLEAR)) { if (o->rows_map != NULL) { return o->rows_map_size > 0; } else { return csv_file_get_rows(o->csv) > 0; } } else if (tk_str_ieq(name, TK_OBJECT_CMD_REMOVE)) { if (o->rows_map != NULL) { return o->rows_map_size > 0; } else { return csv_file_get_rows(o->csv) > 0; } } else if (tk_str_ieq(name, TK_OBJECT_CMD_REMOVE_CHECKED)) { return csv_file_get_checked_rows(o->csv) > 0; } else if (tk_str_ieq(name, TK_OBJECT_CMD_ADD)) { return TRUE; } else if (tk_str_eq(name, CSV_CMD_QUERY)) { return TRUE; } return FALSE; } static ret_t csv_file_object_prepare(csv_file_object_t* o) { o->rows_map_size = 0; if (o->rows_map != NULL) { if (o->rows_map_capacity < csv_file_get_rows(o->csv)) { TKMEM_FREE(o->rows_map); o->rows_map = NULL; o->rows_map_capacity = 0; } } if (o->rows_map == NULL) { o->rows_map_capacity = csv_file_get_rows(o->csv); o->rows_map = TKMEM_ZALLOCN(uint32_t, o->rows_map_capacity); } return o->rows_map != NULL ? RET_OK : RET_OOM; } static ret_t csv_file_object_clear_query(tk_object_t* obj) { csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); o->rows_map_size = 0; TKMEM_FREE(o->rows_map); o->rows_map_capacity = 0; return RET_OK; } static ret_t csv_file_object_remove_all_query_result(tk_object_t* obj) { uint32_t i = 0; csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); for (i = o->rows_map_size; i > 0; i--) { uint32_t row = o->rows_map[i - 1]; csv_file_remove_row(o->csv, row); } o->rows_map_size = 0; return RET_OK; } static ret_t csv_file_object_query(tk_object_t* obj) { uint32_t i = 0; uint32_t n = 0; csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); return_value_if_fail(o->filter != NULL, RET_BAD_PARAMS); return_value_if_fail(csv_file_object_prepare(o) == RET_OK, RET_OOM); n = csv_file_get_rows(o->csv); for (i = 0; i < n; i++) { csv_row_t* row = csv_file_get_row(o->csv, i); ret_t ret = o->filter(o->filter_ctx, o->query_args, i, row); if (ret == RET_OK) { o->rows_map[o->rows_map_size++] = i; } else if (ret == RET_STOP) { break; } } return RET_OK; } ret_t csv_file_object_set_filter(tk_object_t* obj, csv_file_object_filter_t filter, void* ctx) { csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); o->filter = filter; o->filter_ctx = ctx; return RET_OK; } static ret_t csv_file_object_exec(tk_object_t* obj, const char* name, const char* args) { ret_t ret = RET_NOT_IMPL; csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); if (tk_str_ieq(name, TK_OBJECT_CMD_SAVE)) { if (o->is_dirty || tk_atob(args)) { o->is_dirty = FALSE; ret = csv_file_save(o->csv, NULL); emitter_dispatch_simple_event(EMITTER(obj), EVT_PROPS_CHANGED); } else { ret = RET_OK; log_debug("csv file is not dirty, need not save.\n"); } } else if (tk_str_ieq(name, TK_OBJECT_CMD_RELOAD)) { csv_file_reload(o->csv); ret = RET_ITEMS_CHANGED; csv_file_object_clear_query(obj); o->is_dirty = FALSE; } else if (tk_str_ieq(name, TK_OBJECT_CMD_CLEAR)) { if (o->rows_map != NULL) { csv_file_object_remove_all_query_result(obj); } else { csv_file_clear(o->csv); csv_file_object_clear_query(obj); } o->is_dirty = TRUE; ret = RET_ITEMS_CHANGED; } else if (tk_str_ieq(name, TK_OBJECT_CMD_REMOVE)) { o->is_dirty = TRUE; ret = csv_file_object_remove_prop(obj, args) == RET_OK ? RET_ITEMS_CHANGED : RET_FAIL; } else if (tk_str_ieq(name, TK_OBJECT_CMD_REMOVE_CHECKED)) { ret = csv_file_remove_checked_rows(o->csv) == RET_OK ? RET_ITEMS_CHANGED : RET_FAIL; csv_file_object_clear_query(obj); o->is_dirty = TRUE; } else if (tk_str_ieq(name, TK_OBJECT_CMD_ADD)) { if (args != NULL) { ret = csv_file_append_row(o->csv, args) == RET_OK ? RET_ITEMS_CHANGED : RET_FAIL; o->is_dirty = TRUE; } else { ret = RET_OK; } } else if (tk_str_eq(name, CSV_CMD_QUERY)) { if (tk_str_eq(args, CSV_CMD_QUERY_ARG_CLEAR)) { ret = csv_file_object_clear_query(obj); } else { ret = csv_file_object_query(obj); } ret = RET_ITEMS_CHANGED; } else { return RET_NOT_IMPL; } if (ret == RET_ITEMS_CHANGED) { emitter_dispatch_simple_event(EMITTER(obj), EVT_PROPS_CHANGED); emitter_dispatch_simple_event(EMITTER(obj), EVT_ITEMS_CHANGED); } return RET_OK; } static ret_t csv_file_object_destroy(tk_object_t* obj) { csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); csv_row_reset(&(o->col_names)); csv_file_destroy(o->csv); o->csv = NULL; TK_OBJECT_UNREF(o->query_args); TKMEM_FREE(o->rows_map); str_reset(&(o->str)); return RET_OK; } static const object_vtable_t s_csv_file_object_vtable = {.type = "csv_file_object", .desc = "csv_file_object", .size = sizeof(csv_file_object_t), .is_collection = TRUE, .exec = csv_file_object_exec, .can_exec = csv_file_object_can_exec, .remove_prop = csv_file_object_remove_prop, .get_prop = csv_file_object_get_prop, .set_prop = csv_file_object_set_prop, .on_destroy = csv_file_object_destroy}; csv_file_object_t* csv_file_object_cast(tk_object_t* obj) { return_value_if_fail(obj != NULL && obj->vt == &s_csv_file_object_vtable, NULL); return (csv_file_object_t*)obj; } tk_object_t* csv_file_object_create(csv_file_t* csv) { tk_object_t* obj = NULL; csv_file_object_t* o = NULL; return_value_if_fail(csv != NULL, NULL); obj = tk_object_create(&s_csv_file_object_vtable); o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, NULL); o->csv = csv; o->query_args = object_default_create_ex(FALSE); str_init(&(o->str), 0); return obj; } csv_file_t* csv_file_object_get_csv(tk_object_t* obj) { csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, NULL); return o->csv; } tk_object_t* csv_file_object_load(const char* filename, char sep) { csv_file_t* csv = csv_file_create(filename, sep); return_value_if_fail(csv != NULL, NULL); return csv_file_object_create(csv); } tk_object_t* csv_file_object_load_from_buff(const void* buff, uint32_t size, char sep) { csv_file_t* csv = NULL; if (buff != NULL) { csv = csv_file_create_with_buff(buff, size, sep); } else { csv = csv_file_create_empty(sep, NULL, NULL); } return_value_if_fail(csv != NULL, NULL); return csv_file_object_create(csv); } ret_t csv_file_object_save_to_buff(tk_object_t* obj, wbuffer_t* wb) { csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); return csv_file_save_to_buff(o->csv, wb); } ret_t csv_file_object_save_as(tk_object_t* obj, const char* filename) { csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); return csv_file_save(o->csv, filename); } csv_row_t* csv_file_object_find_first(tk_object_t* obj, tk_compare_t compare, void* ctx) { csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, NULL); return csv_file_find_first(o->csv, compare, ctx); } ret_t csv_file_object_set_check_new_row(tk_object_t* obj, csv_filter_object_check_new_row_t check_new_row, void* ctx) { csv_file_object_t* o = CSV_FILE_OBJECT(obj); return_value_if_fail(o != NULL, RET_BAD_PARAMS); o->check_new_row = check_new_row; o->check_new_row_ctx = ctx; return RET_OK; }
0
repos/awtk/src
repos/awtk/src/image_loader/image_loader_stb.h
/** * File: image_loader_stb.h * Author: AWTK Develop Team * Brief: stb image loader * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-01-21 Li XianJing <[email protected]> created * */ #ifndef TK_IMAGE_LOADER_STB_H #define TK_IMAGE_LOADER_STB_H #include "base/image_loader.h" BEGIN_C_DECLS /** * @class image_loader_stb_t * @parent image_loader_t * stb图片加载器。 * * stb主要用于加载jpg/png/gif等格式的图片,它功能强大,体积小巧。 * * @annotation["fake"] * */ /** * @method image_loader_stb * @annotation ["constructor"] * * 获取stb图片加载器对象。 * * @return {image_loader_t*} 返回图片加载器对象。 */ image_loader_t* image_loader_stb(void); /*for tool image_gen only*/ /** * @method stb_load_image * 加载图片。 * * @annotation ["static"] * @param {int32_t} subtype 资源类型。 * @param {const uint8_t*} buff 资源数据。 * @param {uint32_t} buff_size 资源数据长度。 * @param {bitmap_t*} image image 对象。 * @param {bitmap_format_t} transparent_bitmap_format 带透明通道的位图格式(只能 BITMAP_FMT_RGBA8888 和 BITMAP_FMT_RGBA8888 二选一,其他类型默认都为 BITMAP_FMT_RGBA8888) * @param {bitmap_format_t} opaque_bitmap_format 不透明位图格式(暂时支持 BITMAP_FMT_RGBA8888,BITMAP_FMT_RGBA8888,16 位色和 24 位色以及 mono 格式) * @param {lcd_orientation_t} o 旋转方向 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t stb_load_image(int32_t subtype, const uint8_t* buff, uint32_t buff_size, bitmap_t* image, bitmap_format_t transparent_bitmap_format, bitmap_format_t opaque_bitmap_format, lcd_orientation_t o); END_C_DECLS #endif /*TK_IMAGE_LOADER_STB_H*/
0
repos/awtk/src
repos/awtk/src/image_loader/image_loader_stb.c
/** * File: image_loader.h * Author: AWTK Develop Team * Brief: stb image loader * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-01-21 Li XianJing <[email protected]> created * */ #define STB_IMAGE_IMPLEMENTATION #define STBI_FREE TKMEM_FREE #define STBI_MALLOC TKMEM_ALLOC #define STBI_REALLOC(p, s) TKMEM_REALLOC(p, s) #include "tkc/mem.h" #include "base/bitmap.h" #include "stb/stb_image.h" #include "base/system_info.h" #include "image_loader/image_loader_stb.h" static uint8_t* convert_2_to_4(uint8_t* src, uint32_t w, uint32_t h) { uint32_t i = 0; uint8_t* s = src; uint8_t* d = NULL; uint8_t* data = NULL; uint32_t size = w * h; return_value_if_fail(src != NULL, NULL); data = TKMEM_ALLOC(size * 4); return_value_if_fail(data != NULL, NULL); d = data; for (i = 0; i < size; i++) { d[0] = s[0]; d[1] = s[0]; d[2] = s[0]; d[3] = s[1]; d += 4; s += 2; } return data; } static uint8_t* convert_1_to_4(uint8_t* src, uint32_t w, uint32_t h) { uint32_t i = 0; uint8_t* s = src; uint8_t* d = NULL; uint8_t* data = NULL; uint32_t size = w * h; return_value_if_fail(src != NULL, NULL); data = TKMEM_ALLOC(size * 4); return_value_if_fail(data != NULL, NULL); d = data; for (i = 0; i < size; i++) { d[0] = s[0]; d[1] = s[0]; d[2] = s[0]; d[3] = 0xFF; d += 4; s += 1; } return data; } ret_t stb_load_image(int32_t subtype, const uint8_t* buff, uint32_t buff_size, bitmap_t* image, bitmap_format_t transparent_bitmap_format, bitmap_format_t opaque_bitmap_format, lcd_orientation_t o) { int w = 0; int h = 0; int n = 0; ret_t ret = RET_FAIL; if (subtype != ASSET_TYPE_IMAGE_GIF) { uint8_t* data = NULL; int out_channel_order; uint8_t* stb_data = stbi_load_from_memory_ex(buff, buff_size, &w, &h, &n, &out_channel_order, 0); return_value_if_fail(stb_data != NULL, RET_FAIL); if (n == 2) { n = 4; data = convert_2_to_4(stb_data, w, h); } else if (n == 1) { n = 4; data = convert_1_to_4(stb_data, w, h); } else { data = stb_data; } if (opaque_bitmap_format == BITMAP_FMT_MONO) { if (out_channel_order == STBI_ORDER_RGB) { ret = bitmap_init_from_rgba(image, w, h, BITMAP_FMT_MONO, data, n, o); } else { ret = bitmap_init_from_bgra(image, w, h, BITMAP_FMT_MONO, data, n, o); } } else { if (out_channel_order == STBI_ORDER_RGB) { if (opaque_bitmap_format == BITMAP_FMT_BGR565 && rgba_data_is_opaque(data, w, h, n)) { ret = bitmap_init_from_rgba(image, w, h, BITMAP_FMT_BGR565, data, n, o); } else if (opaque_bitmap_format == BITMAP_FMT_RGB565 && rgba_data_is_opaque(data, w, h, n)) { ret = bitmap_init_from_rgba(image, w, h, BITMAP_FMT_RGB565, data, n, o); } else if (opaque_bitmap_format == BITMAP_FMT_BGR888 && rgba_data_is_opaque(data, w, h, n)) { ret = bitmap_init_from_rgba(image, w, h, BITMAP_FMT_BGR888, data, n, o); } else if (opaque_bitmap_format == BITMAP_FMT_RGB888 && rgba_data_is_opaque(data, w, h, n)) { ret = bitmap_init_from_rgba(image, w, h, BITMAP_FMT_RGB888, data, n, o); } else if (transparent_bitmap_format == BITMAP_FMT_BGRA8888) { ret = bitmap_init_from_rgba(image, w, h, BITMAP_FMT_BGRA8888, data, n, o); } else { ret = bitmap_init_from_rgba(image, w, h, BITMAP_FMT_RGBA8888, data, n, o); } } else { if (opaque_bitmap_format == BITMAP_FMT_BGR565 && rgba_data_is_opaque(data, w, h, n)) { ret = bitmap_init_from_bgra(image, w, h, BITMAP_FMT_BGR565, data, n, o); } else if (opaque_bitmap_format == BITMAP_FMT_RGB565 && rgba_data_is_opaque(data, w, h, n)) { ret = bitmap_init_from_bgra(image, w, h, BITMAP_FMT_RGB565, data, n, o); } else if (opaque_bitmap_format == BITMAP_FMT_BGR888 && rgba_data_is_opaque(data, w, h, n)) { ret = bitmap_init_from_bgra(image, w, h, BITMAP_FMT_BGR888, data, n, o); } else if (opaque_bitmap_format == BITMAP_FMT_RGB888 && rgba_data_is_opaque(data, w, h, n)) { ret = bitmap_init_from_bgra(image, w, h, BITMAP_FMT_RGB888, data, n, o); } else if (transparent_bitmap_format == BITMAP_FMT_BGRA8888) { ret = bitmap_init_from_bgra(image, w, h, BITMAP_FMT_BGRA8888, data, n, o); } else { ret = bitmap_init_from_bgra(image, w, h, BITMAP_FMT_RGBA8888, data, n, o); } } } stbi_image_free((uint8_t*)(stb_data)); if (stb_data != data) { TKMEM_FREE(data); } } else { int z = 0; int total_h = 0; int* delays = NULL; uint8_t* data = stbi_load_gif_from_memory(buff, buff_size, &delays, &w, &h, &z, &n, 0); return_value_if_fail(data != NULL, RET_FAIL); total_h = h * z; if (opaque_bitmap_format == BITMAP_FMT_MONO) { ret = bitmap_init_from_rgba(image, w, total_h, BITMAP_FMT_MONO, data, n, o); } else { if (opaque_bitmap_format == BITMAP_FMT_BGR565 && rgba_data_is_opaque(data, w, total_h, n)) { ret = bitmap_init_from_rgba(image, w, total_h, BITMAP_FMT_BGR565, data, n, o); } else if (opaque_bitmap_format == BITMAP_FMT_RGB565 && rgba_data_is_opaque(data, w, h, n)) { ret = bitmap_init_from_rgba(image, w, total_h, BITMAP_FMT_RGB565, data, n, o); } else if (opaque_bitmap_format == BITMAP_FMT_BGRA8888) { ret = bitmap_init_from_rgba(image, w, total_h, BITMAP_FMT_BGRA8888, data, n, o); } else { ret = bitmap_init_from_rgba(image, w, total_h, BITMAP_FMT_RGBA8888, data, n, o); } } image->is_gif = TRUE; image->gif_frame_h = h; image->gif_frames_nr = z; image->gif_delays = delays; stbi_image_free((uint8_t*)(data)); } return ret; } static ret_t image_loader_stb_load(image_loader_t* l, const asset_info_t* asset, bitmap_t* image) { ret_t ret = RET_OK; system_info_t* info = system_info(); lcd_orientation_t o = LCD_ORIENTATION_0; bitmap_format_t opaque_bitmap_format = BITMAP_FMT_RGBA8888; bitmap_format_t transparent_bitmap_format = BITMAP_FMT_RGBA8888; return_value_if_fail(l != NULL && image != NULL && info != NULL, RET_BAD_PARAMS); if (asset->subtype != ASSET_TYPE_IMAGE_JPG && asset->subtype != ASSET_TYPE_IMAGE_PNG && asset->subtype != ASSET_TYPE_IMAGE_GIF && asset->subtype != ASSET_TYPE_IMAGE_BMP) { return RET_NOT_IMPL; } #if !defined(WITH_GPU) && !defined(WITH_VGCANVAS_CAIRO) && defined(WITH_FAST_LCD_PORTRAIT) if (system_info()->flags & SYSTEM_INFO_FLAG_FAST_LCD_PORTRAIT) { o = info->lcd_orientation; } #endif #ifdef WITHOUT_FAST_LCD_PORTRAIT_FOR_IMAGE o = LCD_ORIENTATION_0; #endif #ifdef WITH_BITMAP_BGR565 opaque_bitmap_format = BITMAP_FMT_BGR565; #elif defined(WITH_BITMAP_RGB565) opaque_bitmap_format = BITMAP_FMT_RGB565; #elif defined(WITH_BITMAP_BGR888) opaque_bitmap_format = BITMAP_FMT_BGR888; #elif defined(WITH_BITMAP_RGB888) opaque_bitmap_format = BITMAP_FMT_RGB888; #endif /*WITH_BITMAP_RGB565*/ #ifdef WITH_BITMAP_BGRA transparent_bitmap_format = BITMAP_FMT_BGRA8888; #endif /*WITH_BITMAP_BGRA*/ #ifdef WITH_LCD_MONO opaque_bitmap_format = BITMAP_FMT_MONO; #endif ret = stb_load_image(asset->subtype, asset->data, asset->size, image, transparent_bitmap_format, opaque_bitmap_format, o); #ifdef WITH_BITMAP_PREMULTI_ALPHA if (ret == RET_OK) { ret = bitmap_premulti_alpha(image); } #endif /*WITH_BITMAP_RGB565*/ return ret; } static const image_loader_t stb_loader = {.load = image_loader_stb_load}; image_loader_t* image_loader_stb() { return (image_loader_t*)&stb_loader; }
0
repos/awtk/src
repos/awtk/src/window_manager/window_manager_default.c
/** * File: window_manager_default.c * Author: AWTK Develop Team * Brief: default window manager * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-01-13 Li XianJing <[email protected]> created * */ #include "base/keys.h" #include "tkc/mem.h" #include "base/idle.h" #include "tkc/utils.h" #include "base/timer.h" #include "base/layout.h" #include "tkc/time_now.h" #include "base/dialog.h" #include "base/locale_info.h" #include "base/system_info.h" #include "base/input_method.h" #include "base/image_manager.h" #include "base/canvas_offline.h" #include "base/dirty_rects.inc" #include "base/dialog_highlighter_factory.h" #include "window_manager/window_manager_default.h" static ret_t window_manager_animate_done(widget_t* widget); static ret_t window_manager_default_update_fps(widget_t* widget); static ret_t window_manager_invalidate_system_bar(widget_t* widget); static ret_t window_manager_default_reset_window_animator(widget_t* widget); static ret_t window_manager_default_reset_dialog_highlighter(widget_t* widget); static ret_t window_manager_default_invalidate(widget_t* widget, const rect_t* r); static ret_t window_manager_default_get_client_r(widget_t* widget, rect_t* r); static ret_t window_manager_default_do_open_window(widget_t* wm, widget_t* window); static ret_t window_manager_default_layout_child(widget_t* widget, widget_t* window); static ret_t window_manager_default_paint_always_on_top(widget_t* widget, canvas_t* c); static ret_t window_manager_default_layout_system_bar(widget_t* widget, widget_t* window); static ret_t window_manager_default_create_dialog_highlighter(widget_t* widget, widget_t* curr_win); static ret_t window_manager_default_layout_not_system_bar(widget_t* widget, widget_t* window, rect_t client_r); static bool_t window_is_opened(widget_t* widget) { int32_t stage = widget_get_prop_int(widget, WIDGET_PROP_STAGE, WINDOW_STAGE_NONE); return stage == WINDOW_STAGE_OPENED || stage == WINDOW_STAGE_SUSPEND; } static ret_t wm_on_screen_saver_timer(const timer_info_t* info) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(info->ctx); event_t e = event_init(EVT_SCREEN_SAVER, wm); wm->screen_saver_timer_id = TK_INVALID_ID; emitter_dispatch(WINDOW_MANAGER(wm)->global_emitter, &e); widget_dispatch(WIDGET(wm), &e); log_debug("emit: EVT_SCREEN_SAVER\n"); return RET_REMOVE; } static ret_t window_manager_start_or_reset_screen_saver_timer(window_manager_default_t* wm) { if (wm->screen_saver_time > 0) { if (wm->screen_saver_timer_id == TK_INVALID_ID) { wm->screen_saver_timer_id = timer_add(wm_on_screen_saver_timer, wm, wm->screen_saver_time); } else { timer_modify(wm->screen_saver_timer_id, wm->screen_saver_time); } } else { if (wm->screen_saver_timer_id != TK_INVALID_ID) { timer_remove(wm->screen_saver_timer_id); wm->screen_saver_timer_id = TK_INVALID_ID; } } return RET_OK; } static widget_t* window_manager_find_prev_window(widget_t* widget) { int32_t i = 0; int32_t nr = 0; return_value_if_fail(widget != NULL, NULL); if (widget->children != NULL && widget->children->size > 0) { nr = widget->children->size; for (i = nr - 2; i >= 0; i--) { widget_t* iter = (widget_t*)(widget->children->elms[i]); if (widget_is_normal_window(iter) || widget_is_dialog(iter) || widget_is_popup(iter) || (widget_is_overlay(iter) && !widget_is_always_on_top(iter))) { return iter; } } } return NULL; } static widget_t* window_manager_find_prev_normal_window(widget_t* widget) { return_value_if_fail(widget != NULL, NULL); if (widget->children != NULL && widget->children->size >= 2) { WIDGET_FOR_EACH_CHILD_BEGIN_R(widget, iter, i) if (i <= widget->children->size - 2 && widget_is_normal_window(iter) && iter->visible) { return iter; } WIDGET_FOR_EACH_CHILD_END(); } return NULL; } static ret_t window_manager_default_set_paint_system_bar_by_window_animator(widget_t* widget, rect_t* rect) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); WIDGET_FOR_EACH_CHILD_BEGIN_R(widget, iter, i) if (tk_str_eq(iter->vt->type, WIDGET_TYPE_SYSTEM_BAR) && !wm->is_animator_paint_system_bar_top) { rect_t r = rect_init(iter->x, iter->y, iter->w, iter->h); rect_t dr = rect_intersect(rect, &r); if (dr.w == 0 || dr.h == 0) { wm->is_animator_paint_system_bar_top = TRUE; } else if (dr.w == r.w && dr.h == r.h) { wm->is_animator_paint_system_bar_top = FALSE; } else { wm->is_animator_paint_system_bar_top = TRUE; } } else if (tk_str_eq(iter->vt->type, WIDGET_TYPE_SYSTEM_BAR_BOTTOM) && !wm->is_animator_paint_system_bar_bottom) { rect_t r = rect_init(iter->x, iter->y, iter->w, iter->h); rect_t dr = rect_intersect(rect, &r); if (dr.w == 0 || dr.h == 0) { wm->is_animator_paint_system_bar_bottom = TRUE; } else if (dr.w == r.w && dr.h == r.h) { wm->is_animator_paint_system_bar_bottom = FALSE; } else { wm->is_animator_paint_system_bar_bottom = TRUE; } } WIDGET_FOR_EACH_CHILD_END() return RET_OK; } ret_t window_manager_default_snap_curr_window(widget_t* widget, widget_t* curr_win, bitmap_t* img) { #ifndef WITHOUT_WINDOW_ANIMATORS canvas_t* c = NULL; rect_t r = {0}; canvas_t* canvas = NULL; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(img != NULL && wm != NULL && curr_win != NULL, RET_BAD_PARAMS); c = native_window_get_canvas(wm->native_window); return_value_if_fail(c != NULL && c->lcd != NULL, RET_BAD_PARAMS); window_manager_check_and_layout(widget); r = rect_init(curr_win->x, curr_win->y, curr_win->w, curr_win->h); canvas_save(c); canvas = canvas_offline_create(lcd_get_physical_width(c->lcd), lcd_get_physical_height(c->lcd), lcd_get_desired_bitmap_format(c->lcd)); canvas_offline_begin_draw(canvas); canvas_set_clip_rect(canvas, &r); ENSURE(widget_on_paint_background(widget, canvas) == RET_OK); ENSURE(widget_paint(curr_win, canvas) == RET_OK); canvas_offline_end_draw(canvas); ENSURE(canvas_offline_bitmap_move_to_new_bitmap(canvas, img) == RET_OK); ENSURE(canvas_offline_destroy(canvas) == RET_OK); window_manager_default_set_paint_system_bar_by_window_animator(widget, &r); img->flags |= BITMAP_FLAG_OPAQUE; canvas_restore(c); /* 清除在线画布的缓存,确保绘制完窗口动画后,lcd对象的数据能和在线画布同步 */ canvas_reset_cache(c); #endif return RET_OK; } #ifndef WITHOUT_WINDOW_ANIMATORS static ret_t window_manager_default_snap_prev_window_draw_dialog_highlighter_and_get_alpha( widget_t* widget, canvas_t* c, uint8_t* alpha) { value_t v; return_value_if_fail(widget != NULL && c != NULL, RET_BAD_PARAMS); if (widget_get_prop(widget, WIDGET_PROP_HIGHLIGHT, &v) == RET_OK) { const char* args = value_str(&v); if (args != NULL && *args != '\0') { dialog_highlighter_factory_t* f = dialog_highlighter_factory(); dialog_highlighter_t* dialog_highlighter = dialog_highlighter_factory_create_highlighter(f, args, widget); if (dialog_highlighter != NULL) { dialog_highlighter_draw_mask(dialog_highlighter, c, 1.0f); *alpha = dialog_highlighter_get_alpha(dialog_highlighter, 1.0f); widget_off_by_func(widget, EVT_DESTROY, dialog_highlighter_on_dialog_destroy, dialog_highlighter); dialog_highlighter_destroy(dialog_highlighter); return RET_OK; } } } return RET_FAIL; } static ret_t window_manager_default_snap_prev_window_get_system_bar_rect( widget_t* widget, slist_t* system_bar_top_list, slist_t* system_bar_bottom_list) { WIDGET_FOR_EACH_CHILD_BEGIN_R(widget, iter, i) if (iter->vt->is_window) { if (tk_str_eq(iter->vt->type, WIDGET_TYPE_SYSTEM_BAR)) { rect_t* r = rect_create(iter->x, iter->y, iter->w, iter->h); slist_append(system_bar_top_list, r); } else if (tk_str_eq(iter->vt->type, WIDGET_TYPE_SYSTEM_BAR_BOTTOM)) { rect_t* r = rect_create(iter->x, iter->y, iter->w, iter->h); slist_append(system_bar_bottom_list, r); } } WIDGET_FOR_EACH_CHILD_END() return RET_OK; } static bool_t window_manager_default_snap_prev_window_check_paint_system_bar( slist_t* diff_rect_list) { bool_t su = FALSE; rect_t* rect = NULL; slist_node_t* iter = NULL; iter = diff_rect_list->first; while (iter != NULL) { rect = (rect_t*)iter->data; if (rect->w != 0 && rect->h != 0) { su = TRUE; break; } iter = iter->next; } return su; } static ret_t window_manager_default_snap_prev_window_get_system_bar_rect_diff_on_visit( void* ctx, const void* data) { uint32_t i = 0; rect_t diff_rects[4]; void** arges = (void**)ctx; rect_t* rect = (rect_t*)data; rect_t* r = (rect_t*)arges[1]; slist_t* diff_rect_list = (slist_t*)arges[0]; if (rect_diff(rect, r, &diff_rects[0], &diff_rects[1], &diff_rects[2], &diff_rects[3])) { for (i = 0; i < ARRAY_SIZE(diff_rects); i++) { if (diff_rects[i].w != 0 && diff_rects[i].h != 0) { rect_t* data = TKMEM_ZALLOC(rect_t); break_if_fail(data != NULL); memcpy(data, &diff_rects[i], sizeof(rect_t)); slist_append(diff_rect_list, data); } } return RET_REMOVE; } return RET_OK; } static ret_t window_manager_default_snap_prev_window_get_system_bar_rect_diff(slist_t* rect_list, rect_t* r) { void* arges[2]; void* iter = NULL; slist_t diff_rect_list; slist_init(&diff_rect_list, NULL, NULL); arges[0] = &diff_rect_list; arges[1] = r; slist_foreach(rect_list, window_manager_default_snap_prev_window_get_system_bar_rect_diff_on_visit, arges); if (!slist_is_empty(&diff_rect_list)) { while ((iter = slist_head_pop(&diff_rect_list)) != NULL) { slist_append(rect_list, iter); } } slist_deinit(&diff_rect_list); return RET_OK; } static ret_t window_manager_default_snap_prev_window_system_bar_top_push_clip_rect( void* ctx, const void* data) { rect_t* r = (rect_t*)data; dialog_highlighter_t* dialog_highlighter = (dialog_highlighter_t*)ctx; dialog_highlighter_system_bar_top_append_clip_rect(dialog_highlighter, r); return RET_OK; } static ret_t window_manager_default_snap_prev_window_system_bar_bottom_push_clip_rect( void* ctx, const void* data) { rect_t* r = (rect_t*)data; dialog_highlighter_t* dialog_highlighter = (dialog_highlighter_t*)ctx; dialog_highlighter_system_bar_bottom_append_clip_rect(dialog_highlighter, r); return RET_OK; } #endif ret_t window_manager_default_snap_prev_window(widget_t* widget, widget_t* prev_win, bitmap_t* img) { #ifndef WITHOUT_WINDOW_ANIMATORS rect_t r = {0}; uint8_t alpha = 0xFF; canvas_t* c = NULL; canvas_t* canvas = NULL; int32_t end = -1, start = -1; bool_t is_fullscreen_window = FALSE; dialog_highlighter_t* dialog_highlighter = NULL; slist_t system_bar_top_rect_list, system_bar_bottom_rect_list; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); const char* curr_highlight = widget_get_prop_str(wm->curr_win, WIDGET_PROP_HIGHLIGHT, NULL); return_value_if_fail(img != NULL && wm != NULL && prev_win != NULL, RET_BAD_PARAMS); c = native_window_get_canvas(wm->native_window); return_value_if_fail(c != NULL && c->lcd != NULL, RET_BAD_PARAMS); dialog_highlighter = wm->dialog_highlighter; window_manager_check_and_layout(widget); WIDGET_FOR_EACH_CHILD_BEGIN_R(widget, iter, i) if (iter == prev_win) { start = i; end = widget->children->size - 2; break; } WIDGET_FOR_EACH_CHILD_END() is_fullscreen_window = widget_is_fullscreen_window(prev_win); r = rect_init(prev_win->x, prev_win->y, prev_win->w, prev_win->h); canvas_save(c); canvas = canvas_offline_create(lcd_get_physical_width(c->lcd), lcd_get_physical_height(c->lcd), lcd_get_desired_bitmap_format(c->lcd)); canvas_offline_begin_draw(canvas); canvas_set_clip_rect(canvas, NULL); ENSURE(widget_on_paint_background(widget, canvas) == RET_OK); if (!is_fullscreen_window) { window_manager_paint_system_bar(widget, canvas); } { widget_t** children = (widget_t**)(widget->children->elms); slist_init(&system_bar_top_rect_list, default_destroy, NULL); slist_init(&system_bar_bottom_rect_list, default_destroy, NULL); if (!is_fullscreen_window) { window_manager_default_snap_prev_window_get_system_bar_rect(widget, &system_bar_top_rect_list, &system_bar_bottom_rect_list); } for (; start <= end; ++start) { widget_t* iter = children[start]; if (widget_is_system_bar(iter) || !iter->visible) continue; /* 过滤 curr_win 的对象 */ if (iter != wm->curr_win) { rect_t iter_rect = rect_init(iter->x, iter->y, iter->w, iter->h); /* 给前面的高亮对话框叠加黑色色块 */ if (widget_is_support_highlighter(iter)) { uint8_t a = 0x0; if (window_manager_default_snap_prev_window_draw_dialog_highlighter_and_get_alpha( iter, canvas, &a) == RET_OK) { /* 计算最终叠加后的透明度值 */ alpha = alpha * (1 - a / 255.0f); } } /* 如果不是全屏的话,就削减 system_bar 的显示裁剪区 */ if (!is_fullscreen_window && !widget_is_normal_window(iter)) { window_manager_default_snap_prev_window_get_system_bar_rect_diff( &system_bar_top_rect_list, &iter_rect); window_manager_default_snap_prev_window_get_system_bar_rect_diff( &system_bar_bottom_rect_list, &iter_rect); } rect_merge(&r, &iter_rect); ENSURE(widget_paint(iter, canvas) == RET_OK); } } /* 检查是否还有 system_bar 的显示区域,如果有则让其绘图 */ wm->is_animator_paint_system_bar_top = window_manager_default_snap_prev_window_check_paint_system_bar(&system_bar_top_rect_list); wm->is_animator_paint_system_bar_bottom = window_manager_default_snap_prev_window_check_paint_system_bar( &system_bar_bottom_rect_list); } if (dialog_highlighter != NULL) { dialog_highlighter_set_bg_clip_rect(dialog_highlighter, &r); if (!is_fullscreen_window) { /* 把 system_bar 的显示裁剪区域追加到高亮对象中 */ slist_foreach(&system_bar_top_rect_list, window_manager_default_snap_prev_window_system_bar_top_push_clip_rect, dialog_highlighter); slist_foreach(&system_bar_bottom_rect_list, window_manager_default_snap_prev_window_system_bar_bottom_push_clip_rect, dialog_highlighter); } if (curr_highlight != NULL) { dialog_highlighter_set_system_bar_alpha(dialog_highlighter, 0xFF - alpha); dialog_highlighter_set_win(dialog_highlighter, prev_win); /* 把没有遮罩的 system_bar 绘制到离线画布上 */ dialog_highlighter_prepare_ex(dialog_highlighter, c, canvas); } } canvas_offline_end_draw(canvas); ENSURE(canvas_offline_bitmap_move_to_new_bitmap(canvas, img) == RET_OK); ENSURE(canvas_offline_destroy(canvas) == RET_OK); img->flags |= BITMAP_FLAG_OPAQUE; canvas_restore(c); if (dialog_highlighter != NULL) { dialog_highlighter_set_bg(dialog_highlighter, img); } slist_deinit(&system_bar_top_rect_list); slist_deinit(&system_bar_bottom_rect_list); wm->last_curr_win = wm->curr_win; wm->curr_win = NULL; #endif return RET_OK; } static ret_t window_manager_on_highlighter_destroy(void* ctx, event_t* e) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(ctx); if (wm->dialog_highlighter == e->target) { wm->dialog_highlighter = NULL; } return RET_OK; } static dialog_highlighter_t* window_manager_default_get_dialog_highlighter(widget_t* widget) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return wm->dialog_highlighter; } static ret_t window_manager_default_dialog_highlighter_destroy(widget_t* widget) { dialog_highlighter_t* dialog_highlighter = NULL; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); dialog_highlighter = wm->dialog_highlighter; if (dialog_highlighter != NULL) { widget_t* dialog = dialog_highlighter->dialog; if (dialog != NULL) { widget_off_by_func(dialog, EVT_DESTROY, dialog_highlighter_on_dialog_destroy, dialog_highlighter); } dialog_highlighter_destroy(dialog_highlighter); wm->dialog_highlighter = NULL; } return RET_OK; } static ret_t window_manager_default_create_dialog_highlighter(widget_t* widget, widget_t* curr_win) { ret_t ret = RET_FAIL; dialog_highlighter_t* dialog_highlighter = NULL; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); const char* curr_highlight = widget_get_prop_str(curr_win, WIDGET_PROP_HIGHLIGHT, NULL); dialog_highlighter = wm->dialog_highlighter; if (dialog_highlighter != NULL && curr_highlight != NULL && (dialog_highlighter->dialog != curr_win || dialog_highlighter->used_by_others)) { /* dialog_highlighter被其他窗口使用过,需重新生成 */ window_manager_default_dialog_highlighter_destroy(widget); dialog_highlighter = NULL; } if (dialog_highlighter == NULL && widget_is_support_highlighter(curr_win) && curr_highlight != NULL && *curr_highlight != '\0') { dialog_highlighter_factory_t* f = dialog_highlighter_factory(); dialog_highlighter = dialog_highlighter_factory_create_highlighter(f, curr_highlight, curr_win); if (dialog_highlighter != NULL) { wm->dialog_highlighter = dialog_highlighter; emitter_on(EMITTER(dialog_highlighter), EVT_DESTROY, window_manager_on_highlighter_destroy, widget); ret = RET_OK; } } /* 把 dialog_highlighter 给键盘窗口使用 */ if (dialog_highlighter != NULL && widget_is_keyboard(curr_win)) { dialog_highlighter->used_by_others = TRUE; } else if (dialog_highlighter != NULL && !widget_has_highlighter(curr_win)) { /* 把 dialog_highlighter 给自身没高亮且支持高亮的窗口使用 */ if (widget_is_support_highlighter(curr_win)) { dialog_highlighter->used_by_others = TRUE; } else { /* 因为当支持高亮的窗口销毁的时候会释放 dialog_highlighter 局部, 防止不支持高亮的窗口使用 dialog_highlighter 高亮贴图。 */ wm->dialog_highlighter = NULL; } } return ret; } static ret_t window_manager_prepare_dialog_highlighter(widget_t* widget, widget_t* prev_win, widget_t* curr_win) { if (window_manager_default_create_dialog_highlighter(widget, curr_win) == RET_OK) { bitmap_t img = {0}; ret_t ret = window_manager_default_snap_prev_window(widget, prev_win, &img); if (ret != RET_OK) { window_manager_default_dialog_highlighter_destroy(widget); } return ret; } return RET_FAIL; } static ret_t window_manager_create_highlighter(widget_t* widget, widget_t* curr_win) { widget_t* prev_win = window_manager_find_prev_normal_window(widget); window_manager_prepare_dialog_highlighter(widget, prev_win, curr_win); return RET_OK; } static bool_t window_manager_curr_win_is_top_animator_window(widget_t* wm, widget_t* curr_win) { bool_t is_find = FALSE; WIDGET_FOR_EACH_CHILD_BEGIN_R(wm, iter, i) if (widget_is_normal_window(iter) && !is_find && curr_win != iter) { return FALSE; } if (iter == curr_win) { is_find = TRUE; break; } WIDGET_FOR_EACH_CHILD_END() return TRUE; } static ret_t window_manager_create_animator(window_manager_default_t* wm, widget_t* curr_win, bool_t open) { value_t v; const char* anim_hint = NULL; widget_t* prev_win = window_manager_find_prev_normal_window(WIDGET(wm)); const char* key = open ? WIDGET_PROP_OPEN_ANIM_HINT : WIDGET_PROP_CLOSE_ANIM_HINT; if (prev_win == curr_win || prev_win == NULL) { return RET_FAIL; } return_value_if_fail(wm != NULL && prev_win != NULL && curr_win != NULL, RET_BAD_PARAMS); if (wm->animator != NULL || !window_manager_curr_win_is_top_animator_window(WIDGET(wm), curr_win)) { return RET_FAIL; } if (widget_get_prop(curr_win, key, &v) == RET_OK) { anim_hint = value_str(&(v)); } else { key = WIDGET_PROP_ANIM_HINT; if (widget_get_prop(curr_win, key, &v) == RET_OK) { anim_hint = value_str(&(v)); } } wm->is_animator_paint_system_bar_top = FALSE; wm->is_animator_paint_system_bar_bottom = FALSE; if (anim_hint && *anim_hint) { canvas_t* c = native_window_get_canvas(wm->native_window); window_manager_default_create_dialog_highlighter(WIDGET(wm), curr_win); wm->curr_win = curr_win; if (open) { wm->animator = window_animator_create_for_open(anim_hint, c, prev_win, curr_win); } else { wm->animator = window_animator_create_for_close(anim_hint, c, prev_win, curr_win); } wm->animating = wm->animator != NULL; if (wm->animating) { wm->animator->is_paint_system_bar_top = wm->is_animator_paint_system_bar_top; wm->animator->is_paint_system_bar_bottom = wm->is_animator_paint_system_bar_bottom; wm->ignore_user_input = TRUE; log_debug("ignore_user_input\n"); } } else { /* 动画播放完毕后刷新wm,避免出现高亮残留 */ widget_invalidate_force(WIDGET(wm), NULL); if (widget_get_prop(curr_win, WIDGET_PROP_HIGHLIGHT, &v) == RET_OK) { wm->curr_win = curr_win; window_manager_invalidate_system_bar(WIDGET(wm)); window_manager_prepare_dialog_highlighter(WIDGET(wm), prev_win, curr_win); } } return wm->animating ? RET_OK : RET_FAIL; } static ret_t on_idle_invalidate(const timer_info_t* info) { widget_t* curr_win = WIDGET(info->ctx); widget_invalidate_force(curr_win, NULL); return RET_REMOVE; } static ret_t window_manager_check_if_need_open_animation(const idle_info_t* info) { widget_t* curr_win = WIDGET(info->ctx); window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(curr_win->parent); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); if (wm->dialog_highlighter != NULL && widget_is_normal_window(curr_win)) { window_manager_default_dialog_highlighter_destroy(WIDGET(wm)); } window_manager_dispatch_window_event(curr_win, EVT_WINDOW_WILL_OPEN); wm->ready_animator = FALSE; if (window_manager_create_animator(wm, curr_win, TRUE) != RET_OK) { widget_t* prev_win = window_manager_find_prev_window(WIDGET(wm)); if (prev_win != NULL) { if (!widget_is_keyboard(curr_win) && !widget_is_overlay(curr_win)) { window_manager_dispatch_window_event(prev_win, EVT_WINDOW_TO_BACKGROUND); } } window_manager_dispatch_window_event(curr_win, EVT_WINDOW_OPEN); widget_add_timer(curr_win, on_idle_invalidate, 100); } return RET_REMOVE; } static ret_t on_window_switch_done(void* ctx, event_t* e) { widget_t* to_close = WIDGET(ctx); log_debug("window %s close\n", to_close->name); window_manager_close_window_force(to_close->parent, to_close); return RET_REMOVE; } static ret_t window_manager_default_switch_to(widget_t* widget, widget_t* curr_win, widget_t* target_win, bool_t close) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(curr_win != NULL && target_win != NULL && wm != NULL, RET_BAD_PARAMS); wm->ready_animator = FALSE; widget_restack(target_win, 0xffffff); if (close) { widget_on(target_win, EVT_WINDOW_TO_FOREGROUND, on_window_switch_done, curr_win); } if (window_manager_create_animator(wm, target_win, TRUE) != RET_OK) { window_manager_dispatch_window_event(curr_win, EVT_WINDOW_TO_BACKGROUND); window_manager_dispatch_window_event(target_win, EVT_WINDOW_TO_FOREGROUND); widget_invalidate_force(target_win, NULL); } return RET_OK; } static ret_t window_manager_dispatch_window_open(widget_t* curr_win) { window_manager_dispatch_window_event(curr_win, EVT_WINDOW_WILL_OPEN); return window_manager_dispatch_window_event(curr_win, EVT_WINDOW_OPEN); } static ret_t window_manager_idle_dispatch_window_open(const idle_info_t* info) { widget_t* curr_win = WIDGET(info->ctx); window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(curr_win->parent); if (wm != NULL) { wm->ready_animator = FALSE; window_manager_dispatch_window_open(curr_win); } return RET_REMOVE; } static ret_t window_manager_check_if_need_close_animation(window_manager_default_t* wm, widget_t* curr_win) { return window_manager_create_animator(wm, curr_win, FALSE); } static ret_t window_manager_default_do_open_window(widget_t* widget, widget_t* window) { if (widget->children != NULL && widget->children->size > 0) { widget_add_idle(window, (idle_func_t)window_manager_check_if_need_open_animation); } else { widget_add_idle(window, (idle_func_t)window_manager_idle_dispatch_window_open); } return RET_OK; } static ret_t wm_on_destroy_child(void* ctx, event_t* e) { widget_t* widget = WIDGET(ctx); (void)e; if (!widget->destroying) { window_manager_dispatch_top_window_changed(widget); } return RET_REMOVE; } static ret_t window_manager_default_open_window(widget_t* widget, widget_t* window) { ret_t ret = RET_OK; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(widget != NULL && window != NULL, RET_BAD_PARAMS); wm->prev_win = window_manager_get_top_window(widget); if (wm->animator != NULL) { wm->pending_open_window = window; } else { wm->ready_animator = TRUE; window_manager_default_do_open_window(widget, window); } ret = widget_add_child(widget, window); return_value_if_fail(ret == RET_OK, RET_FAIL); window_manager_default_layout_child(widget, window); window->dirty = FALSE; widget->target = window; widget_invalidate(window, NULL); widget_set_prop_pointer(window, WIDGET_PROP_NATIVE_WINDOW, wm->native_window); widget_on(window, EVT_DESTROY, wm_on_destroy_child, widget); widget_update_style(widget); return ret; } static ret_t window_manager_idle_destroy_window(const idle_info_t* info) { widget_t* win = WIDGET(info->ctx); widget_destroy(win); return RET_OK; } static ret_t window_manager_prepare_close_window(widget_t* widget, widget_t* window) { return_value_if_fail(widget != NULL && window != NULL, RET_BAD_PARAMS); if (widget->target == window) { widget->target = NULL; } if (widget->key_target == window) { widget->key_target = NULL; } if (widget->grab_widget != NULL) { if (widget->grab_widget == window) { widget->grab_widget = NULL; } } return RET_OK; } static ret_t window_manager_default_on_idle_check_and_close_window(const idle_info_t* idle) { widget_t* win = WIDGET(idle->ctx); window_manager_close_window_force(window_manager(), win); return RET_REMOVE; } static ret_t window_manager_default_close_window(widget_t* widget, widget_t* window) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); return_value_if_fail(widget_is_window(window), RET_BAD_PARAMS); if (!window_is_opened(window)) { uint32_t idle_id = widget_get_prop_int(window, "check_and_close_window_idle_id", 0); if (idle_id == 0) { idle_id = widget_add_idle(window, window_manager_default_on_idle_check_and_close_window); widget_set_prop_int(window, "check_and_close_window_idle_id", idle_id); } return RET_OK; } return_value_if_fail(wm->pending_close_window != window, RET_BAD_PARAMS); window_manager_prepare_close_window(widget, window); if (wm->animator) { if (widget_is_keyboard(window)) { input_method_t* im = input_method(); if (im != NULL) { widget_t* win = widget_get_window(im->widget); if (win == wm->animator->prev_win && widget_is_normal_window(wm->animator->curr_win)) { /* 如果已经打开下一个窗口后,就直接释放上一个窗口的软键盘,不必播放软键盘的动画 */ window_manager_close_window_force(window->parent, window); return RET_OK; } } } wm->pending_close_window = window; return RET_OK; } window_manager_dispatch_window_event(window, EVT_WINDOW_CLOSE); if (window_manager_check_if_need_close_animation(wm, window) != RET_OK) { widget_t* prev_win = NULL; widget_remove_child(widget, window); idle_add(window_manager_idle_destroy_window, window); if (wm->dialog_highlighter != NULL && wm->dialog_highlighter->dialog == window) { window_manager_default_dialog_highlighter_destroy(widget); } /* 这里是解决没有结束动画,但是 prev_win 是高亮的对话框的情况 */ prev_win = window_manager_get_top_window(widget); if (widget_is_keyboard(prev_win)) { input_method_t* im = input_method(); if (im != NULL) { if (im->keyboard != NULL && im->keyboard == prev_win) { prev_win = widget_get_window(im->widget); } } } if (prev_win != NULL) { if (!widget_is_keyboard(window)) { bool_t is_create = TRUE; const char* curr_highlight = NULL; widget_t* widget_highlighter = prev_win; wm->curr_win = prev_win; window_manager_dispatch_window_event(prev_win, EVT_WINDOW_TO_FOREGROUND); WIDGET_FOR_EACH_CHILD_BEGIN_R(widget, iter, i) if (widget_is_normal_window(iter)) { break; } if (widget_is_support_highlighter(iter)) { curr_highlight = widget_get_prop_str(iter, WIDGET_PROP_HIGHLIGHT, NULL); if (curr_highlight != NULL && *curr_highlight != '\0') { widget_highlighter = iter; break; } } WIDGET_FOR_EACH_CHILD_END(); if (is_create) { wm->curr_win = widget_highlighter; window_manager_create_highlighter(widget, widget_highlighter); wm->curr_win = prev_win; } } } } if (widget->children == NULL || widget->children->size == 0) { widget_invalidate_force(widget, NULL); } return RET_OK; } static ret_t window_manager_default_close_window_force(widget_t* widget, widget_t* window) { ret_t ret = RET_OK; bool_t close_window = TRUE; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); return_value_if_fail(widget_is_window(window), RET_BAD_PARAMS); return_value_if_fail(wm->pending_close_window != window, RET_BAD_PARAMS); if (wm->animator != NULL) { bool_t is_open = wm->animator->open; bool_t curr_is_target = wm->animator->curr_win == window; if (curr_is_target || curr_is_target) { ret = window_manager_animate_done(widget); close_window = FALSE; } if (curr_is_target && is_open) { close_window = TRUE; } } if (close_window) { window_manager_prepare_close_window(widget, window); window_manager_dispatch_window_event(window, EVT_WINDOW_CLOSE); widget_remove_child(widget, window); widget_destroy(window); } return ret; } static widget_t* window_manager_default_find_target(widget_t* widget, xy_t x, xy_t y) { return window_manager_find_target(widget, NULL, x, y); } static ret_t window_manager_paint_cursor(widget_t* widget, canvas_t* c) { bitmap_t bitmap; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); if (wm->r_cursor.w > 0 && wm->r_cursor.h > 0) { return_value_if_fail(image_manager_get_bitmap(image_manager(), wm->cursor, &bitmap) == RET_OK, RET_BAD_PARAMS); canvas_draw_icon(c, &bitmap, wm->r_cursor.x, wm->r_cursor.y); } return RET_OK; } static ret_t window_manager_update_cursor(widget_t* widget, int32_t x, int32_t y) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); uint32_t w = wm->r_cursor.w; uint32_t h = wm->r_cursor.h; if (w > 0 && h > 0) { uint32_t hw = w >> 1; uint32_t hh = h >> 1; int32_t oldx = wm->r_cursor.x; int32_t oldy = wm->r_cursor.y; rect_t r = rect_init(oldx - hw, oldy - hh, w, h); window_manager_default_invalidate(widget, &r); wm->r_cursor.x = x; wm->r_cursor.y = y; r = rect_init(x - hw, y - hh, w, h); window_manager_default_invalidate(widget, &r); } return RET_OK; } static ret_t window_manager_paint_normal(widget_t* widget, canvas_t* c) { #ifdef FRAGMENT_FRAME_BUFFER_SIZE uint32_t i = 0; uint32_t y = 0; uint32_t h = 0; uint32_t tmp_h = 0; uint32_t number = 0; #endif uint64_t start_time = time_now_ms(); window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); if (WINDOW_MANAGER(wm)->max_fps) { uint32_t duration = 1000 / WINDOW_MANAGER(wm)->max_fps; uint32_t elapsed_time = start_time - wm->last_paint_time + wm->last_paint_cost; /* * 上一帧的绘图耗时加上各种事件触发耗时小于绘图间隔时间,则跳过绘图并且控制睡眠时间。 * 控制睡眠时间是为了防止睡眠时间过长导致减低绘图次数。 */ if (elapsed_time < duration) { window_manager_set_curr_expected_sleep_time(widget, duration - elapsed_time); return RET_OK; } } fps_inc(&(wm->fps)); if (WINDOW_MANAGER(wm)->show_fps) { rect_t fps_rect = rect_init(WINDOW_MANAGER(wm)->fps_position.x, WINDOW_MANAGER(wm)->fps_position.y, 60, 30); window_manager_default_invalidate(widget, &fps_rect); } #ifdef FRAGMENT_FRAME_BUFFER_SIZE if (wm->native_window->dirty_rects.max.w > 0 && wm->native_window->dirty_rects.max.h > 0) { rect_t r = native_window_calc_dirty_rect(wm->native_window); if (r.w > 0 && r.h > 0) { assert(r.w <= FRAGMENT_FRAME_BUFFER_SIZE); y = r.y; h = r.h; tmp_h = FRAGMENT_FRAME_BUFFER_SIZE / r.w; number = r.h / tmp_h; for (i = 0; i <= number; i++) { dirty_rects_t tmp_dirty_rects; r.y = y + i * tmp_h; if (i == number) { tmp_h = h % tmp_h; } r.h = tmp_h; if (r.h == 0) { break; } dirty_rects_init(&(tmp_dirty_rects)); dirty_rects_add(&(tmp_dirty_rects), (const rect_t*)&r); canvas_t* c = native_window_get_canvas(wm->native_window); canvas_begin_frame(c, (const dirty_rects_t*)&tmp_dirty_rects, LCD_DRAW_NORMAL); widget_paint(WIDGET(wm), c); window_manager_paint_cursor(widget, c); canvas_end_frame(c); dirty_rects_deinit(&(tmp_dirty_rects)); } native_window_update_last_dirty_rect(wm->native_window); } native_window_clear_dirty_rect(wm->native_window); } #else if (native_window_begin_frame(wm->native_window, LCD_DRAW_NORMAL) == RET_OK) { if (widget->children == NULL || widget->children->size == 0) { color_t bg = color_init(0xff, 0xff, 0xff, 0xff); canvas_set_fill_color(c, bg); canvas_fill_rect(c, 0, 0, widget->w, widget->h); } else { /* * 获取当前帧的脏矩形列表和 fb 的脏矩形列表合并后的新的脏矩形列表, * 如果没有 fb 的脏矩形列表的话,会退化为获取当前帧的脏矩形。 */ dirty_rects_t* dirty_rects = (dirty_rects_t*)lcd_get_dirty_rects(c->lcd); if (dirty_rects == NULL && !lcd_is_support_dirty_rect(c->lcd)) { dirty_rects = &(wm->native_window->dirty_rects); } dirty_rects_paint(dirty_rects, WIDGET(wm), c, widget_paint); } window_manager_paint_cursor(widget, c); native_window_end_frame(wm->native_window); } #endif wm->last_paint_time = time_now_ms(); wm->last_paint_cost = wm->last_paint_time - start_time; return RET_OK; } static ret_t window_manager_invalidate_system_bar(widget_t* widget) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); WIDGET_FOR_EACH_CHILD_BEGIN_R(widget, iter, i) if (widget_is_system_bar(iter)) { widget_invalidate_force(iter, NULL); } WIDGET_FOR_EACH_CHILD_END() return RET_OK; } #ifndef WITHOUT_WINDOW_ANIMATORS static ret_t window_manager_animate_done_set_window_foreground(widget_t* widget, widget_t* prev_win, widget_t* curr_win) { bool_t is_set = FALSE; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); WIDGET_FOR_EACH_CHILD_BEGIN(widget, iter, i) if (prev_win == iter) { is_set = TRUE; } else if (curr_win == iter) { is_set = FALSE; } if (is_set && (widget_is_normal_window(iter) || i + 1 == widget->children->size)) { window_manager_dispatch_window_event(iter, EVT_WINDOW_TO_FOREGROUND); } WIDGET_FOR_EACH_CHILD_END() return RET_OK; } static bool_t window_manager_default_is_dialog_highlighter(widget_t* widget) { value_t v; return_value_if_fail(widget != NULL, FALSE); if (widget_is_support_highlighter(widget) && widget_get_prop(widget, WIDGET_PROP_HIGHLIGHT, &v) == RET_OK) { return TRUE; } return FALSE; } static widget_t* window_manager_default_find_top_dialog_highlighter(widget_t* widget, widget_t* prev_win, widget_t* curr_win) { int32_t i = 0; widget_t* dialog = NULL; widget_t** children = (widget_t**)(widget->children->elms); i = widget->children->size - 1; for (; i >= 0; i--) { widget_t* iter = children[i]; if (iter == prev_win) { break; } if (iter == curr_win) { continue; } if (window_manager_default_is_dialog_highlighter(iter)) { dialog = iter; break; } } return dialog; } static ret_t window_manager_animate_done(widget_t* widget) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); if (wm->animator != NULL) { bool_t is_open = wm->animator->open; widget_t* top_dialog_highligth = NULL; widget_t* prev_win = wm->animator->prev_win; widget_t* curr_win = wm->animator->curr_win; window_animator_destroy(wm->animator); bool_t curr_win_is_keyboard = widget_is_keyboard(curr_win); bool_t curr_win_is_normal_window = widget_is_normal_window(curr_win); wm->animator = NULL; wm->animating = FALSE; wm->ignore_user_input = FALSE; if (is_open) { /*此时前一个窗口并非是真正的前一个窗口,而是前一个normal窗口,所以这里重新找真正的前一个窗口*/ prev_win = window_manager_find_prev_window(WIDGET(wm)); /* 结束打开窗口动画后 */ if (!curr_win_is_keyboard && prev_win != curr_win) { window_manager_dispatch_window_event(prev_win, EVT_WINDOW_TO_BACKGROUND); } if (!curr_win_is_normal_window) { top_dialog_highligth = window_manager_default_find_top_dialog_highlighter( widget, prev_win, curr_win_is_keyboard ? curr_win : NULL); } if (widget_is_window_opened(curr_win)) { //for swtich to window_manager_dispatch_window_event(curr_win, EVT_WINDOW_TO_FOREGROUND); } else { window_manager_dispatch_window_event(curr_win, EVT_WINDOW_OPEN); } } else { /* 结束关闭窗口动画后 */ if (!curr_win_is_keyboard) { window_manager_animate_done_set_window_foreground(widget, prev_win, curr_win); } top_dialog_highligth = window_manager_default_find_top_dialog_highlighter(widget, prev_win, curr_win); } /* 制作一张没有最后一个对话框的高亮背景贴图 */ if (top_dialog_highligth != NULL) { widget_t* tmp_curr_win = wm->curr_win; wm->curr_win = top_dialog_highligth; window_manager_create_highlighter(widget, top_dialog_highligth); wm->curr_win = tmp_curr_win; } if (wm->pending_close_window != NULL) { widget_t* window = wm->pending_close_window; wm->pending_close_window = NULL; if (wm->pending_open_window != NULL) { window_manager_close_window_force(widget, window); } else { window_manager_close_window(widget, window); } } if (wm->pending_open_window != NULL) { widget_t* window = wm->pending_open_window; wm->pending_open_window = NULL; window_manager_default_do_open_window(widget, window); } /* 动画播放完毕后刷新wm,避免出现高亮残留 */ widget_invalidate_force(widget, NULL); } return RET_OK; } static ret_t window_manager_paint_animation(widget_t* widget, canvas_t* c) { paint_event_t e; uint64_t start_time = time_now_ms(); window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); ENSURE(window_animator_begin_frame(wm->animator) == RET_OK); widget_dispatch(widget, paint_event_init(&e, EVT_BEFORE_PAINT, widget, c)); ret_t ret = window_animator_update(wm->animator, start_time); window_manager_default_paint_always_on_top(widget, c); widget_dispatch(widget, paint_event_init(&e, EVT_AFTER_PAINT, widget, c)); ENSURE(window_animator_end_frame(wm->animator) == RET_OK); wm->last_paint_cost = time_now_ms() - start_time; fps_inc(&(wm->fps)); if (ret == RET_DONE) { window_manager_animate_done(widget); } return RET_OK; } #else static ret_t window_manager_animate_done(widget_t* widget) { return RET_OK; } #endif /*WITHOUT_WINDOW_ANIMATORS*/ static ret_t window_manager_default_update_fps(widget_t* widget) { canvas_t* c = NULL; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); c = native_window_get_canvas(wm->native_window); canvas_set_fps_ex(c, WINDOW_MANAGER(wm)->show_fps, fps_get(&(wm->fps)), wm->window_manager.fps_position.x, wm->window_manager.fps_position.y); return RET_OK; } static ret_t window_manager_default_paint(widget_t* widget) { ret_t ret = RET_OK; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); canvas_t* c = native_window_get_canvas(wm->native_window); return_value_if_fail(wm != NULL && c != NULL, RET_BAD_PARAMS); canvas_set_global_alpha(c, 0xff); window_manager_default_update_fps(widget); window_manager_set_curr_expected_sleep_time(widget, 0xFFFFFFFF); #ifndef WITHOUT_WINDOW_ANIMATORS if (wm->animator != NULL) { ret = window_manager_paint_animation(widget, c); } else if (!wm->ready_animator) { ret = window_manager_paint_normal(widget, c); } #else ret = window_manager_paint_normal(widget, c); #endif /*WITHOUT_WINDOW_ANIMATORS*/ return ret; } static ret_t window_manager_default_invalidate(widget_t* widget, const rect_t* r) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); if (wm->native_window != NULL) { native_window_invalidate(wm->native_window, r); } return RET_OK; } static widget_t* window_manager_default_get_prev_window(widget_t* widget) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return wm->prev_win; } static ret_t window_manager_default_paint_always_on_top(widget_t* widget, canvas_t* c) { WIDGET_FOR_EACH_CHILD_BEGIN(widget, iter, i) if (iter->visible) { if (widget_get_prop_bool(iter, WIDGET_PROP_ALWAYS_ON_TOP, FALSE)) { widget_paint(iter, c); } } WIDGET_FOR_EACH_CHILD_END() return RET_OK; } static ret_t window_manager_default_on_paint_children(widget_t* widget, canvas_t* c) { int32_t start = 0; bool_t cover_highlighter = FALSE; bool_t has_fullscreen_win = FALSE; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(widget != NULL && c != NULL, RET_BAD_PARAMS); WIDGET_FOR_EACH_CHILD_BEGIN_R(widget, iter, i) if (wm->dialog_highlighter != NULL && wm->dialog_highlighter->dialog == iter) { start = i; break; } else if (iter->visible && widget_is_normal_window(iter)) { start = i; cover_highlighter = TRUE; break; } WIDGET_FOR_EACH_CHILD_END() if (!cover_highlighter && wm->dialog_highlighter != NULL) { dialog_highlighter_draw(wm->dialog_highlighter, 1); } else { /*paint normal windows*/ WIDGET_FOR_EACH_CHILD_BEGIN(widget, iter, i) if (i >= start && iter->visible) { if (widget_is_normal_window(iter)) { widget_paint(iter, c); if (!has_fullscreen_win) { has_fullscreen_win = widget_is_fullscreen_window(iter); } start = i + 1; break; } } WIDGET_FOR_EACH_CHILD_END() /*paint system_bar*/ if (!has_fullscreen_win) { window_manager_paint_system_bar(widget, c); } } /*paint dialog and other*/ WIDGET_FOR_EACH_CHILD_BEGIN(widget, iter, i) if (i >= start && iter->visible) { if ((!widget_is_system_bar(iter) && !widget_is_normal_window(iter)) || (wm->dialog_highlighter != NULL && wm->dialog_highlighter->dialog != NULL && widget_is_normal_window(iter))) { widget_paint(iter, c); } } WIDGET_FOR_EACH_CHILD_END() window_manager_default_paint_always_on_top(widget, c); return RET_OK; } static ret_t window_manager_default_on_remove_child(widget_t* widget, widget_t* window) { widget_t* top = window_manager_get_top_main_window(widget); if (top != NULL) { rect_t r; r = rect_init(window->x, window->y, window->w, window->h); widget_invalidate(top, &r); } if (widget->destroying) { widget_off_by_ctx(window, widget); } return RET_FAIL; } static ret_t window_manager_default_get_prop(widget_t* widget, const char* name, value_t* v) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(widget != NULL && name != NULL && v != NULL, RET_BAD_PARAMS); if (tk_str_eq(name, WIDGET_PROP_POINTER_CURSOR)) { value_set_str(v, wm->cursor); return RET_OK; } else if (tk_str_eq(name, WIDGET_PROP_CANVAS)) { canvas_t* c = native_window_get_canvas(wm->native_window); value_set_pointer(v, c); return RET_OK; } else if (tk_str_eq(name, WIDGET_PROP_CURR_WIN)) { value_set_pointer(v, wm->curr_win); return RET_OK; } else if (tk_str_eq(name, WIDGET_PROP_SCREEN_SAVER_TIME)) { value_set_uint32(v, wm->screen_saver_time); return RET_OK; } else if (tk_str_eq(name, WIDGET_PROP_SHOW_FPS)) { value_set_bool(v, WINDOW_MANAGER(wm)->show_fps); return RET_OK; } else if (tk_str_eq(name, WIDGET_PROP_MAX_FPS)) { value_set_uint32(v, WINDOW_MANAGER(wm)->max_fps); return RET_OK; } return RET_NOT_FOUND; } static ret_t window_manager_default_set_prop(widget_t* widget, const char* name, const value_t* v) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(widget != NULL && name != NULL && v != NULL, RET_BAD_PARAMS); if (tk_str_eq(name, WIDGET_PROP_POINTER_CURSOR)) { return window_manager_set_cursor(widget, value_str(v)); } else if (tk_str_eq(name, WIDGET_PROP_CURR_WIN)) { wm->curr_win = value_pointer(v); return RET_OK; } else if (tk_str_eq(name, WIDGET_PROP_SCREEN_SAVER_TIME)) { return window_manager_set_screen_saver_time(widget, value_uint32(v)); } else if (tk_str_eq(name, WIDGET_PROP_SHOW_FPS)) { return window_manager_set_show_fps(widget, value_bool(v)); } else if (tk_str_eq(name, WIDGET_PROP_MAX_FPS)) { return window_manager_set_max_fps(widget, value_uint32(v)); } return RET_NOT_FOUND; } static ret_t window_manager_default_on_destroy(widget_t* widget) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); #ifndef WITHOUT_WINDOW_ANIMATORS if (wm->animator != NULL) { wm->animator->prev_win = NULL; wm->animator->curr_win = NULL; window_animator_destroy(wm->animator); wm->animator = NULL; } #endif /*WITHOUT_WINDOW_ANIMATORS*/ TK_OBJECT_UNREF(wm->native_window); return RET_OK; } static ret_t window_manager_default_on_layout_children(widget_t* widget) { rect_t client_r = rect_init(0, 0, widget->w, widget->h); return_value_if_fail(widget != NULL, RET_BAD_PARAMS); WIDGET_FOR_EACH_CHILD_BEGIN(widget, iter, i) if (widget_is_system_bar(iter)) { window_manager_default_layout_system_bar(widget, iter); } WIDGET_FOR_EACH_CHILD_END(); window_manager_default_get_client_r(widget, &client_r); WIDGET_FOR_EACH_CHILD_BEGIN(widget, iter, i) if (!widget_is_system_bar(iter)) { window_manager_default_layout_not_system_bar(widget, iter, client_r); } WIDGET_FOR_EACH_CHILD_END(); return RET_OK; } static ret_t window_manager_default_resize(widget_t* widget, wh_t w, wh_t h); static ret_t window_manager_default_post_init(widget_t* widget, wh_t w, wh_t h); static ret_t window_manager_default_set_cursor(widget_t* widget, const char* cursor); static ret_t window_manager_default_set_show_fps(widget_t* widget, bool_t show_fps); static ret_t window_manager_default_dispatch_input_event(widget_t* widget, event_t* e); static ret_t window_manager_default_set_screen_saver_time(widget_t* widget, uint32_t screen_saver_time); static ret_t window_manager_default_get_pointer(widget_t* widget, xy_t* x, xy_t* y, bool_t* pressed, bool_t* in_pointer_up) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); input_device_status_t* ids = window_manager_get_input_device_status(widget); return_value_if_fail(wm != NULL && ids != NULL, RET_BAD_PARAMS); if (x != NULL) { *x = ids->last_x; } if (y != NULL) { *y = ids->last_y; } if (pressed != NULL) { *pressed = ids->pressed; } if (in_pointer_up != NULL) { *in_pointer_up = ids->in_pointer_up; } return RET_OK; } static ret_t window_manager_default_is_animating(widget_t* widget, bool_t* playing) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(widget != NULL, RET_BAD_PARAMS); *playing = wm->animating; return RET_OK; } static ret_t window_manager_default_orientation(widget_t* widget, wh_t w, wh_t h, lcd_orientation_t old_orientation, lcd_orientation_t new_orientation) { ret_t ret = RET_OK; rect_t r = rect_init(0, 0, w, h); window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); ret = native_window_set_orientation(wm->native_window, old_orientation, new_orientation); return_value_if_fail(ret == RET_OK, ret); widget_move_resize(widget, 0, 0, w, h); native_window_invalidate(wm->native_window, &r); native_window_update_last_dirty_rect(wm->native_window); return widget_layout_children(widget); } ret_t window_manager_default_on_event(widget_t* widget, event_t* e) { ret_t ret = RET_OK; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); input_device_status_t* ids = window_manager_get_input_device_status(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); if (e->type == EVT_ORIENTATION_WILL_CHANGED) { wh_t w, h; lcd_orientation_t new_orientation; lcd_orientation_t old_orientation; orientation_event_t* evt = orientation_event_cast(e); lcd_t* lcd = native_window_get_canvas(wm->native_window)->lcd; return_value_if_fail(lcd != NULL && evt != NULL, RET_FAIL); w = lcd->w; h = lcd->h; new_orientation = evt->orientation; old_orientation = evt->old_orientation; native_window_clear_dirty_rect(wm->native_window); if (tk_is_swap_size_by_orientation(old_orientation, new_orientation)) { w = lcd->h; h = lcd->w; } ret = lcd_set_orientation(lcd, old_orientation, new_orientation); return_value_if_fail(ret == RET_OK, ret); #if !defined(WITH_GPU) && defined(WITH_FAST_LCD_PORTRAIT) if (system_info()->flags & SYSTEM_INFO_FLAG_FAST_LCD_PORTRAIT) { ENSURE(image_manager_unload_all(widget_get_image_manager(widget)) == RET_OK); } #endif window_manager_default_orientation(widget, w, h, old_orientation, new_orientation); e->type = EVT_ORIENTATION_CHANGED; widget_dispatch(widget, e); window_manager_default_reset_window_animator(widget); window_manager_default_reset_dialog_highlighter(widget); } else if (e->type == EVT_THEME_CHANGED) { window_manager_on_theme_changed(widget); window_manager_default_reset_window_animator(widget); window_manager_default_reset_dialog_highlighter(widget); } else if (e->type == EVT_TOP_WINDOW_CHANGED) { input_device_status_abort_all_pressed_keys(ids); } return RET_OK; } static bool_t widget_is_system_bar_top(widget_t* window) { return tk_str_eq(window->vt->type, WIDGET_TYPE_SYSTEM_BAR); } static bool_t widget_is_system_bar_bottom(widget_t* window) { return tk_str_eq(window->vt->type, WIDGET_TYPE_SYSTEM_BAR_BOTTOM); } static ret_t window_manager_default_get_client_r(widget_t* widget, rect_t* r) { *r = rect_init(0, 0, widget->w, widget->h); WIDGET_FOR_EACH_CHILD_BEGIN(widget, iter, i) if (widget_is_system_bar_top(iter)) { r->y = iter->h; r->h -= iter->h; } if (widget_is_system_bar_bottom(iter)) { r->h -= iter->h; } WIDGET_FOR_EACH_CHILD_END(); return RET_OK; } static ret_t window_manager_default_layout_system_bar(widget_t* widget, widget_t* window) { window->x = 0; window->w = widget->w; if (widget_is_system_bar_bottom(window)) { window->y = widget->h - window->h; } widget_layout(window); return RET_OK; } static ret_t window_manager_default_layout_not_system_bar(widget_t* widget, widget_t* window, rect_t client_r) { xy_t x = window->x; xy_t y = window->y; wh_t w = window->w; wh_t h = window->h; if (widget_is_normal_window(window)) { if (widget_is_fullscreen_window(window)) { x = 0; y = 0; w = widget->w; h = widget->h; } else { x = client_r.x; y = client_r.y; w = client_r.w; h = client_r.h; } } else if (widget_is_dialog(window)) { rect_t widget_r = {widget->x, widget->y, widget->w, widget->h}; rect_t window_r = {window->x, window->y, window->w, window->h}; rect_merge(&widget_r, &window_r); /* Force centering if the dialog box is out of window_manager! */ if (widget_r.x < widget->x || widget_r.y < widget->y || widget_r.w > widget->w || widget_r.h > widget->h) { w = tk_min(widget->w, window->w); h = tk_min(widget->h, window->h); x = (widget->w - w) >> 1; y = (widget->h - h) >> 1; } } else { x = window->x; y = window->y; w = window->w; h = window->h; } widget_move_resize_ex(window, x, y, w, h, FALSE); widget_layout(window); return RET_OK; } static ret_t window_manager_default_layout_child(widget_t* widget, widget_t* window) { if (widget_is_system_bar(window)) { return window_manager_default_layout_system_bar(widget, window); } else { rect_t client_r = rect_init(0, 0, widget->w, widget->h); window_manager_default_get_client_r(widget, &client_r); return window_manager_default_layout_not_system_bar(widget, window, client_r); } } static ret_t window_manager_default_set_fullscreen(widget_t* widget, bool_t fullscreen) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); return native_window_set_fullscreen(wm->native_window, fullscreen); } static ret_t window_manager_default_resize(widget_t* widget, wh_t w, wh_t h) { ret_t ret = RET_OK; rect_t r = rect_init(0, 0, w, h); window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); lcd_orientation_t lcd_orientation = system_info()->lcd_orientation; return_value_if_fail(wm != NULL, RET_BAD_PARAMS); ret = native_window_resize(wm->native_window, w, h, TRUE); return_value_if_fail(ret == RET_OK, ret); if (lcd_orientation == LCD_ORIENTATION_90 || lcd_orientation == LCD_ORIENTATION_270) { wh_t tmp_w = w; w = h; h = tmp_w; r = rect_init(0, 0, w, h); } if (widget->w == w && widget->h == h) { return RET_OK; } widget_move_resize(widget, 0, 0, w, h); native_window_invalidate(wm->native_window, &r); native_window_update_last_dirty_rect(wm->native_window); return widget_layout_children(widget); } static ret_t window_manager_default_post_init(widget_t* widget, wh_t w, wh_t h) { native_window_info_t info; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); wm->lcd_w = w; wm->lcd_h = h; wm->native_window = window_manager_create_native_window(WINDOW_MANAGER(wm), widget); if (native_window_get_info(wm->native_window, &info) == RET_OK) { w = info.w; h = info.h; } window_manager_default_resize(widget, w, h); return RET_OK; } static ret_t window_manager_default_dispatch_input_event(widget_t* widget, event_t* e) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); input_device_status_t* ids = window_manager_get_input_device_status(widget); return_value_if_fail(wm != NULL && e != NULL, RET_BAD_PARAMS); window_manager_start_or_reset_screen_saver_timer(wm); native_window_preprocess_event(wm->native_window, e); if (wm->ignore_user_input) { log_debug("animating ignore input\n"); input_device_status_on_ignore_input_event(ids, widget, e); return RET_OK; } input_device_status_on_input_event(ids, widget, e); window_manager_update_cursor(widget, ids->last_x, ids->last_y); return RET_OK; } static ret_t window_manager_default_set_show_fps(widget_t* widget, bool_t show_fps) { window_manager_t* wm = WINDOW_MANAGER(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); wm->show_fps = show_fps; return RET_OK; } static ret_t window_manager_default_set_screen_saver_time(widget_t* widget, uint32_t screen_saver_time) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); wm->screen_saver_time = screen_saver_time; window_manager_start_or_reset_screen_saver_timer(wm); return RET_OK; } static ret_t window_manager_default_set_cursor(widget_t* widget, const char* cursor) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); #if defined(ENABLE_CURSOR) if (tk_str_eq(cursor, wm->cursor)) { return RET_OK; } tk_strncpy(wm->cursor, cursor, TK_NAME_LEN); if (cursor != NULL && *cursor) { bitmap_t bitmap; bitmap_t* img = NULL; if (image_manager_get_bitmap(image_manager(), cursor, &bitmap) == RET_OK) { img = &bitmap; } if (native_window_set_cursor(wm->native_window, cursor, img) != RET_OK) { wm->r_cursor.w = bitmap.w; wm->r_cursor.h = bitmap.h; } else { wm->r_cursor.w = 0; wm->r_cursor.h = 0; } } #endif /*ENABLE_CURSOR*/ return RET_OK; } ret_t window_manager_paint_system_bar(widget_t* widget, canvas_t* c) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL && c != NULL, RET_BAD_PARAMS); WIDGET_FOR_EACH_CHILD_BEGIN_R(widget, iter, i) if (widget_is_system_bar(iter)) { widget_paint(iter, c); } WIDGET_FOR_EACH_CHILD_END() return RET_OK; } ret_t window_manager_paint_system_bar_top(widget_t* widget, canvas_t* c) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL && c != NULL, RET_BAD_PARAMS); WIDGET_FOR_EACH_CHILD_BEGIN_R(widget, iter, i) if (iter->vt->is_window && tk_str_eq(iter->vt->type, WIDGET_TYPE_SYSTEM_BAR)) { widget_paint(iter, c); break; } WIDGET_FOR_EACH_CHILD_END() return RET_OK; } ret_t window_manager_paint_system_bar_bottom(widget_t* widget, canvas_t* c) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(wm != NULL && c != NULL, RET_BAD_PARAMS); WIDGET_FOR_EACH_CHILD_BEGIN_R(widget, iter, i) if (iter->vt->is_window && tk_str_eq(iter->vt->type, WIDGET_TYPE_SYSTEM_BAR_BOTTOM)) { widget_paint(iter, c); break; } WIDGET_FOR_EACH_CHILD_END() return RET_OK; } static ret_t window_manager_default_reset_window_animator(widget_t* widget) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); #ifndef WITHOUT_WINDOW_ANIMATOR_CACHE if (wm->animator != NULL) { window_animator_t* wa = wm->animator; if (wa->dialog_highlighter == NULL) { bitmap_destroy(&(wa->prev_img)); } bitmap_destroy(&(wa->curr_img)); window_manager_snap_prev_window(widget, wa->prev_win, &(wa->prev_img)); window_manager_snap_curr_window(widget, wa->curr_win, &(wa->curr_img)); } #endif return RET_OK; } static ret_t window_manager_default_reset_dialog_highlighter(widget_t* widget) { window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); if (wm->dialog_highlighter != NULL) { bitmap_t img; widget_t* prev = window_manager_find_prev_normal_window(widget); memset(&img, 0x00, sizeof(img)); if (prev != NULL) { dialog_highlighter_clear_image(wm->dialog_highlighter); wm->curr_win = wm->last_curr_win; window_manager_default_snap_prev_window(widget, prev, &img); wm->curr_win = NULL; } } return RET_OK; } static ret_t window_manager_default_native_window_resized(widget_t* widget, void* handle) { native_window_info_t ainfo; window_manager_default_t* wm = WINDOW_MANAGER_DEFAULT(widget); return_value_if_fail(native_window_get_info(wm->native_window, &ainfo) == RET_OK, RET_FAIL); native_window_clear_dirty_rect(wm->native_window); window_manager_default_resize(widget, ainfo.w, ainfo.h); window_manager_default_reset_window_animator(widget); window_manager_default_reset_dialog_highlighter(widget); return RET_OK; } static ret_t window_manager_default_on_locale_changed(void* ctx, event_t* e) { widget_t* widget = WIDGET(ctx); return_value_if_fail(widget != NULL, RET_FAIL); window_manager_default_reset_window_animator(widget); window_manager_default_reset_dialog_highlighter(widget); return RET_OK; } static ret_t window_manager_default_dispatch_native_window_event(widget_t* widget, event_t* e, void* handle) { input_device_status_t* ids = window_manager_get_input_device_status(widget); return_value_if_fail(ids != NULL, RET_BAD_PARAMS); if (e->type == EVT_NATIVE_WINDOW_RESIZED) { window_manager_default_native_window_resized(widget, handle); } else if (e->type == EVT_NATIVE_WINDOW_ENTER) { int32_t x = ((pointer_event_t*)e)->x; int32_t y = ((pointer_event_t*)e)->y; input_device_status_on_pointer_enter(ids, widget, x, y); } else if (e->type == EVT_NATIVE_WINDOW_LEAVE) { input_device_status_on_pointer_leave(ids, widget); } return RET_OK; } static window_manager_vtable_t s_window_manager_self_vtable = { .switch_to = window_manager_default_switch_to, .paint = window_manager_default_paint, .post_init = window_manager_default_post_init, .set_cursor = window_manager_default_set_cursor, .open_window = window_manager_default_open_window, .close_window = window_manager_default_close_window, .set_show_fps = window_manager_default_set_show_fps, .get_prev_window = window_manager_default_get_prev_window, .close_window_force = window_manager_default_close_window_force, .dispatch_input_event = window_manager_default_dispatch_input_event, .dispatch_native_window_event = window_manager_default_dispatch_native_window_event, .set_screen_saver_time = window_manager_default_set_screen_saver_time, .get_pointer = window_manager_default_get_pointer, .is_animating = window_manager_default_is_animating, .snap_curr_window = window_manager_default_snap_curr_window, .snap_prev_window = window_manager_default_snap_prev_window, .get_dialog_highlighter = window_manager_default_get_dialog_highlighter, .resize = window_manager_default_resize, .set_fullscreen = window_manager_default_set_fullscreen}; static const widget_vtable_t s_window_manager_vtable = { .size = sizeof(window_manager_t), .type = WIDGET_TYPE_WINDOW_MANAGER, .is_window_manager = TRUE, .set_prop = window_manager_default_set_prop, .get_prop = window_manager_default_get_prop, .on_event = window_manager_default_on_event, .invalidate = window_manager_default_invalidate, .on_layout_children = window_manager_default_on_layout_children, .on_paint_children = window_manager_default_on_paint_children, .on_remove_child = window_manager_default_on_remove_child, .find_target = window_manager_default_find_target, .on_destroy = window_manager_default_on_destroy}; widget_t* window_manager_create(void) { window_manager_default_t* wm = TKMEM_ZALLOC(window_manager_default_t); return_value_if_fail(wm != NULL, NULL); wm->ready_animator = FALSE; WINDOW_MANAGER(wm)->max_fps = TK_MAX_FPS; locale_info_on(locale_info(), EVT_LOCALE_CHANGED, window_manager_default_on_locale_changed, wm); return window_manager_init(WINDOW_MANAGER(wm), &s_window_manager_vtable, &s_window_manager_self_vtable); }
0
repos/awtk/src
repos/awtk/src/window_manager/window_manager_default.h
/** * File: window_manager.h * Author: AWTK Develop Team * Brief: window manager * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-01-13 Li XianJing <[email protected]> created * */ #ifndef TK_WINDOW_MANAGER_DEFAULT_H #define TK_WINDOW_MANAGER_DEFAULT_H #include "tkc/fps.h" #include "base/native_window.h" #include "base/window_manager.h" BEGIN_C_DECLS /** * @class window_manager_default_t * @parent window_manager_t * 缺省窗口管理器。 */ typedef struct _window_manager_default_t { window_manager_t window_manager; /*private*/ bool_t animating; bool_t ready_animator; bool_t ignore_user_input; bool_t is_animator_paint_system_bar_top; bool_t is_animator_paint_system_bar_bottom; window_animator_t* animator; fps_t fps; uint32_t last_paint_cost; uint64_t last_paint_time; widget_t* pending_close_window; widget_t* pending_open_window; char cursor[TK_NAME_LEN + 1]; rect_t r_cursor; uint32_t screen_saver_timer_id; uint32_t screen_saver_time; widget_t* prev_win; /* for window_manager_default_snap_prev_window */ widget_t* curr_win; widget_t* last_curr_win; native_window_t* native_window; dialog_highlighter_t* dialog_highlighter; int32_t lcd_w; int32_t lcd_h; } window_manager_default_t; /** * @method window_manager_create * @export none * 创建窗口管理器。 * @annotation ["constructor"] * * @return {widget_t*} 返回窗口管理器对象。 */ widget_t* window_manager_create(void); #define WINDOW_MANAGER_DEFAULT(widget) ((window_manager_default_t*)(widget)) /* private */ ret_t window_manager_paint_system_bar(widget_t* widget, canvas_t* c); ret_t window_manager_paint_system_bar_top(widget_t* widget, canvas_t* c); ret_t window_manager_paint_system_bar_bottom(widget_t* widget, canvas_t* c); END_C_DECLS #endif /*TK_WINDOW_MANAGER_DEFAULT_H*/
0
repos/awtk/src
repos/awtk/src/window_manager/window_manager_simple.c
/** * File: window_manager_simple.c * Author: AWTK Develop Team * Brief: default window manager * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2019-08-18 Li XianJing <[email protected]> created * */ #include "base/keys.h" #include "tkc/mem.h" #include "base/idle.h" #include "tkc/utils.h" #include "base/timer.h" #include "base/layout.h" #include "tkc/time_now.h" #include "base/dialog.h" #include "base/locale_info.h" #include "base/system_info.h" #include "base/image_manager.h" #include "window_manager/window_manager_simple.h" ret_t window_manager_paint_system_bar(widget_t* widget, canvas_t* c); static ret_t window_manager_simple_invalidate(widget_t* widget, const rect_t* r); static ret_t window_manager_simple_do_open_window(widget_t* wm, widget_t* window); static ret_t window_manager_simple_layout_child(widget_t* widget, widget_t* window); static bool_t window_is_opened(widget_t* widget) { int32_t stage = widget_get_prop_int(widget, WIDGET_PROP_STAGE, WINDOW_STAGE_NONE); return stage == WINDOW_STAGE_OPENED || stage == WINDOW_STAGE_SUSPEND; } static widget_t* window_manager_find_prev_window(widget_t* widget) { int32_t i = 0; int32_t nr = 0; return_value_if_fail(widget != NULL, NULL); if (widget->children != NULL && widget->children->size > 0) { nr = widget->children->size; for (i = nr - 2; i >= 0; i--) { widget_t* iter = (widget_t*)(widget->children->elms[i]); if (widget_is_normal_window(iter)) { return iter; } } } return NULL; } static ret_t window_manager_dispatch_window_open(widget_t* curr_win) { window_manager_dispatch_window_event(curr_win, EVT_WINDOW_WILL_OPEN); return window_manager_dispatch_window_event(curr_win, EVT_WINDOW_OPEN); } static ret_t window_manager_idle_dispatch_window_open(const idle_info_t* info) { window_manager_dispatch_window_open(WIDGET(info->ctx)); return RET_REMOVE; } static ret_t window_manager_simple_do_open_window(widget_t* widget, widget_t* window) { widget_add_idle(window, (idle_func_t)window_manager_idle_dispatch_window_open); return RET_OK; } static ret_t wm_on_destroy_child(void* ctx, event_t* e) { widget_t* widget = WIDGET(ctx); (void)e; if (!widget->destroying) { window_manager_dispatch_top_window_changed(widget); } return RET_REMOVE; } static ret_t window_manager_simple_open_window(widget_t* widget, widget_t* window) { ret_t ret = RET_OK; window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); return_value_if_fail(widget != NULL && window != NULL, RET_BAD_PARAMS); if (widget_is_system_bar(window)) { return_value_if_fail(wm->system_bar == NULL, RET_BAD_PARAMS); } wm->prev_win = window_manager_get_top_window(widget); window_manager_simple_do_open_window(widget, window); ret = widget_add_child(widget, window); return_value_if_fail(ret == RET_OK, RET_FAIL); window_manager_simple_layout_child(widget, window); window->dirty = FALSE; widget->target = window; if (!widget_is_keyboard(window)) { widget->key_target = window; } widget_invalidate(window, NULL); if (widget_is_system_bar(window)) { wm->system_bar = window; } widget_set_prop_pointer(window, WIDGET_PROP_NATIVE_WINDOW, wm->native_window); widget_on(window, EVT_DESTROY, wm_on_destroy_child, widget); widget_update_style(widget); return ret; } static ret_t window_manager_idle_destroy_window(const idle_info_t* info) { widget_t* win = WIDGET(info->ctx); widget_destroy(win); return RET_OK; } static ret_t window_manager_prepare_close_window(widget_t* widget, widget_t* window) { window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); return_value_if_fail(widget != NULL && window != NULL, RET_BAD_PARAMS); if (widget->target == window) { widget->target = NULL; } if (widget->key_target == window) { widget->key_target = NULL; } if (widget->grab_widget != NULL) { if (widget->grab_widget == window) { widget->grab_widget = NULL; } } if (wm->system_bar == window) { wm->system_bar = NULL; } return RET_OK; } static ret_t window_manager_simple_close_window(widget_t* widget, widget_t* window) { window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); return_value_if_fail(widget_is_window(window), RET_BAD_PARAMS); return_value_if_fail(window_is_opened(window), RET_BAD_PARAMS); window_manager_prepare_close_window(widget, window); window_manager_dispatch_window_event(window, EVT_WINDOW_CLOSE); { widget_t* prev_win = window_manager_find_prev_window(WIDGET(wm)); if (prev_win != NULL) { if (!widget_is_keyboard(window)) { window_manager_dispatch_window_event(prev_win, EVT_WINDOW_TO_FOREGROUND); } } widget_remove_child(widget, window); idle_add(window_manager_idle_destroy_window, window); } return RET_OK; } static ret_t window_manager_simple_close_window_force(widget_t* widget, widget_t* window) { window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); return_value_if_fail(widget_is_window(window), RET_BAD_PARAMS); window_manager_prepare_close_window(widget, window); window_manager_dispatch_window_event(window, EVT_WINDOW_CLOSE); widget_remove_child(widget, window); widget_destroy(window); return RET_OK; } static widget_t* window_manager_simple_find_target(widget_t* widget, xy_t x, xy_t y) { return window_manager_find_target(widget, NULL, x, y); } static ret_t window_manager_paint_normal(widget_t* widget, canvas_t* c) { uint64_t start_time = time_now_ms(); window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); if (native_window_begin_frame(wm->native_window, LCD_DRAW_NORMAL) == RET_OK) { ENSURE(widget_paint(WIDGET(wm), c) == RET_OK); native_window_end_frame(wm->native_window); } wm->last_paint_cost = time_now_ms() - start_time; return RET_OK; } static ret_t window_manager_simple_paint(widget_t* widget) { ret_t ret = RET_OK; window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); canvas_t* c = native_window_get_canvas(wm->native_window); return_value_if_fail(wm != NULL && c != NULL, RET_BAD_PARAMS); canvas_set_global_alpha(c, 0xff); ret = window_manager_paint_normal(widget, c); return ret; } static ret_t window_manager_simple_invalidate(widget_t* widget, const rect_t* r) { window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); if (wm->native_window != NULL) { native_window_invalidate(wm->native_window, r); } return RET_OK; } static widget_t* window_manager_simple_get_prev_window(widget_t* widget) { window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); return wm->prev_win; } static ret_t window_manager_simple_on_paint_children(widget_t* widget, canvas_t* c) { int32_t start = 0; bool_t has_fullscreen_win = FALSE; window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); return_value_if_fail(widget != NULL && c != NULL, RET_BAD_PARAMS); WIDGET_FOR_EACH_CHILD_BEGIN_R(widget, iter, i) if (iter->visible && widget_is_normal_window(iter)) { start = i; break; } WIDGET_FOR_EACH_CHILD_END() /*paint normal windows*/ WIDGET_FOR_EACH_CHILD_BEGIN(widget, iter, i) if (i >= start && iter->visible) { if (widget_is_normal_window(iter)) { widget_paint(iter, c); if (!has_fullscreen_win) { has_fullscreen_win = widget_is_fullscreen_window(iter); } start = i + 1; break; } } WIDGET_FOR_EACH_CHILD_END() /*paint system_bar*/ if (!has_fullscreen_win) { window_manager_paint_system_bar(widget, c); } /*paint dialog and other*/ WIDGET_FOR_EACH_CHILD_BEGIN(widget, iter, i) if (i >= start && iter->visible) { if (wm->system_bar != iter && !widget_is_normal_window(iter)) { widget_paint(iter, c); } } WIDGET_FOR_EACH_CHILD_END() return RET_OK; } static ret_t window_manager_simple_on_remove_child(widget_t* widget, widget_t* window) { widget_t* top = window_manager_get_top_main_window(widget); if (top != NULL) { rect_t r; r = rect_init(window->x, window->y, window->w, window->h); widget_invalidate(top, &r); } return RET_FAIL; } static ret_t window_manager_simple_get_prop(widget_t* widget, const char* name, value_t* v) { window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); return_value_if_fail(widget != NULL && name != NULL && v != NULL, RET_BAD_PARAMS); if (tk_str_eq(name, WIDGET_PROP_CANVAS)) { canvas_t* c = native_window_get_canvas(wm->native_window); value_set_pointer(v, c); return RET_OK; } return RET_NOT_FOUND; } static ret_t window_manager_simple_set_prop(widget_t* widget, const char* name, const value_t* v) { return_value_if_fail(widget != NULL && name != NULL && v != NULL, RET_BAD_PARAMS); return RET_NOT_FOUND; } static ret_t window_manager_simple_on_destroy(widget_t* widget) { window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); tk_object_unref(TK_OBJECT(wm->native_window)); return RET_OK; } static ret_t window_manager_simple_on_layout_children(widget_t* widget) { return_value_if_fail(widget != NULL, RET_BAD_PARAMS); WIDGET_FOR_EACH_CHILD_BEGIN(widget, iter, i) window_manager_simple_layout_child(widget, iter); WIDGET_FOR_EACH_CHILD_END(); return RET_OK; } static ret_t window_manager_simple_resize(widget_t* widget, wh_t w, wh_t h); static ret_t window_manager_simple_post_init(widget_t* widget, wh_t w, wh_t h); static ret_t window_manager_simple_dispatch_input_event(widget_t* widget, event_t* e); static ret_t window_manager_simple_get_pointer(widget_t* widget, xy_t* x, xy_t* y, bool_t* pressed, bool_t* in_pointer_up) { window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); input_device_status_t* ids = window_manager_get_input_device_status(widget); return_value_if_fail(wm != NULL && ids != NULL, RET_BAD_PARAMS); if (x != NULL) { *x = ids->last_x; } if (y != NULL) { *y = ids->last_y; } if (pressed != NULL) { *pressed = ids->pressed; } if (in_pointer_up != NULL) { *in_pointer_up = ids->in_pointer_up; } return RET_OK; } static ret_t window_manager_simple_on_event(widget_t* widget, event_t* e) { if (e->type == EVT_ORIENTATION_WILL_CHANGED) { orientation_event_t* evt = orientation_event_cast(e); lcd_orientation_t orientation = evt->orientation; window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); lcd_t* lcd = native_window_get_canvas(wm->native_window)->lcd; wh_t w = wm->lcd_w; wh_t h = wm->lcd_h; if (orientation == LCD_ORIENTATION_90 || orientation == LCD_ORIENTATION_270) { w = wm->lcd_h; h = wm->lcd_w; } lcd_resize(lcd, w, h, 0); window_manager_simple_resize(widget, w, h); e->type = EVT_ORIENTATION_CHANGED; widget_dispatch(widget, e); } return RET_OK; } static ret_t window_manager_simple_layout_child(widget_t* widget, widget_t* window) { xy_t x = window->x; xy_t y = window->y; wh_t w = window->w; wh_t h = window->h; window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); rect_t client_r = rect_init(0, 0, widget->w, widget->h); if (wm->system_bar != NULL) { widget_t* bar = wm->system_bar; client_r = rect_init(0, bar->h, widget->w, widget->h - bar->h); } if (widget_is_normal_window(window)) { if (widget_is_fullscreen_window(window)) { x = 0; y = 0; w = widget->w; h = widget->h; } else { x = client_r.x; y = client_r.y; w = client_r.w; h = client_r.h; } } else if (widget_is_system_bar(window)) { x = 0; y = 0; w = widget->w; } else if (widget_is_dialog(window)) { x = (widget->w - window->w) >> 1; y = (widget->h - window->h) >> 1; } else { x = window->x; y = window->y; w = window->w; h = window->h; } widget_move_resize(window, x, y, w, h); widget_layout(window); return RET_OK; } static ret_t window_manager_default_set_fullscreen(widget_t* widget, bool_t fullscreen) { window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); return native_window_set_fullscreen(wm->native_window, fullscreen); } static ret_t window_manager_simple_resize(widget_t* widget, wh_t w, wh_t h) { rect_t r = rect_init(0, 0, w, h); window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); widget_move_resize(widget, 0, 0, w, h); native_window_resize(wm->native_window, w, h, TRUE); native_window_invalidate(wm->native_window, &r); native_window_update_last_dirty_rect(wm->native_window); return widget_layout_children(widget); } static ret_t window_manager_simple_post_init(widget_t* widget, wh_t w, wh_t h) { native_window_info_t info; window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); return_value_if_fail(wm != NULL, RET_BAD_PARAMS); wm->lcd_w = w; wm->lcd_h = h; wm->native_window = window_manager_create_native_window(wm, widget); if (native_window_get_info(wm->native_window, &info) == RET_OK) { w = info.w; h = info.h; } window_manager_simple_resize(widget, w, h); return RET_OK; } static ret_t window_manager_simple_dispatch_input_event(widget_t* widget, event_t* e) { window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); input_device_status_t* ids = window_manager_get_input_device_status(widget); return_value_if_fail(wm != NULL && ids != NULL && e != NULL, RET_BAD_PARAMS); native_window_preprocess_event(wm->native_window, e); input_device_status_on_input_event(ids, widget, e); return RET_OK; } ret_t window_manager_paint_system_bar(widget_t* widget, canvas_t* c) { window_manager_simple_t* wm = WINDOW_MANAGER_SIMPLE(widget); return_value_if_fail(wm != NULL && c != NULL, RET_BAD_PARAMS); if (wm->system_bar != NULL && wm->system_bar->visible) { widget_paint(wm->system_bar, c); } return RET_OK; } static ret_t window_manager_native_native_window_resized(widget_t* widget, void* handle) { uint32_t w = 0; uint32_t h = 0; system_info_t* info = system_info(); native_window_t* nw = WINDOW_MANAGER_SIMPLE(widget)->native_window; if (info->lcd_orientation == LCD_ORIENTATION_90 || info->lcd_orientation == LCD_ORIENTATION_270) { w = info->lcd_h; h = info->lcd_w; } else { w = info->lcd_w; h = info->lcd_h; } window_manager_simple_resize(widget, w, h); return RET_OK; } static ret_t window_manager_native_dispatch_native_window_event(widget_t* widget, event_t* e, void* handle) { if (e->type == EVT_NATIVE_WINDOW_RESIZED) { window_manager_native_native_window_resized(widget, handle); } return RET_OK; } static window_manager_vtable_t s_window_manager_self_vtable = { .paint = window_manager_simple_paint, .post_init = window_manager_simple_post_init, .open_window = window_manager_simple_open_window, .get_pointer = window_manager_simple_get_pointer, .close_window = window_manager_simple_close_window, .get_prev_window = window_manager_simple_get_prev_window, .close_window_force = window_manager_simple_close_window_force, .dispatch_input_event = window_manager_simple_dispatch_input_event, .dispatch_native_window_event = window_manager_native_dispatch_native_window_event, .resize = window_manager_simple_resize, .set_fullscreen = window_manager_default_set_fullscreen, }; static const widget_vtable_t s_window_manager_vtable = { .size = sizeof(window_manager_t), .is_window_manager = TRUE, .type = WIDGET_TYPE_WINDOW_MANAGER, .set_prop = window_manager_simple_set_prop, .get_prop = window_manager_simple_get_prop, .on_event = window_manager_simple_on_event, .invalidate = window_manager_simple_invalidate, .on_layout_children = window_manager_simple_on_layout_children, .on_paint_children = window_manager_simple_on_paint_children, .on_remove_child = window_manager_simple_on_remove_child, .find_target = window_manager_simple_find_target, .on_destroy = window_manager_simple_on_destroy}; widget_t* window_manager_create(void) { window_manager_simple_t* wm = TKMEM_ZALLOC(window_manager_simple_t); return_value_if_fail(wm != NULL, NULL); return window_manager_init(WINDOW_MANAGER(wm), &s_window_manager_vtable, &s_window_manager_self_vtable); }
0
repos/awtk/src
repos/awtk/src/window_manager/window_manager_simple.h
/** * File: window_manager.h * Author: AWTK Develop Team * Brief: window manager * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2019-08-18 Li XianJing <[email protected]> created * */ #ifndef TK_WINDOW_MANAGER_SIMPLE_H #define TK_WINDOW_MANAGER_SIMPLE_H #include "base/native_window.h" #include "base/window_manager.h" BEGIN_C_DECLS /** * @class window_manager_simple_t * @parent window_manager_t * 简单窗口管理器(不支持窗口动画和对话框高亮策略)。 */ typedef struct _window_manager_simple_t { window_manager_t window_manager; /*private*/ uint32_t last_paint_cost; widget_t* system_bar; widget_t* prev_win; native_window_t* native_window; int32_t lcd_w; int32_t lcd_h; } window_manager_simple_t; /** * @method window_manager_create * @export none * 创建窗口管理器。 * @annotation ["constructor"] * * @return {widget_t*} 返回窗口管理器对象。 */ widget_t* window_manager_create(void); #define WINDOW_MANAGER_SIMPLE(widget) ((window_manager_simple_t*)(widget)) END_C_DECLS #endif /*TK_WINDOW_MANAGER_SIMPLE_H*/
0
repos/awtk/src
repos/awtk/src/widget_animators/widget_animator_scroll.c
/** * File: widget_animator_scroll.h * Author: AWTK Develop Team * Brief: animate widget by change its position. * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-05-15 Li XianJing <[email protected]> created * */ #include "tkc/mem.h" #include "widget_animators/widget_animator_scroll.h" static ret_t widget_animator_scroll_update(widget_animator_t* animator, float_t percent) { int64_t xoffset = 0; int64_t yoffset = 0; value_t v; widget_animator_scroll_t* scroll = (widget_animator_scroll_t*)animator; return_value_if_fail(scroll != NULL, RET_BAD_PARAMS); if (scroll->x_to != scroll->x_from) { xoffset = scroll->x_from + (double)(scroll->x_to - scroll->x_from) * percent; value_set_int64(&v, xoffset); widget_set_prop(animator->widget, WIDGET_PROP_XOFFSET, &v); } if (scroll->y_to != scroll->y_from) { yoffset = scroll->y_from + (double)(scroll->y_to - scroll->y_from) * percent; value_set_int64(&v, yoffset); widget_set_prop(animator->widget, WIDGET_PROP_YOFFSET, &v); } return RET_OK; } widget_animator_t* widget_animator_scroll_create(widget_t* widget, uint32_t duration, uint32_t delay, easing_type_t easing) { widget_animator_t* animator = NULL; return_value_if_fail(widget != NULL && duration > 0, NULL); animator = (widget_animator_t*)TKMEM_ZALLOC(widget_animator_scroll_t); return_value_if_fail( widget_animator_init(animator, widget, duration, delay, easing_get(easing)) == RET_OK, NULL); animator->update = widget_animator_scroll_update; return animator; } ret_t widget_animator_scroll_set_params(widget_animator_t* animator, xy_t x_from, xy_t y_from, xy_t x_to, xy_t y_to) { widget_animator_scroll_t* scroll = (widget_animator_scroll_t*)animator; return_value_if_fail(scroll != NULL, RET_BAD_PARAMS); scroll->x_to = x_to; scroll->y_to = y_to; scroll->x_from = x_from; scroll->y_from = y_from; return RET_OK; }
0
repos/awtk/src
repos/awtk/src/widget_animators/widget_animator_prop.h
/** * File: widget_animator_prop.h * Author: AWTK Develop Team * Brief: animate widget by change its prop * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-12-11 Li XianJing <[email protected]> created * */ #ifndef TK_WIDGET_ANIMATOR_PROP_H #define TK_WIDGET_ANIMATOR_PROP_H #include "base/widget_animator.h" BEGIN_C_DECLS /** * @class widget_animator_prop_t * 通过修改对象的指定属性形成动画效果。 */ typedef struct _widget_animator_prop_t { widget_animator_t base; double to; double from; char prop_name[TK_NAME_LEN + 1]; } widget_animator_prop_t; /** * @method widget_animator_prop_create * 创建单属性动画对象。 * @param {widget_t*} widget 控件对象。 * @param {uint32_t} duration 动画持续时间(毫秒)。 * @param {uint32_t} delay 动画执行时间(毫秒)。 * @param {easing_type_t} easing 插值函数类型。 * @param {const char*} prop_name 属性的名称。 * * @return {widget_animator_t*} 成功返回动画对象,失败返回NULL。 */ widget_animator_t* widget_animator_prop_create(widget_t* widget, uint32_t duration, uint32_t delay, easing_type_t easing, const char* prop_name); /** * @method widget_animator_prop_set_params * 设置动画对象的参数。 * @param {widget_animator_t*} animator 动画对象本身。 * @param {double} from prop起始值。 * @param {double} to prop结束值。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t widget_animator_prop_set_params(widget_animator_t* animator, double from, double to); END_C_DECLS #endif /*TK_WIDGET_ANIMATOR_PROP_H*/
0
repos/awtk/src
repos/awtk/src/widget_animators/widget_animator_opacity.h
/** * File: widget_animator_opacity.h * Author: AWTK Develop Team * Brief: animate widget by change its opacity(just wrap widget_animator_prop) * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-05-16 Li XianJing <[email protected]> created * */ #ifndef TK_WIDGET_ANIMATOR_OPACITY_H #define TK_WIDGET_ANIMATOR_OPACITY_H #include "widget_animators/widget_animator_prop.h" BEGIN_C_DECLS #define widget_animator_opacity_create(widget, duration, delay, easing) \ widget_animator_prop_create(widget, duration, delay, easing, WIDGET_PROP_OPACITY) #define widget_animator_opacity_set_params widget_animator_prop_set_params END_C_DECLS #endif /*TK_WIDGET_ANIMATOR_OPACITY_H*/
0
repos/awtk/src
repos/awtk/src/widget_animators/widget_animator_prop.c
/** * File: widget_animator_prop.c * Author: AWTK Develop Team * Brief: animate widget by change its prop * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-12-11 Li XianJing <[email protected]> created * */ #include "tkc/mem.h" #include "tkc/utils.h" #include "widget_animators/widget_animator_prop.h" static ret_t widget_animator_prop_update(widget_animator_t* animator, float_t percent) { value_t v; double new_prop = 0; widget_animator_prop_t* prop = (widget_animator_prop_t*)animator; return_value_if_fail(prop != NULL, RET_BAD_PARAMS); new_prop = prop->from + (prop->to - prop->from) * percent; widget_set_prop(animator->widget, prop->prop_name, value_set_double(&v, new_prop)); return RET_OK; } widget_animator_t* widget_animator_prop_create(widget_t* widget, uint32_t duration, uint32_t delay, easing_type_t easing, const char* prop_name) { widget_animator_t* animator = NULL; widget_animator_prop_t* prop = NULL; return_value_if_fail(widget != NULL && duration > 0 && prop_name != NULL, NULL); animator = (widget_animator_t*)TKMEM_ZALLOC(widget_animator_prop_t); return_value_if_fail(animator != NULL, NULL); return_value_if_fail( widget_animator_init(animator, widget, duration, delay, easing_get(easing)) == RET_OK, NULL); prop = (widget_animator_prop_t*)animator; animator->update = widget_animator_prop_update; tk_strncpy(prop->prop_name, prop_name, TK_NAME_LEN); return animator; } ret_t widget_animator_prop_set_params(widget_animator_t* animator, double from, double to) { widget_animator_prop_t* prop = (widget_animator_prop_t*)animator; return_value_if_fail(prop != NULL, RET_BAD_PARAMS); prop->to = to; prop->from = from; return RET_OK; }
0
repos/awtk/src
repos/awtk/src/widget_animators/widget_animator_prop2.h
/** * File: widget_animator_prop2.h * Author: AWTK Develop Team * Brief: animate widget by change its 2 props. * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-12-11 Li XianJing <[email protected]> created * */ #ifndef TK_WIDGET_ANIMATOR_PROP2_H #define TK_WIDGET_ANIMATOR_PROP2_H #include "base/widget_animator.h" BEGIN_C_DECLS /** * @class widget_animator_prop2_t * 通过修改对象的两个指定属性形成动画效果。 */ typedef struct _widget_animator_prop2_t { widget_animator_t base; double to1; double to2; double from1; double from2; char prop1_name[TK_NAME_LEN + 1]; char prop2_name[TK_NAME_LEN + 1]; } widget_animator_prop2_t; /** * @method widget_animator_prop2_create * 创建双属性动画对象。 * @param {widget_t*} widget 控件对象。 * @param {uint32_t} duration 动画持续时间(毫秒)。 * @param {uint32_t} delay 动画执行时间(毫秒)。 * @param {easing_type_t} easing 插值函数类型。 * @param {const char*} prop1_name 属性1的名称。 * @param {const char*} prop2_name 属性2的名称。 * * @return {widget_animator_t*} 成功返回动画对象,失败返回NULL。 */ widget_animator_t* widget_animator_prop2_create(widget_t* widget, uint32_t duration, uint32_t delay, easing_type_t easing, const char* prop1_name, const char* prop2_name); /** * @method widget_animator_prop2_set_params * 设置动画对象的参数。 * @param {widget_animator_t*} animator 动画对象本身。 * @param {double} from1 x的初值。 * @param {double} from2 y的初值。 * @param {double} to1 x的终值。 * @param {double} to2 y的终值。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t widget_animator_prop2_set_params(widget_animator_t* animator, double from1, double from2, double to1, double to2); END_C_DECLS #endif /*TK_WIDGET_ANIMATOR_PROP2_H*/
0
repos/awtk/src
repos/awtk/src/widget_animators/widget_animator_scale.h
/** * File: widget_animator_scale.h * Author: AWTK Develop Team * Brief: animate widget by change its scale(just wrap widget_animator_prop2) * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-05-16 Li XianJing <[email protected]> created * */ #ifndef TK_WIDGET_ANIMATOR_SCALE_H #define TK_WIDGET_ANIMATOR_SCALE_H #include "widget_animators/widget_animator_prop2.h" BEGIN_C_DECLS #define widget_animator_scale_create(widget, duration, delay, easing) \ widget_animator_prop2_create(widget, duration, delay, easing, WIDGET_PROP_SCALE_X, \ WIDGET_PROP_SCALE_Y) #define widget_animator_scale_set_params widget_animator_prop2_set_params END_C_DECLS #endif /*TK_WIDGET_ANIMATOR_SCALE_H*/
0
repos/awtk/src
repos/awtk/src/widget_animators/widget_animator_factory.c
/** * File: widget_animator_factory.c * Author: AWTK Develop Team * Brief: widget animator factory * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-10-21 Li XianJing <[email protected]> created * */ #include "base/enums.h" #include "tkc/utils.h" #include "tkc/func_call_parser.h" #include "base/widget_animator_factory.h" #ifndef WITHOUT_WIDGET_ANIMATOR #include "widget_animators/widget_animator_prop.h" #include "widget_animators/widget_animator_move.h" #include "widget_animators/widget_animator_scale.h" typedef struct _move_params_t { xy_t x_to; xy_t y_to; xy_t x_from; xy_t y_from; } move_params_t; typedef struct _scale_params_t { float_t x_to; float_t y_to; float_t x_from; float_t y_from; } scale_params_t; typedef struct _prop_params_t { float_t to; float_t from; } prop_params_t; typedef struct _animator_params_t { char type[TK_NAME_LEN + 1]; char name[TK_NAME_LEN + 1]; widget_t* widget; union { move_params_t move; scale_params_t scale; prop_params_t prop; } u; uint32_t delay; int32_t easing; uint32_t duration; int32_t yoyo_times; int32_t repeat_times; float_t time_scale; bool_t auto_start; bool_t auto_destroy; bool_t relayout; } animator_params_t; typedef struct _widget_animator_parser_t { func_call_parser_t base; animator_params_t params; } widget_animator_parser_t; static ret_t parser_on_name(func_call_parser_t* parser, const char* func_name) { value_t v; widget_animator_parser_t* p = (widget_animator_parser_t*)parser; widget_t* widget = p->params.widget; const char* type = p->params.type; tk_strncpy(p->params.type, func_name, TK_NAME_LEN); if (tk_str_eq(type, "move")) { move_params_t* params = &p->params.u.move; params->x_from = widget->x; params->y_from = widget->y; params->x_to = widget->x; params->y_to = widget->y; } else if (tk_str_eq(type, "scale")) { float_t scale_x = 1.0f; float_t scale_y = 1.0f; scale_params_t* params = &p->params.u.scale; if (widget_get_prop(widget, WIDGET_PROP_SCALE_X, &v) == RET_OK) { scale_x = value_float(&v); } if (widget_get_prop(widget, WIDGET_PROP_SCALE_Y, &v) == RET_OK) { scale_y = value_float(&v); } params->x_from = scale_x; params->y_from = scale_y; params->x_to = scale_x; params->y_to = scale_y; } else { float_t value = 0; const char* prop_name = p->params.type; prop_params_t* params = &p->params.u.prop; if (widget_get_prop(widget, prop_name, &v) == RET_OK) { value = value_float(&v); } params->from = value; params->to = value; } return RET_OK; } static ret_t parser_on_param(func_call_parser_t* parser, const char* name, const char* value) { widget_animator_parser_t* p = (widget_animator_parser_t*)parser; const char* type = p->params.type; if (tk_str_eq(type, "move")) { move_params_t* move = &p->params.u.move; if (tk_str_eq(name, "x_from")) { move->x_from = tk_atoi(value); return RET_OK; } else if (tk_str_eq(name, "y_from")) { move->y_from = tk_atoi(value); return RET_OK; } else if (tk_str_eq(name, "x_to")) { move->x_to = tk_atoi(value); return RET_OK; } else if (tk_str_eq(name, "y_to")) { move->y_to = tk_atoi(value); return RET_OK; } } else if (tk_str_eq(type, "scale")) { scale_params_t* scale = &p->params.u.scale; if (tk_str_eq(name, "x_from")) { scale->x_from = tk_atof(value); return RET_OK; } else if (tk_str_eq(name, "y_from")) { scale->y_from = tk_atof(value); return RET_OK; } else if (tk_str_eq(name, "x_to")) { scale->x_to = tk_atof(value); return RET_OK; } else if (tk_str_eq(name, "y_to")) { scale->y_to = tk_atof(value); return RET_OK; } } else { prop_params_t* v = &p->params.u.prop; if (tk_str_eq(name, "from")) { v->from = tk_atof(value); return RET_OK; } else if (tk_str_eq(name, "to")) { v->to = tk_atof(value); return RET_OK; } } switch (name[0]) { case 'y': /*yoyo_times*/ { p->params.yoyo_times = tk_atoi(value); break; } case 't': /*time_scale*/ { p->params.time_scale = tk_atof(value); break; } case 'n': /*name*/ { tk_strncpy(p->params.name, value, TK_NAME_LEN); break; } case 'r': /*repeat_times*/ { if (tk_str_eq(name, "repeat_times")) { p->params.repeat_times = tk_atoi(value); } else if (tk_str_eq(name, "relayout")) { p->params.relayout = tk_atob(value); } break; } case 'd': /*duration|delay*/ { if (tk_str_eq(name, "delay")) { p->params.delay = tk_atoi(value); } else if (tk_str_eq(name, "duration")) { p->params.duration = tk_atoi(value); } break; } case 'a': /*auto_start|auto_destroy*/ { if (tk_str_eq(name, "auto_start")) { p->params.auto_start = tk_atob(value); } else if (tk_str_eq(name, "auto_destroy")) { p->params.auto_destroy = tk_atob(value); } break; } case 'e': { const key_type_value_t* easing = easing_type_find(value); p->params.easing = easing != NULL ? (int32_t)(easing->value) : -1; break; } default: break; } return RET_OK; } static ret_t widget_animator_parser_parse(widget_animator_parser_t* parser, const char* str, widget_t* widget) { memset(parser, 0x00, sizeof(*parser)); func_call_parser_init(&(parser->base), str, strlen(str)); parser->params.delay = 0; parser->params.duration = 500; parser->params.yoyo_times = -1; parser->params.repeat_times = -1; parser->params.relayout = FALSE; parser->params.auto_start = TRUE; parser->params.auto_destroy = TRUE; parser->params.time_scale = 1; parser->params.easing = EASING_SIN_INOUT; parser->params.widget = widget; parser->base.on_name = parser_on_name; parser->base.on_param = parser_on_param; parser->base.on_done = NULL; return func_call_parser_parse(&(parser->base)); } static ret_t widget_animator_start_animator(void* ctx, event_t* evt) { widget_animator_t* wa = (widget_animator_t*)ctx; widget_animator_start(wa); return RET_REMOVE; } widget_animator_t* widget_animator_create(widget_t* widget, const char* params) { uint32_t delay = 0; uint32_t easing = 0; uint32_t duration = 0; const char* type = NULL; widget_animator_t* wa = NULL; widget_animator_parser_t parser; return_value_if_fail(params != NULL && widget != NULL, NULL); widget_animator_parser_parse(&parser, params, widget); delay = parser.params.delay; easing = parser.params.easing; duration = parser.params.duration; type = parser.params.type; if (tk_str_eq(type, "move")) { move_params_t* move = &parser.params.u.move; wa = widget_animator_move_create(widget, duration, delay, (easing_type_t)easing); return_value_if_fail(wa != NULL, NULL); widget_animator_move_set_params(wa, move->x_from, move->y_from, move->x_to, move->y_to); } else if (tk_str_eq(type, "scale")) { scale_params_t* scale = &parser.params.u.scale; wa = widget_animator_scale_create(widget, duration, delay, (easing_type_t)easing); return_value_if_fail(wa != NULL, NULL); widget_animator_scale_set_params(wa, scale->x_from, scale->y_from, scale->x_to, scale->y_to); } else { const char* prop_name = parser.params.type; prop_params_t* param = &parser.params.u.prop; wa = widget_animator_prop_create(widget, duration, delay, (easing_type_t)easing, prop_name); return_value_if_fail(wa != NULL, NULL); widget_animator_prop_set_params(wa, param->from, param->to); } func_call_parser_deinit(&(parser.base)); if (wa != NULL) { if (parser.params.yoyo_times >= 0) { widget_animator_set_yoyo(wa, parser.params.yoyo_times); } if (parser.params.repeat_times >= 0) { widget_animator_set_repeat(wa, parser.params.repeat_times); } if (parser.params.auto_start) { if (widget->loading) { /* 加载控件中启动动画的情况,为了确保不受注册的回调事件顺序影响,所以等控件加载完成后,再启动动画 */ widget_on(widget, EVT_WIDGET_LOAD, widget_animator_start_animator, wa); } else { /* 加载控件完成后,用户通过代码 set_prop 注册动画的情况 */ widget_animator_start(wa); } } widget_animator_set_relayout(wa, parser.params.relayout); widget_animator_set_time_scale(wa, parser.params.time_scale); widget_animator_set_destroy_when_done(wa, parser.params.auto_destroy); if (parser.params.name[0]) { widget_animator_set_name(wa, parser.params.name); } else { widget_animator_set_name(wa, parser.params.type); } } return wa; } #endif /*WITHOUT_WIDGET_ANIMATOR*/
0
repos/awtk/src
repos/awtk/src/widget_animators/widget_animator_value.h
/** * File: widget_animator_prop.h * Author: AWTK Develop Team * Brief: animate widget by change its value(just wrap widget_animator_prop) * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-05-16 Li XianJing <[email protected]> created * */ #ifndef TK_WIDGET_ANIMATOR_VALUE_H #define TK_WIDGET_ANIMATOR_VALUE_H #include "widget_animators/widget_animator_prop.h" BEGIN_C_DECLS #define widget_animator_value_create(widget, duration, delay, easing) \ widget_animator_prop_create(widget, duration, delay, easing, WIDGET_PROP_VALUE) #define widget_animator_value_set_params widget_animator_prop_set_params END_C_DECLS #endif /*TK_WIDGET_ANIMATOR_VALUE_H*/
0
repos/awtk/src
repos/awtk/src/widget_animators/widget_animator_scroll.h
/** * File: widget_animator_scroll.h * Author: AWTK Develop Team * Brief: animate widget by change its xoffset/yoffset. * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-05-15 Li XianJing <[email protected]> created * */ #ifndef TK_WIDGET_ANIMATOR_SCROLL_H #define TK_WIDGET_ANIMATOR_SCROLL_H #include "base/widget_animator.h" BEGIN_C_DECLS /** * @class widget_animator_scroll_t * 滚动控件的动画。 * 本动画也可以用widget_animator_prop2实现,但滚动控件需要访问内部数据结构,出于可读性考虑保留独立实现。 */ typedef struct _widget_animator_scroll_t { widget_animator_t base; xy_t x_to; xy_t y_to; xy_t x_from; xy_t y_from; } widget_animator_scroll_t; /** * @method widget_animator_scroll_create * 创建动画对象。 * @param {widget_t*} widget 控件对象。 * @param {uint32_t} duration 动画持续时间(毫秒)。 * @param {uint32_t} delay 动画执行时间(毫秒)。 * @param {easing_type_t} easing 插值函数类型。 * * @return {widget_animator_t*} 成功返回动画对象,失败返回NULL。 */ widget_animator_t* widget_animator_scroll_create(widget_t* widget, uint32_t duration, uint32_t delay, easing_type_t easing); /** * @method widget_animator_scroll_set_params * 设置动画对象的参数。 * @param {widget_animator_t*} animator 动画对象本身。 * @param {xy_t} x_from x起点值。 * @param {xy_t} y_from y起点值。 * @param {xy_t} x_to x终点值。 * @param {xy_t} y_to y终点值。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t widget_animator_scroll_set_params(widget_animator_t* animator, xy_t x_from, xy_t y_from, xy_t x_to, xy_t y_to); END_C_DECLS #endif /*TK_WIDGET_ANIMATOR_SCROLL_H*/
0
repos/awtk/src
repos/awtk/src/widget_animators/widget_animator_prop2.c
/** * File: widget_animator_prop2.h * Author: AWTK Develop Team * Brief: animate widget by change its 2 props. * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-12-11 Li XianJing <[email protected]> created * */ #include "tkc/mem.h" #include "tkc/utils.h" #include "widget_animators/widget_animator_prop2.h" static ret_t widget_animator_prop2_update(widget_animator_t* animator, float_t percent) { value_t v; widget_animator_prop2_t* prop2 = (widget_animator_prop2_t*)animator; return_value_if_fail(prop2 != NULL, RET_BAD_PARAMS); if (prop2->to1 != prop2->from1) { value_set_double(&v, prop2->from1 + (prop2->to1 - prop2->from1) * percent); widget_set_prop(animator->widget, prop2->prop1_name, &v); } if (prop2->to2 != prop2->from2) { value_set_double(&v, prop2->from2 + (prop2->to2 - prop2->from2) * percent); widget_set_prop(animator->widget, prop2->prop2_name, &v); } return RET_OK; } widget_animator_t* widget_animator_prop2_create(widget_t* widget, uint32_t duration, uint32_t delay, easing_type_t easing, const char* prop1_name, const char* prop2_name) { widget_animator_t* animator = NULL; widget_animator_prop2_t* prop2 = NULL; return_value_if_fail(widget != NULL && duration > 0 && prop1_name != NULL && prop2_name != NULL, NULL); animator = (widget_animator_t*)TKMEM_ZALLOC(widget_animator_prop2_t); return_value_if_fail(animator != NULL, NULL); return_value_if_fail( widget_animator_init(animator, widget, duration, delay, easing_get(easing)) == RET_OK, NULL); prop2 = (widget_animator_prop2_t*)animator; animator->update = widget_animator_prop2_update; tk_strncpy(prop2->prop1_name, prop1_name, TK_NAME_LEN); tk_strncpy(prop2->prop2_name, prop2_name, TK_NAME_LEN); return animator; } ret_t widget_animator_prop2_set_params(widget_animator_t* animator, double from1, double from2, double to1, double to2) { widget_animator_prop2_t* prop2 = (widget_animator_prop2_t*)animator; return_value_if_fail(prop2 != NULL, RET_BAD_PARAMS); prop2->to1 = to1; prop2->to2 = to2; prop2->from1 = from1; prop2->from2 = from2; return RET_OK; }
0
repos/awtk/src
repos/awtk/src/widget_animators/widget_animator_rotation.h
/** * File: widget_animator_rotation.h * Author: AWTK Develop Team * Brief: animate widget by change its rotation(just wrap widget_animator_prop) * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-05-16 Li XianJing <[email protected]> created * */ #ifndef TK_WIDGET_ANIMATOR_ROTATION_H #define TK_WIDGET_ANIMATOR_ROTATION_H #include "widget_animators/widget_animator_prop.h" BEGIN_C_DECLS #define widget_animator_rotation_create(widget, duration, delay, easing) \ widget_animator_prop_create(widget, duration, delay, easing, WIDGET_PROP_ROTATION) #define widget_animator_rotation_set_params widget_animator_prop_set_params END_C_DECLS #endif /*TK_WIDGET_ANIMATOR_ROTATION_H*/
0
repos/awtk/src
repos/awtk/src/widget_animators/widget_animator_move.h
/** * File: widget_animator_move.h * Author: AWTK Develop Team * Brief: animate widget by change its x/y(just wrap widget_animator_prop2) * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-05-16 Li XianJing <[email protected]> created * */ #ifndef TK_WIDGET_ANIMATOR_MOVE_H #define TK_WIDGET_ANIMATOR_MOVE_H #include "widget_animators/widget_animator_prop2.h" BEGIN_C_DECLS #define widget_animator_move_create(widget, duration, delay, easing) \ widget_animator_prop2_create(widget, duration, delay, easing, WIDGET_PROP_X, WIDGET_PROP_Y) #define widget_animator_move_set_params widget_animator_prop2_set_params END_C_DECLS #endif /*TK_WIDGET_ANIMATOR_MOVE_H*/
0
repos/awtk/src
repos/awtk/src/native_window/native_window_sdl.h
/** * File: native_window_sdl.h * Author: AWTK Develop Team * Brief: native window sdl * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-07-21 Li XianJing <[email protected]> created * */ #ifndef TK_NATIVE_WINDOW_SDL_H #define TK_NATIVE_WINDOW_SDL_H #include "base/native_window.h" BEGIN_C_DECLS ret_t native_window_sdl_deinit(void); ret_t native_window_sdl_init(bool_t shared, uint32_t w, uint32_t h); END_C_DECLS #endif /*TK_NATIVE_WINDOW_SDL_H*/
0
repos/awtk/src
repos/awtk/src/native_window/native_window_sdl.c
/** * File: native_window_sdl.h * Author: AWTK Develop Team * Brief: native window sdl * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-07-21 Li XianJing <[email protected]> created * */ #include <SDL.h> #include "base/system_info.h" #include "base/window_manager.h" #ifdef WITH_GPU_GL #ifndef WITHOUT_GLAD #include "glad/glad.h" #else #ifdef IOS #include <OpenGLES/gltypes.h> #include <OpenGLES/ES2/gl.h> #include <OpenGLES/ES2/glext.h> #define GL_ALPHA_TEST 0x0BC0 #else #include <SDL_opengl.h> #include <SDL_opengl_glext.h> #endif /*IOS*/ #endif /*WITHOUT_GLAD*/ #endif /*WITH_GPU_GL*/ #include "tkc/rect.h" #include "lcd/lcd_sdl2.h" #include "lcd/lcd_nanovg.h" #include "lcd/lcd_sdl2_mono.h" #include "base/native_window.h" typedef struct _native_window_sdl_t { native_window_t native_window; bool_t is_init; SDL_GLContext context; SDL_Renderer* render; SDL_Window* window; canvas_t canvas; SDL_Cursor* cursor; SDL_Surface* cursor_surface; } native_window_sdl_t; static native_window_t* s_shared_win = NULL; #define NATIVE_WINDOW_SDL(win) ((native_window_sdl_t*)(win)) static ret_t native_window_sdl_move(native_window_t* win, xy_t x, xy_t y) { int oldx = 0; int oldy = 0; native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); win->rect.x = x; win->rect.y = y; SDL_GetWindowPosition(sdl->window, &oldx, &oldy); if (oldx != x || oldy != y) { SDL_SetWindowPosition(sdl->window, x, y); } return RET_OK; } static ret_t native_window_sdl_resize(native_window_t* win, wh_t w, wh_t h) { lcd_t* lcd = NULL; ret_t ret = RET_OK; native_window_info_t info; native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); lcd_orientation_t lcd_orientation = system_info()->lcd_orientation; return_value_if_fail(sdl != NULL, RET_BAD_PARAMS); lcd = sdl->canvas.lcd; native_window_get_info(win, &info); win->rect.w = w; win->rect.h = h; #if !defined(ANDROID) && !defined(IOS) if (w != info.w || h != info.h) { #ifdef WIN32 w = w * win->ratio; h = h * win->ratio; #endif /*WIN32*/ SDL_SetWindowSize(sdl->window, w, h); } #endif /*ANDROID*/ if (lcd != NULL && (lcd->w != w || lcd->h != h)) { ret = lcd_resize(lcd, w, h, 0); } if (lcd_orientation != LCD_ORIENTATION_0) { lcd_set_orientation(lcd, LCD_ORIENTATION_0, lcd_orientation); native_window_set_orientation(win, LCD_ORIENTATION_0, lcd_orientation); } return ret; } static ret_t native_window_sdl_set_orientation(native_window_t* win, lcd_orientation_t old_orientation, lcd_orientation_t new_orientation) { wh_t w, h; native_window_info_t info; native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); return_value_if_fail(sdl != NULL, RET_BAD_PARAMS); native_window_get_info(win, &info); w = info.w; h = info.h; if (new_orientation == LCD_ORIENTATION_90 || new_orientation == LCD_ORIENTATION_270) { w = info.h; h = info.w; } win->rect.w = w; win->rect.h = h; return RET_OK; } static ret_t native_window_sdl_minimize(native_window_t* win) { native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); SDL_MinimizeWindow(sdl->window); return RET_OK; } static ret_t native_window_sdl_maximize(native_window_t* win) { native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); SDL_MaximizeWindow(sdl->window); return RET_OK; } static ret_t native_window_sdl_restore(native_window_t* win) { native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); SDL_RestoreWindow(sdl->window); return RET_OK; } static ret_t native_window_sdl_center(native_window_t* win) { native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); SDL_SetWindowPosition(sdl->window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); return RET_OK; } static ret_t native_window_sdl_show_border(native_window_t* win, bool_t show) { native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); SDL_SetWindowBordered(sdl->window, show); return RET_OK; } static ret_t native_window_sdl_set_fullscreen(native_window_t* win, bool_t fullscreen) { native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); if (fullscreen) { SDL_SetWindowFullscreen(sdl->window, SDL_WINDOW_FULLSCREEN_DESKTOP); } else { SDL_SetWindowFullscreen(sdl->window, 0); } return RET_OK; } static ret_t native_window_sdl_close(native_window_t* win) { native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); lcd_t* lcd = sdl->canvas.lcd; canvas_reset(&(sdl->canvas)); lcd_destroy(lcd); if (sdl->render != NULL) { SDL_DestroyRenderer(sdl->render); } if (sdl->context != NULL) { SDL_GL_DeleteContext(sdl->context); } if (sdl->window != NULL) { SDL_DestroyWindow(sdl->window); } sdl->render = NULL; sdl->window = NULL; sdl->context = NULL; SDL_Quit(); return RET_OK; } static canvas_t* native_window_sdl_get_canvas(native_window_t* win) { native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); return &(sdl->canvas); } static ret_t native_window_sdl_gl_make_current(native_window_t* win) { #ifdef WITH_GPU_GL int fw = 0; int fh = 0; native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); SDL_Window* window = sdl->window; SDL_GL_MakeCurrent(window, sdl->context); SDL_GL_GetDrawableSize(window, &fw, &fh); glViewport(0, 0, fw, fh); if (!sdl->is_init) { sdl->is_init = TRUE; glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); } else { glClear(GL_STENCIL_BUFFER_BIT); } #endif /*WITH_GPU_GL*/ return RET_OK; } static ret_t native_window_sdl_swap_buffer(native_window_t* win) { #ifdef WITH_GPU_GL native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); SDL_GL_SwapWindow(sdl->window); #else #endif /*WITH_GPU_GL*/ return RET_OK; } extern ret_t tk_quit(); static ret_t native_window_sdl_preprocess_event(native_window_t* win, event_t* e) { #if defined(ANDROID) if (e->type == EVT_POINTER_DOWN || e->type == EVT_POINTER_MOVE || e->type == EVT_CLICK || e->type == EVT_POINTER_UP || e->type == EVT_CONTEXT_MENU) { pointer_event_t* evt = pointer_event_cast(e); evt->x /= win->ratio; evt->y /= win->ratio; } else if (e->type == EVT_KEY_DOWN) { key_event_t* evt = key_event_cast(e); if (evt->key == TK_KEY_AC_BACK) { window_manager_back(window_manager()); if (widget_count_children(window_manager()) == 0) { tk_quit(); } } } #endif /*ANDROID*/ return RET_OK; } static ret_t native_window_sdl_get_info(native_window_t* win, native_window_info_t* info) { int ww = 0; int wh = 0; int fw = 0; int fh = 0; int x = 0; int y = 0; native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); SDL_Window* window = sdl->window; SDL_GetWindowPosition(window, &x, &y); SDL_GetWindowSize(window, &ww, &wh); SDL_GL_GetDrawableSize(window, &fw, &fh); memset(info, 0x00, sizeof(*info)); info->x = x; info->y = y; #if defined(ANDROID) float dpi = 1; SDL_GetDisplayDPI(0, &dpi, NULL, NULL); float_t ratio = dpi / 160; info->w = ww / ratio; info->h = wh / ratio; info->ratio = ratio; #elif defined(IOS) info->w = ww; info->h = wh; info->ratio = (float_t)fw / (float_t)ww; #else info->w = ww; info->h = wh; info->ratio = (float_t)fw / (float_t)ww; #endif /**/ info->handle = win->handle; win->rect.x = info->x; win->rect.y = info->y; win->rect.w = info->w; win->rect.h = info->h; win->ratio = info->ratio; return RET_OK; } static ret_t calc_cursor_hot_spot(const char* name, bitmap_t* img, point_t* p) { bool_t midpoint = FALSE; return_value_if_fail(name != NULL && img != NULL && p != NULL, RET_BAD_PARAMS); if (tk_str_eq(WIDGET_CURSOR_EDIT, name) || tk_str_eq(WIDGET_CURSOR_WAIT, name) || tk_str_eq(WIDGET_CURSOR_CROSS, name) || tk_str_eq(WIDGET_CURSOR_NO, name) || tk_str_eq(WIDGET_CURSOR_SIZENWSE, name) || tk_str_eq(WIDGET_CURSOR_SIZENESW, name) || tk_str_eq(WIDGET_CURSOR_SIZEWE, name) || tk_str_eq(WIDGET_CURSOR_SIZENS, name) || tk_str_eq(WIDGET_CURSOR_SIZEALL, name)) { midpoint = TRUE; } if (midpoint) { p->x = img->w / 2; p->y = img->h / 2; } else { p->x = 0; p->y = 0; } return RET_OK; } static ret_t native_window_sdl_cursor_from_bitmap(native_window_t* win, bitmap_t* img, point_t* p) { Uint32 depth = 32; uint8_t* data = NULL; uint32_t w = img->w; uint32_t h = img->h; uint32_t rmask = 0; uint32_t gmask = 0; uint32_t bmask = 0; uint32_t amask = 0; uint32_t pitch = 4 * w; native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); if (img->format == BITMAP_FMT_BGRA8888) { bmask = 0x000000ff; gmask = 0x0000ff00; rmask = 0x00ff0000; amask = 0xff000000; } else if (img->format == BITMAP_FMT_RGBA8888) { rmask = 0x000000ff; gmask = 0x0000ff00; bmask = 0x00ff0000; amask = 0xff000000; } else { /* *assert(!"not supported format!"); */ return RET_FAIL; } if (sdl->cursor_surface != NULL) { SDL_FreeSurface(sdl->cursor_surface); sdl->cursor_surface = NULL; } data = bitmap_lock_buffer_for_read(img); return_value_if_fail(data != NULL, RET_BAD_PARAMS); sdl->cursor_surface = SDL_CreateRGBSurfaceFrom(data, w, h, depth, pitch, rmask, gmask, bmask, amask); bitmap_unlock_buffer(img); return_value_if_fail(sdl->cursor_surface != NULL, RET_OOM); sdl->cursor = SDL_CreateColorCursor(sdl->cursor_surface, p->x, p->y); SDL_SetCursor(sdl->cursor); return RET_OK; } static int map_to_sdl_cursor(const char* name) { if (tk_str_eq(WIDGET_CURSOR_DEFAULT, name)) { return SDL_SYSTEM_CURSOR_ARROW; } else if (tk_str_eq(WIDGET_CURSOR_EDIT, name)) { return SDL_SYSTEM_CURSOR_IBEAM; } else if (tk_str_eq(WIDGET_CURSOR_HAND, name)) { return SDL_SYSTEM_CURSOR_HAND; } else if (tk_str_eq(WIDGET_CURSOR_WAIT, name)) { return SDL_SYSTEM_CURSOR_WAIT; } else if (tk_str_eq(WIDGET_CURSOR_CROSS, name)) { return SDL_SYSTEM_CURSOR_CROSSHAIR; } else if (tk_str_eq(WIDGET_CURSOR_NO, name)) { return SDL_SYSTEM_CURSOR_NO; } else if (tk_str_eq(WIDGET_CURSOR_SIZENWSE, name)) { return SDL_SYSTEM_CURSOR_SIZENWSE; } else if (tk_str_eq(WIDGET_CURSOR_SIZENESW, name)) { return SDL_SYSTEM_CURSOR_SIZENESW; } else if (tk_str_eq(WIDGET_CURSOR_SIZEWE, name)) { return SDL_SYSTEM_CURSOR_SIZEWE; } else if (tk_str_eq(WIDGET_CURSOR_SIZENS, name)) { return SDL_SYSTEM_CURSOR_SIZENS; } else if (tk_str_eq(WIDGET_CURSOR_SIZEALL, name)) { return SDL_SYSTEM_CURSOR_SIZEALL; } return -1; } static ret_t native_window_sdl_set_cursor(native_window_t* win, const char* name, bitmap_t* img) { native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); if (sdl->cursor != NULL) { SDL_FreeCursor(sdl->cursor); sdl->cursor = NULL; } if (img != NULL) { point_t hot_spot = {0, 0}; calc_cursor_hot_spot(name, img, &hot_spot); return native_window_sdl_cursor_from_bitmap(win, img, &hot_spot); } else if (system_info()->app_type == APP_DESKTOP) { int system_cursor = map_to_sdl_cursor(name); if (system_cursor >= 0) { sdl->cursor = SDL_CreateSystemCursor((SDL_SystemCursor)system_cursor); SDL_SetCursor(sdl->cursor); return RET_OK; } } return RET_FAIL; } static const native_window_vtable_t s_native_window_vtable = { .type = "native_window_sdl", .move = native_window_sdl_move, .resize = native_window_sdl_resize, .set_orientation = native_window_sdl_set_orientation, .minimize = native_window_sdl_minimize, .maximize = native_window_sdl_maximize, .restore = native_window_sdl_restore, .center = native_window_sdl_center, .show_border = native_window_sdl_show_border, .set_fullscreen = native_window_sdl_set_fullscreen, .get_info = native_window_sdl_get_info, .preprocess_event = native_window_sdl_preprocess_event, .swap_buffer = native_window_sdl_swap_buffer, .gl_make_current = native_window_sdl_gl_make_current, .set_cursor = native_window_sdl_set_cursor, .get_canvas = native_window_sdl_get_canvas}; static ret_t native_window_sdl_set_prop(tk_object_t* obj, const char* name, const value_t* v) { native_window_t* win = NATIVE_WINDOW(obj); if (tk_str_eq(NATIVE_WINDOW_PROP_SIZE, name)) { rect_t* r = (rect_t*)value_pointer(v); native_window_sdl_resize(win, r->w, r->h); return RET_OK; } else if (tk_str_eq(NATIVE_WINDOW_PROP_POSITION, name)) { rect_t* r = (rect_t*)value_pointer(v); native_window_sdl_move(win, r->x, r->y); return RET_OK; } else if (tk_str_eq(NATIVE_WINDOW_PROP_TITLE, name)) { SDL_Window* sdlwin = (SDL_Window*)(win->handle); const char* app_name = value_str(v); SDL_SetWindowTitle(sdlwin, app_name); system_info_set_app_name(system_info(), app_name); return RET_OK; } return RET_NOT_FOUND; } static ret_t native_window_sdl_get_prop(tk_object_t* obj, const char* name, value_t* v) { native_window_t* win = NATIVE_WINDOW(obj); if (tk_str_eq(NATIVE_WINDOW_PROP_SIZE, name) || tk_str_eq(NATIVE_WINDOW_PROP_POSITION, name)) { int x = 0; int y = 0; int w = 0; int h = 0; SDL_Window* sdlwin = (SDL_Window*)(win->handle); SDL_GetWindowSize(sdlwin, &w, &h); SDL_GetWindowPosition(sdlwin, &x, &y); win->rect = rect_init(x, y, w, h); value_set_pointer(v, &(win->rect)); return RET_OK; } return RET_NOT_FOUND; } static ret_t native_window_sdl_on_destroy(tk_object_t* obj) { log_debug("Close native window.\n"); native_window_sdl_close(NATIVE_WINDOW(obj)); return RET_OK; } static ret_t native_window_sdl_exec(tk_object_t* obj, const char* cmd, const char* args) { #ifdef WITH_GPU native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(obj); if (tk_str_eq(cmd, "reset_canvas")) { canvas_t* c = &(sdl->canvas); vgcanvas_t* vg = canvas_get_vgcanvas(c); vgcanvas_reset(vg); return RET_OK; } #endif /*WITH_GPU*/ return RET_NOT_FOUND; } static const object_vtable_t s_native_window_sdl_vtable = { .type = "native_window_sdl", .desc = "native_window_sdl", .size = sizeof(native_window_sdl_t), .get_prop = native_window_sdl_get_prop, .set_prop = native_window_sdl_set_prop, .exec = native_window_sdl_exec, .on_destroy = native_window_sdl_on_destroy}; static native_window_t* native_window_create_internal(const char* title, uint32_t flags, int32_t x, int32_t y, uint32_t w, uint32_t h) { lcd_t* lcd = NULL; native_window_info_t info; tk_object_t* obj = tk_object_create(&s_native_window_sdl_vtable); native_window_t* win = NATIVE_WINDOW(obj); native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(win); canvas_t* c = &(sdl->canvas); #ifndef NATIVE_WINDOW_NOT_RESIZABLE if (system_info()->app_type == APP_DESKTOP) { flags |= SDL_WINDOW_RESIZABLE; } #endif /*NATIVE_WINDOW_NOT_RESIZABLE*/ #ifndef WITH_NANOVG_SOFT flags |= SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI; #endif /*WITH_NANOVG_SOFT*/ #ifdef NATIVE_WINDOW_BORDERLESS flags |= SDL_WINDOW_BORDERLESS; #endif /*NATIVE_WINDOW_BORDERLESS*/ sdl->window = SDL_CreateWindow(title, x, y, w, h, flags); #ifdef WITH_NANOVG_SOFT sdl->render = SDL_CreateRenderer(sdl->window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); if (sdl->render == NULL) { sdl->render = SDL_CreateRenderer(sdl->window, -1, SDL_RENDERER_SOFTWARE); } #endif /*WITH_NANOVG_SOFT*/ win->handle = sdl->window; win->vt = &s_native_window_vtable; #ifdef WITH_GPU_GL sdl->context = SDL_GL_CreateContext(sdl->window); SDL_GL_SetSwapInterval(1); #endif /*WITH_GPU_GL*/ if (native_window_get_info(win, &info) == RET_OK) { w = info.w; h = info.h; } win->rect = rect_init(x, y, w, h); #ifdef WITH_LCD_MONO lcd = lcd_sdl2_mono_init(sdl->render); #else #ifdef WITH_NANOVG_SOFT lcd = lcd_sdl2_init(sdl->render); #elif WITH_NANOVG_GPU lcd = lcd_nanovg_init(win); #elif WITH_NANOVG_BGFX lcd = lcd_nanovg_init(win); #endif /*WITH_NANOVG_SOFT*/ #endif /*WITH_LCD_MONO*/ canvas_init(c, lcd, font_manager()); return win; } native_window_t* native_window_create(widget_t* widget) { int32_t x = widget->x; int32_t y = widget->y; int32_t w = widget->w; int32_t h = widget->h; native_window_t* nw = NULL; if (s_shared_win != NULL) { tk_object_ref(TK_OBJECT(s_shared_win)); nw = s_shared_win; } else { str_t str; str_init(&str, 0); str_from_wstr(&str, widget->text.str); nw = native_window_create_internal(str.str, 0, x, y, w, h); str_reset(&str); } widget_set_prop_pointer(widget, WIDGET_PROP_NATIVE_WINDOW, nw); return nw; } #ifdef WITH_GPU_GL static ret_t sdl_init_gl(void) { SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest"); #ifdef WITH_GPU_GL2 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); #elif defined(WITH_GPU_GL3) SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); #endif log_debug("Init opengl done.\n"); return RET_OK; } #endif /*WITH_GPU_GL*/ ret_t native_window_sdl_init(bool_t shared, uint32_t w, uint32_t h) { const char* title = system_info()->app_name; SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER, "1"); SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_AUDIO) != 0) { log_debug("Failed to initialize SDL: %s", SDL_GetError()); exit(0); return RET_FAIL; } #ifdef WITH_GPU_GL sdl_init_gl(); #endif /*WITH_GPU_GL*/ SDL_StopTextInput(); if (shared) { int32_t x = SDL_WINDOWPOS_UNDEFINED; int32_t y = SDL_WINDOWPOS_UNDEFINED; s_shared_win = native_window_create_internal(title, 0, x, y, w, h); s_shared_win->shared = TRUE; } SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE); return RET_OK; } ret_t native_window_sdl_deinit(void) { if (s_shared_win != NULL) { native_window_sdl_t* sdl = NATIVE_WINDOW_SDL(s_shared_win); if (sdl->cursor_surface != NULL) { SDL_FreeSurface(sdl->cursor_surface); sdl->cursor_surface = NULL; } tk_object_unref(TK_OBJECT(s_shared_win)); s_shared_win = NULL; } return RET_OK; }
0
repos/awtk/src
repos/awtk/src/native_window/native_window_fb_gl.h
/** * File: native_window_fb_gl.h * Author: AWTK Develop Team * Brief: native window for egl * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2019-10-31 Lou ZhiMing <[email protected]> created * */ #ifndef TK_NATIVE_WINDOW_FB_GL_H #define TK_NATIVE_WINDOW_FB_GL_H #include "base/lcd.h" #include "base/native_window.h" BEGIN_C_DECLS typedef ret_t (*native_window_destroy_t)(native_window_t* win); ret_t native_window_fb_gl_deinit(void); native_window_t* native_window_fb_gl_init(uint32_t w, uint32_t h, float_t ratio); ret_t native_window_fb_gl_set_swap_buffer_func(native_window_t* win, native_window_swap_buffer_t swap_buffer); ret_t native_window_fb_gl_set_make_current_func(native_window_t* win, native_window_gl_make_current_t make_current); ret_t native_window_fb_gl_set_destroy_func(native_window_t* win, native_window_destroy_t destroy); lcd_t* native_window_get_lcd(native_window_t* win); END_C_DECLS #endif /*TK_NATIVE_WINDOW_FB_GL_H*/
0
repos/awtk/src
repos/awtk/src/native_window/native_window_raw.h
/** * File: native_window_raw.h * Author: AWTK Develop Team * Brief: native window raw * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-07-25 Li XianJing <[email protected]> created * */ #ifndef TK_NATIVE_WINDOW_RAW_H #define TK_NATIVE_WINDOW_RAW_H #include "base/lcd.h" #include "base/native_window.h" BEGIN_C_DECLS ret_t native_window_raw_deinit(void); ret_t native_window_raw_init(lcd_t* lcd); END_C_DECLS #endif /*TK_NATIVE_WINDOW_RAW_H*/
0
repos/awtk/src
repos/awtk/src/native_window/native_window_fb_gl.c
/** * File: native_window_fb_gl.c * Author: AWTK Develop Team * Brief: native window for egl * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2019-10-31 Lou ZhiMing <[email protected]> created * */ #ifdef WITH_GPU_GL #ifndef WITHOUT_GLAD #include "glad/glad.h" #define loadGL gladLoadGL #else #define loadGL() #endif /*WITHOUT_GLAD*/ #endif /*WITH_GPU_GL*/ #include "base/widget.h" #include "lcd/lcd_nanovg.h" #include "base/widget_consts.h" #include "base/window_manager.h" #include "native_window/native_window_fb_gl.h" typedef struct _native_window_fb_gl_t { native_window_t native_window; uint32_t w; uint32_t h; float_t ratio; native_window_swap_buffer_t swap_buffer; native_window_gl_make_current_t make_current; native_window_destroy_t destroy; canvas_t canvas; } native_window_fb_gl_t; static native_window_t* s_shared_win = NULL; #define NATIVE_WINDOW_FB_GL(win) ((native_window_fb_gl_t*)(win)) ret_t native_window_fb_gl_set_swap_buffer_func(native_window_t* win, native_window_swap_buffer_t swap_buffer) { native_window_fb_gl_t* fb_gl = NATIVE_WINDOW_FB_GL(win); return_value_if_fail(fb_gl != NULL && swap_buffer != NULL, RET_BAD_PARAMS); fb_gl->swap_buffer = swap_buffer; return RET_OK; } ret_t native_window_fb_gl_set_make_current_func(native_window_t* win, native_window_gl_make_current_t make_current) { native_window_fb_gl_t* fb_gl = NATIVE_WINDOW_FB_GL(win); return_value_if_fail(fb_gl != NULL && make_current != NULL, RET_BAD_PARAMS); fb_gl->make_current = make_current; return RET_OK; } ret_t native_window_fb_gl_set_destroy_func(native_window_t* win, native_window_destroy_t destroy) { native_window_fb_gl_t* fb_gl = NATIVE_WINDOW_FB_GL(win); return_value_if_fail(fb_gl != NULL && destroy != NULL, RET_BAD_PARAMS); fb_gl->destroy = destroy; return RET_OK; } lcd_t* native_window_get_lcd(native_window_t* win) { native_window_fb_gl_t* fb_gl = NATIVE_WINDOW_FB_GL(win); return_value_if_fail(fb_gl != NULL, NULL); return fb_gl->canvas.lcd; } static ret_t native_window_fb_gl_move(native_window_t* win, xy_t x, xy_t y) { return RET_OK; } static ret_t native_window_fg_gl_on_resized_timer(const timer_info_t* info) { widget_t* wm = window_manager(); native_window_t* win = NATIVE_WINDOW(info->ctx); widget_set_need_relayout_children(wm); widget_invalidate_force(wm, NULL); log_debug("on_resized_idle\n"); return RET_REMOVE; } static ret_t native_window_fb_gl_resize(native_window_t* win, wh_t w, wh_t h) { ret_t ret = RET_OK; native_window_info_t info; native_window_fb_gl_t* fb_gl = NATIVE_WINDOW_FB_GL(win); native_window_get_info(win, &info); if (w != info.w || h != info.h) { event_t e = event_init(EVT_NATIVE_WINDOW_RESIZED, NULL); lcd_orientation_t lcd_orientation = system_info()->lcd_orientation; ret = lcd_resize(fb_gl->canvas.lcd, w, h, 0); return_value_if_fail(ret == RET_OK, ret); system_info_set_lcd_w(system_info(), w); system_info_set_lcd_h(system_info(), h); fb_gl->w = win->rect.w = w; fb_gl->h = win->rect.h = h; if (lcd_orientation != LCD_ORIENTATION_0) { lcd_set_orientation(fb_gl->canvas.lcd, LCD_ORIENTATION_0, lcd_orientation); } window_manager_dispatch_native_window_event(window_manager(), &e, win); timer_add(native_window_fg_gl_on_resized_timer, win, 100); } return RET_OK; } static ret_t native_window_fb_gl_set_orientation(native_window_t* win, lcd_orientation_t old_orientation, lcd_orientation_t new_orientation) { wh_t w, h; ret_t ret = RET_OK; native_window_info_t info; native_window_fb_gl_t* fb_gl = NATIVE_WINDOW_FB_GL(win); native_window_get_info(win, &info); w = info.w; h = info.h; if (tk_is_swap_size_by_orientation(old_orientation, new_orientation)) { w = info.h; h = info.w; } fb_gl->w = win->rect.w = w; fb_gl->h = win->rect.h = h; return RET_OK; } static canvas_t* native_window_fb_gl_get_canvas(native_window_t* win) { native_window_fb_gl_t* fb_gl = NATIVE_WINDOW_FB_GL(win); return &(fb_gl->canvas); } static ret_t native_window_fb_gl_get_info(native_window_t* win, native_window_info_t* info) { native_window_fb_gl_t* fb_gl = NATIVE_WINDOW_FB_GL(win); info->x = 0; info->y = 0; info->ratio = fb_gl->ratio; info->w = fb_gl->w; info->h = fb_gl->h; // log_debug("ratio=%f %d %d\n", info->ratio, info->w, info->h); return RET_OK; } static ret_t native_window_fb_gl_swap_buffer(native_window_t* win) { native_window_fb_gl_t* fb_gl = NATIVE_WINDOW_FB_GL(win); if (fb_gl != NULL && fb_gl->swap_buffer != NULL) { return fb_gl->swap_buffer(win); } return RET_OK; } static ret_t native_window_sdl_gl_make_current(native_window_t* win) { native_window_fb_gl_t* fb_gl = NATIVE_WINDOW_FB_GL(win); if (fb_gl != NULL && fb_gl->make_current != NULL) { return fb_gl->make_current(win); } return RET_OK; } static const native_window_vtable_t s_native_window_vtable = { .type = "native_window_fb_gl", .move = native_window_fb_gl_move, .get_info = native_window_fb_gl_get_info, .resize = native_window_fb_gl_resize, .set_orientation = native_window_fb_gl_set_orientation, .swap_buffer = native_window_fb_gl_swap_buffer, .gl_make_current = native_window_sdl_gl_make_current, .get_canvas = native_window_fb_gl_get_canvas}; static ret_t native_window_fb_gl_set_prop(tk_object_t* obj, const char* name, const value_t* v) { return RET_NOT_FOUND; } static ret_t native_window_fb_gl_get_prop(tk_object_t* obj, const char* name, value_t* v) { return RET_NOT_FOUND; } static ret_t native_window_fb_gl_on_destroy(tk_object_t* obj) { native_window_fb_gl_t* fb_gl = NATIVE_WINDOW_FB_GL(obj); lcd_t* lcd = fb_gl->canvas.lcd; canvas_reset(&(fb_gl->canvas)); lcd_destroy(lcd); if (fb_gl->destroy != NULL) { return fb_gl->destroy(NATIVE_WINDOW(fb_gl)); } return RET_OK; } static const object_vtable_t s_native_window_fb_gl_vtable = { .type = "native_window_fb_gl", .desc = "native_window_fb_gl", .size = sizeof(native_window_fb_gl_t), .get_prop = native_window_fb_gl_get_prop, .set_prop = native_window_fb_gl_set_prop, .on_destroy = native_window_fb_gl_on_destroy}; static native_window_t* native_window_create_internal(uint32_t w, uint32_t h, float_t ratio) { lcd_t* lcd = NULL; tk_object_t* obj = tk_object_create(&s_native_window_fb_gl_vtable); native_window_t* win = NATIVE_WINDOW(obj); native_window_fb_gl_t* fb_gl = NATIVE_WINDOW_FB_GL(win); return_value_if_fail(fb_gl != NULL, NULL); fb_gl->w = w; fb_gl->h = h; fb_gl->ratio = ratio; win->shared = TRUE; win->vt = &s_native_window_vtable; win->rect = rect_init(0, 0, w, h); loadGL(); canvas_t* c = &(fb_gl->canvas); #if WITH_NANOVG_GPU lcd = lcd_nanovg_init(win); #endif canvas_init(c, lcd, font_manager()); return win; } native_window_t* native_window_create(widget_t* widget) { native_window_t* nw = s_shared_win; return_value_if_fail(nw != NULL, NULL); widget_set_prop_pointer(widget, WIDGET_PROP_NATIVE_WINDOW, nw); return nw; } native_window_t* native_window_fb_gl_init(uint32_t w, uint32_t h, float_t ratio) { s_shared_win = native_window_create_internal(w, h, ratio); return s_shared_win; } ret_t native_window_fb_gl_deinit(void) { if (s_shared_win != NULL) { tk_object_unref(TK_OBJECT(s_shared_win)); s_shared_win = NULL; } return RET_OK; }
0
repos/awtk/src
repos/awtk/src/native_window/native_window_raw.c
/** * File: native_window_raw.h * Author: AWTK Develop Team * Brief: native window raw * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-07-25 Li XianJing <[email protected]> created * */ #include "base/widget.h" #include "base/window_manager.h" #include "native_window/native_window_raw.h" typedef struct _native_window_raw_t { native_window_t native_window; canvas_t canvas; } native_window_raw_t; static native_window_t* s_shared_win = NULL; #define NATIVE_WINDOW_RAW(win) ((native_window_raw_t*)(win)) static ret_t native_window_raw_move(native_window_t* win, xy_t x, xy_t y) { return RET_OK; } static ret_t native_window_raw_on_resized_timer(const timer_info_t* info) { widget_t* wm = window_manager(); widget_set_need_relayout_children(wm); widget_invalidate_force(wm, NULL); log_debug("on_resized_idle\n"); return RET_REMOVE; } static ret_t native_window_raw_resize(native_window_t* win, wh_t w, wh_t h) { ret_t ret = RET_OK; native_window_info_t info; native_window_get_info(win, &info); if (w != info.w || h != info.h) { native_window_raw_t* raw = NATIVE_WINDOW_RAW(win); event_t e = event_init(EVT_NATIVE_WINDOW_RESIZED, NULL); lcd_orientation_t lcd_orientation = system_info()->lcd_orientation; ret = lcd_resize(raw->canvas.lcd, w, h, 0); return_value_if_fail(ret == RET_OK, ret); system_info_set_lcd_w(system_info(), w); system_info_set_lcd_h(system_info(), h); win->rect.w = w; win->rect.h = h; if (lcd_orientation != LCD_ORIENTATION_0) { lcd_set_orientation(raw->canvas.lcd, LCD_ORIENTATION_0, lcd_orientation); native_window_set_orientation(win, LCD_ORIENTATION_0, lcd_orientation); } window_manager_dispatch_native_window_event(window_manager(), &e, win); timer_add(native_window_raw_on_resized_timer, win, 100); } return RET_OK; } static ret_t native_window_raw_set_orientation(native_window_t* win, lcd_orientation_t old_orientation, lcd_orientation_t new_orientation) { wh_t w, h; native_window_info_t info; native_window_get_info(win, &info); w = info.w; h = info.h; if (new_orientation == LCD_ORIENTATION_90 || new_orientation == LCD_ORIENTATION_270) { w = info.h; h = info.w; } win->rect.w = w; win->rect.h = h; return RET_OK; } static canvas_t* native_window_raw_get_canvas(native_window_t* win) { native_window_raw_t* raw = NATIVE_WINDOW_RAW(win); return &(raw->canvas); } static ret_t native_window_raw_get_info(native_window_t* win, native_window_info_t* info) { system_info_t* s_info = system_info(); info->x = 0; info->y = 0; info->w = s_info->lcd_w; info->h = s_info->lcd_h; win->ratio = info->ratio = s_info->device_pixel_ratio; log_debug("ratio=%f %d %d\n", info->ratio, info->w, info->h); return RET_OK; } static const native_window_vtable_t s_native_window_vtable = { .type = "native_window_raw", .move = native_window_raw_move, .get_info = native_window_raw_get_info, .resize = native_window_raw_resize, .set_orientation = native_window_raw_set_orientation, .get_canvas = native_window_raw_get_canvas}; static ret_t native_window_raw_set_prop(tk_object_t* obj, const char* name, const value_t* v) { return RET_NOT_FOUND; } static ret_t native_window_raw_get_prop(tk_object_t* obj, const char* name, value_t* v) { return RET_NOT_FOUND; } static ret_t native_window_raw_on_destroy(tk_object_t* obj) { native_window_raw_t* raw = NATIVE_WINDOW_RAW(obj); lcd_t* lcd = raw->canvas.lcd; canvas_reset(&(raw->canvas)); lcd_destroy(lcd); return RET_OK; } static const object_vtable_t s_native_window_raw_vtable = { .type = "native_window_raw", .desc = "native_window_raw", .size = sizeof(native_window_raw_t), .get_prop = native_window_raw_get_prop, .set_prop = native_window_raw_set_prop, .on_destroy = native_window_raw_on_destroy}; static native_window_t* native_window_create_internal(lcd_t* lcd) { tk_object_t* obj = tk_object_create(&s_native_window_raw_vtable); native_window_t* win = NATIVE_WINDOW(obj); native_window_raw_t* raw = NATIVE_WINDOW_RAW(win); return_value_if_fail(raw != NULL, NULL); canvas_t* c = &(raw->canvas); canvas_init(c, lcd, font_manager()); win->shared = TRUE; win->vt = &s_native_window_vtable; win->rect = rect_init(0, 0, lcd_get_width(lcd), lcd_get_height(lcd)); return win; } native_window_t* native_window_create(widget_t* widget) { native_window_t* nw = s_shared_win; return_value_if_fail(nw != NULL, NULL); widget_set_prop_pointer(widget, WIDGET_PROP_NATIVE_WINDOW, nw); return nw; } ret_t native_window_raw_init(lcd_t* lcd) { s_shared_win = native_window_create_internal(lcd); return RET_OK; } ret_t native_window_raw_deinit(void) { return RET_OK; }
0
repos/awtk/src
repos/awtk/src/tkc/rect.h
/** * File: rect.h * Author: AWTK Develop Team * Brief: rect struct and utils functions. * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-01-13 Li XianJing <[email protected]> created * */ #ifndef TK_RECT_H #define TK_RECT_H #include "tkc/types_def.h" BEGIN_C_DECLS /** * @class point_t * @annotation ["scriptable"] * @order -10 * 点。包括一个x坐标和一个y坐标。 */ typedef struct _point_t { /** * @property {xy_t} x * @annotation ["readable"] * x坐标。 */ xy_t x; /** * @property {xy_t} y * @annotation ["readable"] * y坐标。 */ xy_t y; } point_t; /** * @method point_init * 初始化point对象。 * * @param {xy_t} x x坐标。 * @param {xy_t} y y坐标。 * * @return {point_t} 返回point对象。 */ point_t point_init(xy_t x, xy_t y); /** * @class pointf_t * @order -10 * @annotation ["scriptable"] * 点(浮点数)。包括一个x坐标和一个y坐标。 */ typedef struct _pointf_t { /** * @property {float_t} x * @annotation ["readable"] * x坐标。 */ float_t x; /** * @property {float_t} y * @annotation ["readable"] * y坐标。 */ float_t y; } pointf_t; /** * @method pointf_init * 初始化point对象。 * * @param {float_t} x x坐标。 * @param {float_t} y y坐标。 * * @return {pointf_t} 返回point对象。 */ pointf_t pointf_init(float_t x, float_t y); /** * @class rectf_t * @order -10 * @annotation ["scriptable"] * 矩形。包括一个x坐标、y坐标、宽度和高度。 */ typedef struct _rectf_t { /** * @property {float} x * @annotation ["readable", "scriptable"] * x坐标。 */ float x; /** * @property {float} y * @annotation ["readable", "scriptable"] * y坐标。 */ float y; /** * @property {float} w * @annotation ["readable", "scriptable"] * 宽度。 */ float w; /** * @property {float} h * @annotation ["readable", "scriptable"] * 高度。 */ float h; } rectf_t; /** * @method rectf_init * 初始化rectf对象。 * * @param {float} x x坐标。 * @param {float} y y坐标。 * @param {float} w 宽度。 * @param {float} h 高度。 * * @return {rectf_t} 返回rect对象。 */ rectf_t rectf_init(float x, float y, float w, float h); /** * @class rect_t * @order -10 * @annotation ["scriptable"] * 矩形。包括一个x坐标、y坐标、宽度和高度。 */ typedef struct _rect_t { /** * @property {xy_t} x * @annotation ["readable", "scriptable"] * x坐标。 */ xy_t x; /** * @property {xy_t} y * @annotation ["readable", "scriptable"] * y坐标。 */ xy_t y; /** * @property {wh_t} w * @annotation ["readable", "scriptable"] * 宽度。 */ wh_t w; /** * @property {wh_t} h * @annotation ["readable", "scriptable"] * 高度。 */ wh_t h; } rect_t; /** * @method rect_create * 创建rect对象。 * * > 主要供脚本语言使用。 * * @annotation ["constructor", "scriptable", "gc"] * @param {xy_t} x x坐标。 * @param {xy_t} y y坐标。 * @param {wh_t} w 宽度。 * @param {wh_t} h 高度。 * * @return {rect_t*} rect对象。 */ rect_t* rect_create(xy_t x, xy_t y, wh_t w, wh_t h); /** * @method rect_set * 设置rect对象的xywh。 * * > 主要供脚本语言使用。 * * @annotation ["scriptable"] * @param {rect_t*} rect rect对象。 * @param {xy_t} x x坐标。 * @param {xy_t} y y坐标。 * @param {wh_t} w 宽度。 * @param {wh_t} h 高度。 * * @return {rect_t*} rect对象。 */ rect_t* rect_set(rect_t* rect, xy_t x, xy_t y, wh_t w, wh_t h); /** * @method rect_cast * 转换为rect对象。 * * > 供脚本语言使用。 * @annotation ["cast", "scriptable"] * @param {rect_t*} rect rect对象。 * * @return {rect_t*} rect对象。 */ rect_t* rect_cast(rect_t* rect); /** * @method rect_destroy * 销毁rect对象。 * * > 主要供脚本语言使用。 * * @annotation ["deconstructor", "scriptable", "gc"] * @param {rect_t*} r rect对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t rect_destroy(rect_t* r); /** * @method rect_scale * 缩放rect对象。 * * @param {rect_t*} r rect对象。 * @param {float_t} scale 缩放比例。 * * @return {rect_t*} 返回rect对象。 */ rect_t* rect_scale(rect_t* r, float_t scale); /** * @method rect_init * 初始化rect对象。 * * @param {xy_t} x x坐标。 * @param {xy_t} y y坐标。 * @param {wh_t} w 宽度。 * @param {wh_t} h 高度。 * * @return {rect_t} 返回rect对象。 */ rect_t rect_init(xy_t x, xy_t y, wh_t w, wh_t h); /** * @method rect_merge * 合并两个rect对象。 * * @param {rect_t*} dst_r rect对象。 * @param {const rect_t*} r rect对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t rect_merge(rect_t* dst_r, const rect_t* r); /** * @method rect_contains * 判断指定的点在rect范围内。 * * @param {const rect_t*} r rect对象。 * @param {xy_t} x x坐标。 * @param {xy_t} y y坐标。 * * @return {bool_t} 返回在rect范围内。 */ bool_t rect_contains(const rect_t* r, xy_t x, xy_t y); /** * @method rect_fix * 确保rect在指定的大小范围内。 * * @param {rect_t*} r rect对象。 * @param {wh_t} max_w 最大宽度。 * @param {wh_t} max_h 最大高度。 * * @return {rect_t} 返回修复之后的rect对象。 */ rect_t rect_fix(rect_t* r, wh_t max_w, wh_t max_h); /** * @method rect_intersect * 求两个rect的交集。 * * @param {const rect_t*} r1 rect对象。 * @param {const rect_t*} r2 rect对象。 * * @return {rect_t} 返回交集。 */ rect_t rect_intersect(const rect_t* r1, const rect_t* r2); /** * @method rect_has_intersect * 判断两个rect的是否存在交集。 * * @param {const rect_t*} r1 rect对象。 * @param {const rect_t*} r2 rect对象。 * * @return {bool_t} 返回TRUE表示存在,否则表示不存在。 */ bool_t rect_has_intersect(const rect_t* r1, const rect_t* r2); /** * @method rect_diff * 求第一个矩形和第二个矩形的差集。 * * 备注:第一个矩形包含第二个矩形的话,就会返回第一个矩形的四个矩形区域。 * * @param {const rect_t*} r1 第一个矩形。 * @param {const rect_t*} r2 第二个矩形。 * @param {rect_t*} out_r1 返回差集的第一个矩形数据。 * @param {rect_t*} out_r2 返回差集的第二个矩形数据。 * @param {rect_t*} out_r3 返回差集的第三个矩形数据。 * @param {rect_t*} out_r4 返回差集的第四个矩形数据。 * * @return {bool_t} 返回TRUE表示存在差集,否则表示不存在差集。 */ bool_t rect_diff(const rect_t* r1, const rect_t* r2, rect_t* out_r1, rect_t* out_r2, rect_t* out_r3, rect_t* out_r4); /** * @method rectf_scale * 缩放rectf对象。 * * @param {rectf_t*} r rect对象。 * @param {float_t} scale 缩放比例。 * * @return {rectf_t*} 返回rect对象。 */ rectf_t* rectf_scale(rectf_t* r, float_t scale); /** * @method rectf_fix * 确保rectf在指定的大小范围内。 * * @param {rectf_t*} r rectf对象。 * @param {wh_t} max_w 最大宽度。 * @param {wh_t} max_h 最大高度。 * * @return {rectf_t} 返回修复之后的rect对象。 */ rectf_t rectf_fix(rectf_t* r, wh_t max_w, wh_t max_h); /** * @method rect_to_rectf * rect 类型转换到 rectf 类型。 * * @param {const rect_t*} r rect对象。 * * @return {rectf_t} 返回 rectf_t 对象。 */ rectf_t rect_to_rectf(const rect_t* r); /** * @method rect_from_rectf * rectf 类型转换到 rect 类型。 * * @param {const rectf_t*} r rectf 对象。 * * @return {rect_t} 返回 rect 对象。 */ rect_t rect_from_rectf(const rectf_t* r); END_C_DECLS #endif /*TK_RECT_H*/
0
repos/awtk/src
repos/awtk/src/tkc/zip_file.h
/** * File: zip_file.h * Author: AWTK Develop Team * Brief: zip file * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2020-12-19 Li XianJing <[email protected]> created * */ #ifndef ZIP_FILE_H #define ZIP_FILE_H #include "tkc/fs.h" #include "tkc/buffer.h" BEGIN_C_DECLS /** * @class zip_file_t * zip文件。 */ /** * @method zip_file_extract * 解压zip文件。 * * @param {const char*} zipfile zip文件名。 * @param {const char*} dst_dir 目录。 * @param {const char*} password 密码(可选) * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t zip_file_extract(const char* zipfile, const char* dst_dir, const char* password); END_C_DECLS #endif /*ZIP_FILE_H*/
0
repos/awtk/src
repos/awtk/src/tkc/cond_var.c
/** * File: cond_var_simple.h * Author: AWTK Develop Team * Brief: cond_var simple * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2020-02-22 Li XianJing <[email protected]> created * */ #include "tkc/mem.h" #include "tkc/cond_var.h" struct _tk_cond_var_t { bool_t inited; bool_t has_signal; tk_mutex_t* mutex; tk_cond_t* cond; }; tk_cond_var_t* tk_cond_var_create(void) { tk_cond_var_t* cond_var = TKMEM_ZALLOC(tk_cond_var_t); return_value_if_fail(cond_var != NULL, NULL); cond_var->inited = TRUE; cond_var->mutex = tk_mutex_create(); cond_var->cond = tk_cond_create(); return cond_var; } ret_t tk_cond_var_wait(tk_cond_var_t* cond_var, uint32_t timeout_ms) { ret_t ret = RET_OK; return_value_if_fail(cond_var != NULL && cond_var->inited, RET_BAD_PARAMS); tk_mutex_lock(cond_var->mutex); if (!cond_var->has_signal) { ret = tk_cond_wait_timeout(cond_var->cond, cond_var->mutex, timeout_ms); } cond_var->has_signal = FALSE; tk_mutex_unlock(cond_var->mutex); return ret; } ret_t tk_cond_var_awake(tk_cond_var_t* cond_var) { return_value_if_fail(cond_var != NULL && cond_var->inited, RET_BAD_PARAMS); tk_mutex_lock(cond_var->mutex); cond_var->has_signal = TRUE; tk_mutex_unlock(cond_var->mutex); tk_cond_signal(cond_var->cond); return RET_OK; } ret_t tk_cond_var_destroy(tk_cond_var_t* cond_var) { return_value_if_fail(cond_var != NULL && cond_var->inited, RET_BAD_PARAMS); tk_cond_destroy(cond_var->cond); tk_mutex_destroy(cond_var->mutex); memset(cond_var, 0x00, sizeof(tk_cond_var_t)); TKMEM_FREE(cond_var); return RET_OK; }
0
repos/awtk/src
repos/awtk/src/tkc/darray.h
/** * File: darray.h * Author: AWTK Develop Team * Brief: dynamic darray. * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-01-13 Li XianJing <[email protected]> created * */ #ifndef TK_DARRAY_H #define TK_DARRAY_H #include "tkc/types_def.h" BEGIN_C_DECLS /** * @class darray_t * 动态数组,根据元素个数动态调整数组的容量。 * * 用darray\_init初始化时,用darray\_deinit释放。如: * * ```c * darray_t darray; * darray_init(&darray, 10, destroy, compare); * ... * darray_deinit(&darray); * ``` * * 用darray\_create创建时,用darray\_destroy销毁。如: * * ```c * darray_t* darray = darray_create(10, destroy, compare); * ... * darray_destroy(darray); * ``` * */ typedef struct _darray_t { /** * @property {uint32_t} size * @annotation ["readable"] * 数组中元素的个数。 */ uint32_t size; /** * @property {uint32_t} capacity * @annotation ["readable"] * 数组的容量大小。 */ uint32_t capacity; /** * @property {void**} elms * @annotation ["readable"] * 数组中的元素。 */ void** elms; /** * @property {tk_destroy_t} destroy * @annotation ["readable"] * 元素销毁函数。 */ tk_destroy_t destroy; /** * @property {tk_compare_t} compare * @annotation ["readable"] * 元素比较函数。 */ tk_compare_t compare; } darray_t; /** * @method darray_create * @annotation ["constructor"] * 创建darray对象。 * * @param {uint32_t} capacity 数组的初始容量。 * @param {tk_destroy_t} destroy 元素销毁函数。 * @param {tk_compare_t} compare 元素比较函数。 * * @return {darray_t*} 数组对象。 */ darray_t* darray_create(uint32_t capacity, tk_destroy_t destroy, tk_compare_t compare); /** * @method darray_init * 初始化darray对象。 * * @param {darray_t*} darray 数组对象。 * @param {uint32_t} capacity 数组的初始容量。 * @param {tk_destroy_t} destroy 元素销毁函数。 * @param {tk_compare_t} compare 元素比较函数。 * * @return {darray_t*} 数组对象。 */ darray_t* darray_init(darray_t* darray, uint32_t capacity, tk_destroy_t destroy, tk_compare_t compare); /** * @method darray_find * 查找第一个满足条件的元素。 * @param {darray_t*} darray 数组对象。 * @param {void*} ctx 比较函数的上下文。 * * @return {void*} 如果找到,返回满足条件的对象,否则返回NULL。 */ void* darray_find(darray_t* darray, void* ctx); /** * @method darray_find_ex * 查找第一个满足条件的元素。 * @param {darray_t*} darray 数组对象。 * @param {tk_compare_t} cmp 比较函数,为NULL则使用内置的比较函数。 * @param {void*} ctx 比较函数的上下文。 * * @return {void*} 如果找到,返回满足条件的对象,否则返回NULL。 */ void* darray_find_ex(darray_t* darray, tk_compare_t cmp, void* ctx); /** * @method darray_bsearch_index * 二分查找(确保数组有序)。 * * @param {darray_t*} darray 数组对象。 * @param {tk_compare_t} cmp 比较函数,为NULL则使用内置的比较函数。 * @param {void*} ctx 比较函数的上下文。 * * @return {int32_t} 如果找到,返回满足条件的对象的位置,否则返回-1。 */ int32_t darray_bsearch_index(darray_t* darray, tk_compare_t cmp, void* ctx); /** * @method darray_bsearch_index_ex * 二分查找(确保数组有序),元素不存在时,返回low索引。 * * @param {darray_t*} darray 数组对象。 * @param {tk_compare_t} cmp 比较函数,为NULL则使用内置的比较函数。 * @param {void*} ctx 比较函数的上下文。 * @param {int32_t*} ret_low low索引。 * * @return {int32_t} 如果找到,返回满足条件的对象的位置,否则返回-1。 */ int32_t darray_bsearch_index_ex(darray_t* darray, tk_compare_t cmp, void* ctx, int32_t* ret_low); /** * @method darray_bsearch * 二分查找(确保数组有序)。 * * @param {darray_t*} darray 数组对象。 * @param {tk_compare_t} cmp 比较函数,为NULL则使用内置的比较函数。 * @param {void*} ctx 比较函数的上下文。 * * @return {void*} 如果找到,返回满足条件的对象,否则返回NULL。 */ void* darray_bsearch(darray_t* darray, tk_compare_t cmp, void* ctx); /** * @method darray_get * 获取指定序数的元素。 * @param {darray_t*} darray 数组对象。 * @param {uint32_t} index 序数。 * * @return {void*} 返回满足条件的对象,否则返回NULL。 */ void* darray_get(darray_t* darray, uint32_t index); /** * @method darray_set * 设置指定序数的元素(不销毁旧的数据)。 * @param {darray_t*} darray 数组对象。 * @param {uint32_t} index 序数。 * @param {void*} data 数据。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_set(darray_t* darray, uint32_t index, void* data); /** * @method darray_replace * 设置指定序数的元素(销毁旧的数据)。 * @param {darray_t*} darray 数组对象。 * @param {uint32_t} index 序数。 * @param {void*} data 数据。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_replace(darray_t* darray, uint32_t index, void* data); /** * @method darray_find_index * 查找第一个满足条件的元素,并返回位置。 * @param {darray_t*} darray 数组对象。 * @param {void*} ctx 比较函数的上下文。 * * @return {int32_t} 如果找到,返回满足条件的对象的位置,否则返回-1。 */ int32_t darray_find_index(darray_t* darray, void* ctx); /** * @method darray_find_index_ex * 查找第一个满足条件的元素,并返回位置。 * @param {darray_t*} darray 数组对象。 * @param {tk_compare_t} cmp 比较函数,为NULL则使用内置的比较函数。 * @param {void*} ctx 比较函数的上下文。 * * @return {int32_t} 如果找到,返回满足条件的对象的位置,否则返回-1。 */ int32_t darray_find_index_ex(darray_t* darray, tk_compare_t cmp, void* ctx); /** * @method darray_remove * 删除第一个满足条件的元素。 * @param {darray_t*} darray 数组对象。 * @param {void*} ctx 比较函数的上下文。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_remove(darray_t* darray, void* ctx); /** * @method darray_remove_ex * 删除第一个满足条件的元素。 * @param {darray_t*} darray 数组对象。 * @param {tk_compare_t} cmp 比较函数,为NULL则使用内置的比较函数。 * @param {void*} ctx 比较函数的上下文。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_remove_ex(darray_t* darray, tk_compare_t cmp, void* ctx); /** * @method darray_remove_index * 删除指定位置的元素。 * @param {darray_t*} darray 数组对象。 * @param {uint32_t} index 位置序数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_remove_index(darray_t* darray, uint32_t index); /** * @method darray_remove_range * 删除指定范围的元素。 * 删除范围为[start, end) * @param {darray_t*} darray 数组对象。 * @param {uint32_t} start 起始位置。 * @param {uint32_t} end 结束位置。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_remove_range(darray_t* darray, uint32_t start, uint32_t end); /** * @method darray_remove_all * 删除全部满足条件的元素。 * @param {darray_t*} darray 数组对象。 * @param {tk_compare_t} cmp 比较函数,为NULL则使用内置的比较函数。 * @param {void*} ctx 比较函数的上下文。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_remove_all(darray_t* darray, tk_compare_t cmp, void* ctx); /** * @method darray_sort * 排序。 * @param {darray_t*} darray 数组对象。 * @param {tk_compare_t} cmp 比较函数,为NULL则使用内置的比较函数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_sort(darray_t* darray, tk_compare_t cmp); /** * @method darray_find_all * 查找全部满足条件的元素。 * * ``` * darray_t matched; * darray_init(&matched, 0, NULL, NULL); * darray_find_all(darray, mycmp, myctx, &matched); * ... * darray_deinit(&matched); * * ``` * @param {darray_t*} darray 数组对象。 * @param {tk_compare_t} cmp 比较函数,为NULL则使用内置的比较函数。 * @param {void*} ctx 比较函数的上下文。 * @param {darray_t*} matched 返回满足条件的元素。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_find_all(darray_t* darray, tk_compare_t cmp, void* ctx, darray_t* matched); /** * @method darray_pop * 弹出最后一个元素。 * @param {darray_t*} darray 数组对象。 * * @return {void*} 成功返回最后一个元素,失败返回NULL。 */ void* darray_pop(darray_t* darray); /** * @method darray_tail * 返回最后一个元素。 * @param {darray_t*} darray 数组对象。 * * @return {void*} 成功返回最后一个元素,失败返回NULL。 */ void* darray_tail(darray_t* darray); /** * @method darray_head * 返回第一个元素。 * @param {darray_t*} darray 数组对象。 * * @return {void*} 成功返回最后一个元素,失败返回NULL。 */ void* darray_head(darray_t* darray); /** * @method darray_push * 在尾巴追加一个元素。 * @param {darray_t*} darray 数组对象。 * @param {void*} data 待追加的元素。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_push(darray_t* darray, void* data); /** * @method darray_push_unique * 如果不存在,在尾巴追加一个元素。 * @param {darray_t*} darray 数组对象。 * @param {void*} data 待追加的元素。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_push_unique(darray_t* darray, void* data); /** * @method darray_insert * 插入一个元素。 * @param {darray_t*} darray 数组对象。 * @param {uint32_t} index 位置序数。 * @param {void*} data 待插入的元素。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_insert(darray_t* darray, uint32_t index, void* data); /** * @method darray_sorted_insert * 插入一个元素到有序数组。 * @param {darray_t*} darray 数组对象。 * @param {void*} data 待插入的元素。 * @param {tk_compare_t} cmp 元素比较函数。 * @param {bool_t} replace_if_exist 如果存在是否替换。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_sorted_insert(darray_t* darray, void* data, tk_compare_t cmp, bool_t replace_if_exist); /** * @method darray_count * 返回满足条件元素的个数。 * @param {darray_t*} darray 单向链表对象。 * @param {void*} ctx 比较函数的上下文。 * * @return {int32_t} 返回元素个数。 */ int32_t darray_count(darray_t* darray, void* ctx); /** * @method darray_clear * 清除全部元素。 * @param {darray_t*} darray 数组对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_clear(darray_t* darray); /** * @method darray_foreach * 遍历元素。 * @param {darray_t*} darray 数组对象。 * @param {tk_visit_t} visit 遍历函数。 * @param {void*} ctx 遍历函数的上下文。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_foreach(darray_t* darray, tk_visit_t visit, void* ctx); /** * @method darray_deinit * 清除全部元素,并释放elms。 * @param {darray_t*} darray 数组对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_deinit(darray_t* darray); /** * @method darray_destroy * 销毁darray对象。 * @param {darray_t*} darray 数组对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t darray_destroy(darray_t* darray); END_C_DECLS #endif /*TK_DARRAY_H*/
0
repos/awtk/src
repos/awtk/src/tkc/asset_info.h
/** * File: asset_info.h * Author: AWTK Develop Team * Brief: asset info * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-03-07 Li XianJing <[email protected]> created * */ #ifndef TK_ASSET_INFO_H #define TK_ASSET_INFO_H #ifdef LOAD_ASSET_WITH_MMAP #include "tkc/mmap.h" #else #include "tkc/types_def.h" #endif /*LOAD_ASSET_WITH_MMAP*/ BEGIN_C_DECLS /** * @enum asset_type_t * @prefix ASSET_TYPE_ * @annotation ["scriptable"] * 资源类型常量定义。 */ typedef enum _asset_type_t { /** * @const ASSET_TYPE_NONE * 无效资源。 */ ASSET_TYPE_NONE, /** * @const ASSET_TYPE_FONT * 字体资源。 */ ASSET_TYPE_FONT, /** * @const ASSET_TYPE_IMAGE * 图片资源。 */ ASSET_TYPE_IMAGE, /** * @const ASSET_TYPE_STYLE * 窗体样式资源。 */ ASSET_TYPE_STYLE, /** * @const ASSET_TYPE_UI * UI数据资源。 */ ASSET_TYPE_UI, /** * @const ASSET_TYPE_XML * XML数据资源。 */ ASSET_TYPE_XML, /** * @const ASSET_TYPE_STRINGS * 字符串数据资源。 */ ASSET_TYPE_STRINGS, /** * @const ASSET_TYPE_SCRIPT * JS等脚本资源。 */ ASSET_TYPE_SCRIPT, /** * @const ASSET_TYPE_FLOW * 流图资源。 */ ASSET_TYPE_FLOW, /** * @const ASSET_TYPE_DATA * 其它数据资源。 */ ASSET_TYPE_DATA } asset_type_t; /** * @enum asset_font_type_t * @prefix ASSET_TYPE_FONT_ * 字体资源类型定义。 */ typedef enum _asset_font_type_t { /** * @const ASSET_TYPE_FONT_NONE * 无效字体。 */ ASSET_TYPE_FONT_NONE, /** * @const ASSET_TYPE_FONT_TTF * TTF字体。 */ ASSET_TYPE_FONT_TTF, /** * @const ASSET_TYPE_FONT_BMP * 位图字体。 */ ASSET_TYPE_FONT_BMP } asset_font_type_t; /** * @enum asset_data_type_t * @prefix ASSET_TYPE_DATA_ * 数据资源类型定义。 */ typedef enum _asset_data_type_t { /** * @const ASSET_TYPE_DATA_NONE * 未知数据类型。 */ ASSET_TYPE_DATA_NONE, /** * @const ASSET_TYPE_DATA_TEXT * 文本数据类型。 */ ASSET_TYPE_DATA_TEXT, /** * @const ASSET_TYPE_DATA_BIN * 二进制数据类型。 */ ASSET_TYPE_DATA_BIN, /** * @const ASSET_TYPE_DATA_JSON * JSON数据类型。 */ ASSET_TYPE_DATA_JSON, /** * @const ASSET_TYPE_DATA_DAT * 通用数据类型。 */ ASSET_TYPE_DATA_DAT } asset_data_type_t; /** * @enum asset_script_type_t * @prefix ASSET_TYPE_SCRIPT_ * 脚本资源类型定义。 */ typedef enum _asset_script_type_t { /** * @const ASSET_TYPE_SCRIPT_NONE * 未知脚本类型。 */ ASSET_TYPE_SCRIPT_NONE, /** * @const ASSET_TYPE_SCRIPT_JS * JS脚本类型。 */ ASSET_TYPE_SCRIPT_JS, /** * @const ASSET_TYPE_SCRIPT_LUA * LUA脚本类型。 */ ASSET_TYPE_SCRIPT_LUA, /** * @const ASSET_TYPE_SCRIPT_PYTHON * Python脚本类型。 */ ASSET_TYPE_SCRIPT_PYTHON } asset_script_type_t; /** * @enum asset_image_type_t * @prefix ASSET_TYPE_IMAGE_ * 图片资源类型定义。 */ typedef enum _asset_image_type_t { /** * @const ASSET_TYPE_IMAGE_NONE * 未知图片类型。 */ ASSET_TYPE_IMAGE_NONE, /** * @const ASSET_TYPE_IMAGE_RAW * Raw图片类型。 */ ASSET_TYPE_IMAGE_RAW, /** * @const ASSET_TYPE_IMAGE_BMP * 位图图片类型。 */ ASSET_TYPE_IMAGE_BMP, /** * @const ASSET_TYPE_IMAGE_PNG * PNG图片类型。 */ ASSET_TYPE_IMAGE_PNG, /** * @const ASSET_TYPE_IMAGE_JPG * JPG图片类型。 */ ASSET_TYPE_IMAGE_JPG, /** * @const ASSET_TYPE_IMAGE_BSVG * BSVG图片类型。 */ ASSET_TYPE_IMAGE_BSVG, /** * @const ASSET_TYPE_IMAGE_GIF * GIF图片类型。 */ ASSET_TYPE_IMAGE_GIF, /** * @const ASSET_TYPE_IMAGE_WEBP * WEBP图片类型。 */ ASSET_TYPE_IMAGE_WEBP, /** * @const ASSET_TYPE_IMAGE_LZ4 * LZ4压缩的图片类型。 */ ASSET_TYPE_IMAGE_LZ4, /** * @const ASSET_TYPE_IMAGE_OTHER * 其它图片类型。 */ ASSET_TYPE_IMAGE_OTHER } asset_image_type_t; /** * @enum asset_ui_type_t * @prefix ASSET_TYPE_UI_ * UI资源类型定义。 */ typedef enum _asset_ui_type_t { /** * @const ASSET_TYPE_UI_NONE * 无效UI类型。 */ ASSET_TYPE_UI_NONE, /** * @const ASSET_TYPE_UI_BIN * 二进制的UI类型。 */ ASSET_TYPE_UI_BIN, /** * @const ASSET_TYPE_UI_XML * XML格式的UI类型。 */ ASSET_TYPE_UI_XML } asset_ui_type_t; /** * @class preload_res_t * 预加载资源的描述信息。 */ typedef struct _preload_res_t { asset_type_t type; const char* name; } preload_res_t; /** * @enum asset_info_flag_t * @prefix ASSET_INFO_FLAG_ * 资源标志常量定义。 */ typedef enum _asset_info_flag_t { /** * @const ASSET_INFO_FLAG_IN_ROM * 资源在ROM中。 */ ASSET_INFO_FLAG_IN_ROM = 1, /** * @const ASSET_INFO_FLAG_FULL_NAME * 使用长名字。 */ ASSET_INFO_FLAG_FULL_NAME = 1 << 1, } asset_info_flag_t; /** * @class asset_info_t * @annotation ["scriptable"] * 单个资源的描述信息。 */ #pragma pack(push, 1) typedef struct _asset_info_t { /** * @property {uint16_t} type * @annotation ["readable","scriptable"] * 类型。 */ uint16_t type; /** * @property {uint8_t} subtype * @annotation ["readable", "scriptable"] * 子类型。 */ uint8_t subtype; /** * @property {uint8_t} flags * @annotation ["readable", "scriptable"] * 资源标志。 */ uint8_t flags; /** * @property {uint32_t} size * @annotation ["readable","scriptable"] * 大小。 */ uint32_t size; /** * @property {uint32_t} refcount * @annotation ["readable","scriptable"] * 引用计数。 * is\_in\_rom == FALSE时才有效。 */ uint32_t refcount; /* internal */ union { char small_name[TK_NAME_LEN + 1]; char* full_name; } name; #ifdef LOAD_ASSET_WITH_MMAP uint8_t* data; mmap_t* map; #else uint8_t data[4]; #endif /*LOAD_ASSET_WITH_MMAP*/ } asset_info_t; #pragma pack(pop) /** * @method asset_info_create * 创建asset_info对象。 * * > 主要供脚本语言使用。 * * @annotation ["constructor"] * @param {uint16_t} type 资源的类型。 * @param {uint16_t} subtype 资源的子类型。 * @param {const char*} name 资源的名称。 * @param {int32_t} size 资源的数据长度(用于分配空间)。 * * @return {asset_info_t*} asset_info对象。 */ asset_info_t* asset_info_create(uint16_t type, uint16_t subtype, const char* name, int32_t size); /** * @method asset_info_destroy * * 销毁asset_info对象。 * * @annotation ["deconstructor"] * @param {asset_info_t*} info asset_info对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t asset_info_destroy(asset_info_t* info); /** * @method asset_info_unref * * 减少asset_info对象的引用计数。 * * @param {asset_info_t*} info asset_info对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t asset_info_unref(asset_info_t* info); /** * @method asset_info_ref * * 增加asset_info对象的引用计数。 * * @param {asset_info_t*} info asset_info对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t asset_info_ref(asset_info_t* info); /** * @method asset_info_get_type * * 获取类型。 * @annotation ["scriptable"] * * @param {asset_info_t*} info asset_info对象。 * * @return {uint16_t} 返回类型。 */ uint16_t asset_info_get_type(asset_info_t* info); /** * @method asset_info_get_name * * 获取名称。 * @annotation ["scriptable"] * * @param {const asset_info_t*} info asset_info对象。 * * @return {const char*} 返回名称。 */ const char* asset_info_get_name(const asset_info_t* info); /** * @method asset_info_get_formatted_name * * 把资源名字格式化为符合标准长度的字符串。 * * @param {const char*} name 未格式化名字。 * * @return {const char*} 返回格式化后的名字。 */ const char* asset_info_get_formatted_name(const char* name); /** * @method asset_info_is_in_rom * * 资源是否在ROM中。 * @annotation ["scriptable"] * * @param {const asset_info_t*} info asset_info对象。 * * @return {bool_t} 返回 TRUE 为在 ROM 中,返回 FALSE 则不在。 */ bool_t asset_info_is_in_rom(const asset_info_t* info); /** * @method asset_info_set_is_in_rom * * 设置资源是否在ROM中的标记位。 * @annotation ["scriptable"] * * @param {asset_info_t*} info asset_info对象。 * @param {bool_t} is_in_rom 资源是否在ROM中。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t asset_info_set_is_in_rom(asset_info_t* info, bool_t is_in_rom); /* internal */ ret_t asset_info_set_name(asset_info_t* info, const char* name, bool_t is_alloc); END_C_DECLS #endif /*TK_ASSET_INFO_H*/
0
repos/awtk/src
repos/awtk/src/tkc/event_source.h
/** * File: event_source.h * Author: AWTK Develop Team * Brief: event source interface. * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2019-09-29 Li XianJing <[email protected]> created * */ #ifndef TK_EVENT_SOURCE_H #define TK_EVENT_SOURCE_H #include "tkc/object.h" BEGIN_C_DECLS typedef int32_t (*event_source_get_fd_t)(event_source_t* source); typedef uint32_t (*event_source_get_wakeup_time_t)(event_source_t* source); typedef ret_t (*event_source_check_t)(event_source_t* source); typedef ret_t (*event_source_dispatch_t)(event_source_t* source); typedef ret_t (*event_source_on_event_t)(event_source_t* source); /** * @class event_source_t * @parent tk_object_t * * 表示一个事件源。 * * 事件源有下列两种方式: * * * 对于有文件描述符的事件源(如socket),get_fd返回一个有效的文件描述符。 * * 对于定时器,则get_wakeup_time返回下次唤醒的时间(毫秒)。 * */ struct _event_source_t { tk_object_t object; event_source_check_t check; event_source_get_fd_t get_fd; event_source_dispatch_t dispatch; event_source_get_wakeup_time_t get_wakeup_time; void* tag; event_source_manager_t* manager; }; /** * @method event_source_get_fd * * 获取文件描述符。 * * @param {event_source_t*} source event_source对象。 * * @return {int32_t} 返回文件描述符。 * */ int32_t event_source_get_fd(event_source_t* source); /** * @method event_source_dispatch * * 分发事件。 * * @param {event_source_t*} source event_source对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 * */ ret_t event_source_dispatch(event_source_t* source); /** * @method event_source_set_tag * * 设置tag,方便通过tag一次移除多个事件源。 * * @param {event_source_t*} source event_source对象。 * @param {void*} tag tag。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 * */ ret_t event_source_set_tag(event_source_t* source, void* tag); /** * @method event_source_check * * 对于没有文件描述符的事件源,需要自己检查是否准备就绪。 * * @param {event_source_t*} source event_source对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 * */ ret_t event_source_check(event_source_t* source); /** * @method event_source_get_wakeup_time * * 获取唤醒时间(毫秒)。 * * @param {event_source_t*} source event_source对象。 * * @return {uint32_t} 返回唤醒时间(毫秒)。 * */ uint32_t event_source_get_wakeup_time(event_source_t* source); #define EVENT_SOURCE(obj) ((event_source_t*)(obj)) END_C_DECLS #endif /*TK_EVENT_SOURCE_H*/
0
repos/awtk/src
repos/awtk/src/tkc/data_reader.h
/** * File: data_reader.h * Author: AWTK Develop Team * Brief: data_reader * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2020-02-26 Li XianJing <[email protected]> created * */ #ifndef TK_DATA_READER_H #define TK_DATA_READER_H #include "tkc/types_def.h" BEGIN_C_DECLS struct _data_reader_t; typedef struct _data_reader_t data_reader_t; typedef int32_t (*data_reader_read_t)(data_reader_t* reader, uint64_t offset, void* data, uint32_t size); typedef uint64_t (*data_reader_get_size_t)(data_reader_t* reader); typedef ret_t (*data_reader_destroy_t)(data_reader_t* reader); typedef struct _data_reader_vtable_t { data_reader_read_t read; data_reader_get_size_t get_size; data_reader_destroy_t destroy; } data_reader_vtable_t; /** * @class data_reader_t * 数据读取接口。 * * >对可读的媒介,如内存、文件、flash、资源和其它媒介提供一个统一的读取接口。 * */ struct _data_reader_t { const data_reader_vtable_t* vt; }; /** * @method data_reader_read * 在指定位置读取数据。 * * @param {data_reader_t*} reader reader对象。 * @param {uint64_t} offset 偏移量。 * @param {void*} data 用于读取数据的缓冲区。 * @param {uint32_t} size 最大读取数据长度。 * * @return {int32_t} 返回实际读取数据的长度。 */ int32_t data_reader_read(data_reader_t* reader, uint64_t offset, void* data, uint32_t size); /** * @method data_reader_get_size * 获取数据长度。 * * @param {data_reader_t*} reader reader对象。 * * @return {uint64_t} 返回数据长度。 */ uint64_t data_reader_get_size(data_reader_t* reader); /** * @method data_reader_destroy * 销毁reader对象。 * @param {data_reader_t*} reader reader对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t data_reader_destroy(data_reader_t* reader); /** * @method data_reader_read_all * 从指定的URL读取全部数据。 * @param {const char*} url URL。 * @param {uint32_t*} size 返回数据长度。 * * @return {void*} 返回全部数据,调用者需要调用TKMEM_FREE释放返回值。 */ void* data_reader_read_all(const char* url, uint32_t* size); /** * @method data_reader_can_read * 查询 url 中是否有数据。 * * @param {const char*} url URL。 * * @return {bool_t} 返回 bool_t 值。 */ bool_t data_reader_can_read(const char* url); #define DATA_READER(reader) ((data_reader_t*)(reader)) END_C_DECLS #endif /*TK_DATA_READER_H*/
0
repos/awtk/src
repos/awtk/src/tkc/mem_allocator.h
/** * File: mem_allocator.h * Author: AWTK Develop Team * Brief: mem_allocator * * Copyright (c) 2020 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2020-06-16 Li XianJing <[email protected]> created * */ #ifndef TK_MEM_ALLOCATOR_H #define TK_MEM_ALLOCATOR_H #include "tkc/types_def.h" BEGIN_C_DECLS struct _mem_allocator_t; typedef struct _mem_allocator_t mem_allocator_t; typedef void* (*mem_allocator_alloc_t)(mem_allocator_t* allocator, uint32_t size, const char* func, uint32_t line); typedef void* (*mem_allocator_realloc_t)(mem_allocator_t* allocator, void* ptr, uint32_t size, const char* func, uint32_t line); typedef void (*mem_allocator_free_t)(mem_allocator_t* allocator, void* ptr); typedef ret_t (*mem_allocator_dump_t)(mem_allocator_t* allocator); typedef ret_t (*mem_allocator_destroy_t)(mem_allocator_t* allocator); typedef struct _mem_allocator_vtable_t { mem_allocator_alloc_t alloc; mem_allocator_realloc_t realloc; mem_allocator_free_t free; mem_allocator_dump_t dump; mem_allocator_destroy_t destroy; } mem_allocator_vtable_t; /** * @class mem_allocator_t * 内存分配接口。 * */ struct _mem_allocator_t { const mem_allocator_vtable_t* vt; }; /** * @method mem_allocator_alloc * @export none * 分配指定大小的内存。 * * @param {mem_allocator_t*} allocator allocator对象。 * @param {uint32_t} size 内存的大小。 * @param {const char*} func 分配内存的函数(用于调试)。 * @param {uint32_t} line 分配内存的行数(用于调试)。 * * @return {void*} 成功返回内存块的地址,失败返回NULL。 */ static inline void* mem_allocator_alloc(mem_allocator_t* allocator, uint32_t size, const char* func, uint32_t line) { return_value_if_fail(allocator != NULL && allocator->vt != NULL && allocator->vt->alloc != NULL, NULL); return allocator->vt->alloc(allocator, size, func, line); } /** * @method mem_allocator_realloc * @export none * 重新分配指定大小的内存。 * * @param {mem_allocator_t*} allocator allocator对象。 * @param {void*} ptr 原来内存的地址。 * @param {uint32_t} size 内存的大小。 * @param {const char*} func 分配内存的函数(用于调试)。 * @param {uint32_t} line 分配内存的行数(用于调试)。 * * @return {void*} 成功返回内存块的地址,失败返回NULL。 */ static inline void* mem_allocator_realloc(mem_allocator_t* allocator, void* ptr, uint32_t size, const char* func, uint32_t line) { return_value_if_fail(allocator != NULL && allocator->vt != NULL && allocator->vt->realloc != NULL, NULL); return allocator->vt->realloc(allocator, ptr, size, func, line); } /** * @method mem_allocator_free * @export none * 释放内存。 * * @param {mem_allocator_t*} allocator allocator对象。 * @param {void*} ptr 内存的地址。 * * @return {void} 无。 */ static inline void mem_allocator_free(mem_allocator_t* allocator, void* ptr) { return_if_fail(allocator != NULL && allocator->vt != NULL && allocator->vt->free != NULL); allocator->vt->free(allocator, ptr); } /** * @method mem_allocator_dump * @export none * 显示内存信息,用于调试。 * * @param {mem_allocator_t*} allocator allocator对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ static inline ret_t mem_allocator_dump(mem_allocator_t* allocator) { return_value_if_fail(allocator != NULL && allocator->vt != NULL && allocator->vt->dump != NULL, RET_BAD_PARAMS); return allocator->vt->dump(allocator); } /** * @method mem_allocator_destroy * @export none * 销毁内存分配器。 * * @param {mem_allocator_t*} allocator allocator对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ static inline ret_t mem_allocator_destroy(mem_allocator_t* allocator) { return_value_if_fail(allocator != NULL && allocator->vt != NULL && allocator->vt->destroy != NULL, RET_BAD_PARAMS); return allocator->vt->destroy(allocator); } #define MEM_ALLOCATOR(allocator) ((mem_allocator_t*)(allocator)) END_C_DECLS #endif /*TK_MEM_ALLOCATOR_H*/
0
repos/awtk/src
repos/awtk/src/tkc/color_parser.h
/** * File: color_parser.h * Author: AWTK Develop Team * Brief: color parser * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-01-13 Li XianJing <[email protected]> created * */ #include "tkc/color.h" #include "tkc/types_def.h" #ifndef COLOR_PARSER_H #define COLOR_PARSER_H BEGIN_C_DECLS /** * @class color_parser_t * @annotation ["fake"] * 颜色解析相关函数。 * * 示例: * * ```c * color_t c; * c = color_parse("#112233"); * c = color_parse("white"); * c = color_parse("rgb(11,22,33)"); * c = color_parse("rgba(11,22,33,0.5)"); * ``` * */ /** * @method color_parse * 把字符串格式的颜色转换成color\_t对象。 * * 目前支持下列格式: * * * 16进制格式。如:"#112233" * * 颜色名称格式。如:"green" * * rgb格式。如:"rgb(11,22,33)" * * rgba格式。如:"rgba(11,22,33,0.5)" * * @annotation ["static"] * @param {const char*} color 字符串格式的颜色。 * * @return {color_t} 返回color_t对象。 */ color_t color_parse(const char* color); END_C_DECLS #endif /*COLOR_PARSER_H*/
0
repos/awtk/src
repos/awtk/src/tkc/mmap.h
/** * File: mmap.h * Author: AWTK Develop Team * Brief: mmap * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is dimmapibuted in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2020-12-11 Li XianJing <[email protected]> created * */ #ifndef TK_MMAP_H #define TK_MMAP_H #include "tkc/str.h" BEGIN_C_DECLS /** * @class mmap_t * 把文件内容映射到内存。 * */ typedef struct _mmap_t { /** * @property {void*} data * @annotation ["readable"] * 内存地址。 */ void* data; /** * @property {uint32_t} size * @annotation ["readable"] * 数据长度。 */ uint32_t size; /*private*/ void* handle; void* fd; } mmap_t; /** * @method mmap_create * 初始化mmap对象。 * @annotation ["constructor"] * @param {const char*} filename 文件名。 * @param {bool_t} writable 是否可写。 * @param {bool_t} shared 是否共享。 * * @return {mmap_t*} mmap对象本身。 */ mmap_t* mmap_create(const char* filename, bool_t writable, bool_t shared); /** * @method mmap_destroy * 销毁mmap。 * @param {mmap_t*} mmap mmap对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t mmap_destroy(mmap_t* mmap); END_C_DECLS #endif /*TK_MMAP_H*/
0
repos/awtk/src
repos/awtk/src/tkc/str.h
/** * File: str.h * Author: AWTK Develop Team * Brief: string * * Copyright (c) 2018 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-04-30 Li XianJing <[email protected]> adapt from uclib * */ #ifndef TK_STR_H #define TK_STR_H #include "tkc/value.h" #include "tkc/types_def.h" BEGIN_C_DECLS /** * @class str_t * 可变长度的UTF8字符串。 * * 示例: * * ```c * str_t s; * str_init(&s, 0); * * str_append(&s, "abc"); * str_append(&s, "123"); * log_debug("%s\n", s.str); * * str_reset(&s); * ``` * * > 先调str\_init进行初始化,最后调用str\_reset释放内存。 * */ typedef struct _str_t { /** * @property {uint32_t} size * @annotation ["readable"] * 长度。 */ uint32_t size; /** * @property {uint32_t} capacity * @annotation ["readable"] * 容量。 */ uint32_t capacity; /** * @property {char*} str * @annotation ["readable"] * 字符串。 */ char* str; /*private*/ bool_t extendable; } str_t; /** * @method str_create * 创建str对象。 * @annotation ["constructor"] * @param {uint32_t} capacity 初始容量。 * * @return {str_t*} str对象。 */ str_t* str_create(uint32_t capacity); /** * @method str_destroy * 销毁str对象 * 备注:最后调用str\_destroy释放内存。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_destroy(str_t* str); /** * @method str_init * 初始化字符串对象。 * 备注:最后调用str\_reset释放内存。 * @annotation ["constructor"] * @param {str_t*} str str对象。 * @param {uint32_t} capacity 初始容量。 * * @return {str_t*} str对象本身。 */ str_t* str_init(str_t* str, uint32_t capacity); /** * @method str_attach * 通过附加到一个buff来初始化str。 * >可以避免str动态分配内存,同时也不会自动扩展内存,使用完成后无需调用str_reset。 *```c * str_t s; * char buff[32]; * str_attach(&s, buff, ARRAY_SIZE(buff)); * str_set(&s, "abc"); * str_append(&s, "123"); *``` * @annotation ["constructor"] * @param {str_t*} str str对象。 * @param {char*} buff 缓冲区。 * @param {uint32_t} capacity 初始容量。 * * @return {str_t*} str对象本身。 */ str_t* str_attach(str_t* str, char* buff, uint32_t capacity); /** * @method str_attach_with_size * 通过附加到一个buff来初始化str。 * >可以避免str动态分配内存,同时也不会自动扩展内存,使用完成后无需调用str_reset。 *```c * str_t s; * char buff[32]; * strcpy(buff, "a"); * str_attach_with_size(&s, buff, 1, ARRAY_SIZE(buff)); * str_set(&s, "abc"); * str_append(&s, "123"); *``` * @annotation ["constructor"] * @param {str_t*} str str对象。 * @param {char*} buff 缓冲区。 * @param {uint32_t} size 初始长度。 * @param {uint32_t} capacity 初始容量。 * * @return {str_t*} str对象本身。 */ str_t* str_attach_with_size(str_t* str, char* buff, uint32_t size, uint32_t capacity); /** * @method str_extend * 扩展字符串到指定的容量。 * @param {str_t*} str str对象。 * @param {uint32_t} capacity 新的容量。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_extend(str_t* str, uint32_t capacity); /** * @method str_shrink * 如果字符串长度大于指定长度,收缩字符串到指定的长度。 * @param {str_t*} str str对象。 * @param {uint32_t} size 新的长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_shrink(str_t* str, uint32_t size); /** * @method str_eq * 判断两个字符串是否相等。 * @param {str_t*} str str对象。 * @param {const char*} text 待比较的字符串。 * * @return {bool_t} 返回是否相等。 */ bool_t str_eq(str_t* str, const char* text); /** * @method str_equal * 判断两个字符是否相同。 * @param {str_t*} str str对象。 * @param {str_t*} other str对象。 * * @return {bool_t} 返回TRUE表示相同,否则表示不同。 */ bool_t str_equal(str_t* str, str_t* other); /** * @method str_set * 设置字符串。 * @param {str_t*} str str对象。 * @param {const char*} text 要设置的字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_set(str_t* str, const char* text); /** * @method str_clear * 清除字符串内容。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_clear(str_t* str); /** * @method str_set_with_len * 设置字符串。 * @param {str_t*} str str对象。 * @param {const char*} text 要设置的字符串。 * @param {uint32_t} len 字符串长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_set_with_len(str_t* str, const char* text, uint32_t len); /** * @method str_append * 追加字符串。 * @param {str_t*} str str对象。 * @param {const char*} text 要追加的字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append(str_t* str, const char* text); /** * @method str_append_uppercase * 将text转换为大写,并追加到str中。 * @param {str_t*} str str对象。 * @param {const char*} text 要追加的字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_uppercase(str_t* str, const char* text); /** * @method str_append_lowercase * 将text转换为大写,并追加到str中。 * @param {str_t*} str str对象。 * @param {const char*} text 要追加的字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_lowercase(str_t* str, const char* text); /** * @method str_append_more * 追加多个字符串。以NULL结束。 * * 示例: * * ```c * str_t s; * str_init(&s, 0); * * str_append_more(&s, "abc", "123", NULL); * log_debug("%s\n", s.str); * * str_reset(&s); * ``` * @param {str_t*} str str对象。 * @param {const char*} text 要追加的字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_more(str_t* str, const char* text, ...); /** * @method str_append_with_len * 追加字符串。 * @param {str_t*} str str对象。 * @param {const char*} text 要追加的字符串。 * @param {uint32_t} len 字符串长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_with_len(str_t* str, const char* text, uint32_t len); /** * @method str_insert * 插入子字符串。 * @param {str_t*} str str对象。 * @param {uint32_t} offset 偏移量。 * @param {const char*} text 要插入的字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_insert(str_t* str, uint32_t offset, const char* text); /** * @method str_insert_with_len * 插入子字符串。 * @param {str_t*} str str对象。 * @param {uint32_t} offset 偏移量。 * @param {const char*} text 要插入的字符串。 * @param {uint32_t} len 字符串长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_insert_with_len(str_t* str, uint32_t offset, const char* text, uint32_t len); /** * @method str_remove * 删除子字符串。 * @param {str_t*} str str对象。 * @param {uint32_t} offset 偏移量。 * @param {uint32_t} len 长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_remove(str_t* str, uint32_t offset, uint32_t len); /** * @method str_append_char * 追加一个字符。 * @param {str_t*} str str对象。 * @param {char} c 要追加的字符。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_char(str_t* str, char c); /** * @method str_append_n_chars * 同一个字符追加n次。 * @param {str_t*} str str对象。 * @param {char} c 要追加的字符。 * @param {uint32_t} n 字符的个数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_n_chars(str_t* str, char c, uint32_t n); /** * @method str_append_int * 追加一个整数。 * @param {str_t*} str str对象。 * @param {int32_t} value 要追加的整数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_int(str_t* str, int32_t value); /** * @method str_append_uint32 * 追加一个uint32整数。 * @param {str_t*} str str对象。 * @param {uint32_t} value 要追加的整数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_uint32(str_t* str, uint32_t value); /** * @method str_append_int64 * 追加一个int64整数。 * @param {str_t*} str str对象。 * @param {int64_t} value 要追加的整数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_int64(str_t* str, int64_t value); /** * @method str_append_uint64 * 追加一个uint64整数。 * @param {str_t*} str str对象。 * @param {uint64_t} value 要追加的整数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_uint64(str_t* str, uint64_t value); /** * @method str_append_double * 追加一个浮点数。 * @param {str_t*} str str对象。 * @param {const char*} format 格式。 * @param {double} value 要追加的浮点数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_double(str_t* str, const char* format, double value); /** * @method str_append_json_str * 追加一个字符串,字符串前后加英文双引号,并按JSON规则转义特殊字符。 * @param {str_t*} str str对象。 * @param {const char*} json_str 待追加的字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_json_str(str_t* str, const char* json_str); /** * @method str_append_c_str * 追加一个字符串,字符串前后加英文双引号,并按C语言规则转义特殊字符。 * @param {str_t*} str str对象。 * @param {const char*} c_str 待追加的字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_c_str(str_t* str, const char* c_str); /** * @method str_append_json_int_pair * 追加int格式的json键值对。 * @param {str_t*} str str对象。 * @param {const char*} key 键。 * @param {int32_t} value 值。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_json_int_pair(str_t* str, const char* key, int32_t value); /** * @method str_append_json_str_pair * 追加字符串格式的json键值对。 * @param {str_t*} str str对象。 * @param {const char*} key 键。 * @param {const char*} value 值。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_json_str_pair(str_t* str, const char* key, const char* value); /** * @method str_append_json_double_pair * 追加doube格式的json键值对。 * @param {str_t*} str str对象。 * @param {const char*} key 键。 * @param {double} value 值。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_json_double_pair(str_t* str, const char* key, double value); /** * @method str_append_json_bool_pair * 追加bool格式的json键值对。 * @param {str_t*} str str对象。 * @param {const char*} key 键。 * @param {bool_t} value 值。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_json_bool_pair(str_t* str, const char* key, bool_t value); /** * @method str_pop * 删除最后一个字符。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_pop(str_t* str); /** * @method str_unescape * 对字符串进行反转义。如:把"\n"转换成'\n'。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_unescape(str_t* str); /** * @method str_append_escape * 对字符串s进行转义,并追加到str对象。 * @param {str_t*} str str对象。 * @param {const char*} s 字符串。 * @param {uint32_t} size 字符串s的长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_escape(str_t* str, const char* s, uint32_t size); /** * @method str_append_unescape * 对字符串s进行反转义,并追加到str对象。 * @param {str_t*} str str对象。 * @param {const char*} s 字符串。 * @param {uint32_t} size 字符串s的长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_unescape(str_t* str, const char* s, uint32_t size); /** * @method str_decode_xml_entity * 对XML基本的entity进行解码,目前仅支持&lt;&gt;&quota;&amp;。 * @param {str_t*} str str对象。 * @param {const char*} text 要解码的XML文本。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_decode_xml_entity(str_t* str, const char* text); /** * @method str_decode_xml_entity_with_len * 对XML基本的entity进行解码,目前仅支持&lt;&gt;&quota;&amp;。 * @param {str_t*} str str对象。 * @param {const char*} text 要解码的XML文本。 * @param {uint32_t} len 字符串长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_decode_xml_entity_with_len(str_t* str, const char* text, uint32_t len); /** * @method str_encode_xml_entity * 对XML基本的entity进行编码,目前仅支持&lt;&gt;&quota;&amp;。 * @param {str_t*} str str对象。 * @param {const char*} text 要编码的XML文本。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_encode_xml_entity(str_t* str, const char* text); /** * @method str_encode_xml_entity_with_len * 对XML基本的entity进行编码,目前仅支持&lt;&gt;&quota;&amp;。 * @param {str_t*} str str对象。 * @param {const char*} text 要编码的XML文本。 * @param {uint32_t} len 字符串长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_encode_xml_entity_with_len(str_t* str, const char* text, uint32_t len); /** * @method str_from_int * 用整数初始化字符串。 * @param {str_t*} str str对象。 * @param {int32_t} value 整数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_from_int(str_t* str, int32_t value); /** * @method str_from_uint32 * 用整数初始化字符串。 * @param {str_t*} str str对象。 * @param {uint32_t} value 整数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_from_uint32(str_t* str, uint32_t value); /** * @method str_from_int64 * 用整数初始化字符串。 * @param {str_t*} str str对象。 * @param {int64_t} value 整数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_from_int64(str_t* str, int64_t value); /** * @method str_from_uint64 * 用整数初始化字符串。 * @param {str_t*} str str对象。 * @param {uint64_t} value 整数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_from_uint64(str_t* str, uint64_t value); /** * @method str_from_float * 用浮点数初始化字符串。 * @param {str_t*} str str对象。 * @param {double} value 浮点数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_from_float(str_t* str, double value); /** * @method str_from_value * 用value初始化字符串。 * @param {str_t*} str str对象。 * @param {const value_t*} value value。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_from_value(str_t* str, const value_t* value); /** * @method str_from_wstr * 用value初始化字符串。 * @param {str_t*} str str对象。 * @param {const wchar_t*} wstr Unicode字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_from_wstr(str_t* str, const wchar_t* wstr); /** * @method str_from_wstr_with_len * 用value初始化字符串。 * @param {str_t*} str str对象。 * @param {const wchar_t*} wstr Unicode字符串 * @param {uint32_t} len Unicode字符串的长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_from_wstr_with_len(str_t* str, const wchar_t* wstr, uint32_t len); /** * @method str_to_int * 将字符串转成整数。 * @param {str_t*} str str对象。 * @param {int32_t*} value 用于返回整数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_to_int(str_t* str, int32_t* value); /** * @method str_to_float * 将字符串转成浮点数。 * @param {str_t*} str str对象。 * @param {double*} value 用于返回浮点数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_to_float(str_t* str, double* value); /** * @method str_encode_hex * 把二进制的数据编码成16进制格式的字符串。 * @param {str_t*} str str对象。 * @param {const void*} data 数据。 * @param {uint32_t} size 数据长度。 * @param {const char*} format 格式(如:"%02x" 表示生成小写) * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_encode_hex(str_t* str, const void* data, uint32_t size, const char* format); /** * @method str_decode_hex * 把16进制格式的字符串解码成字符串。 * @param {str_t*} str str对象。 * @param {void*} data 数据缓存区(返回)。 * @param {uint32_t} size 数据最大长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_decode_hex(str_t* str, void* data, uint32_t size); /** * @method str_end_with * 判断字符串是否以指定的子串结尾。 * @param {str_t*} str str对象。 * @param {const char*} text 子字符串。 * * @return {bool_t} 返回是否以指定的子串结尾。 */ bool_t str_end_with(str_t* str, const char* text); /** * @method str_start_with * 判断字符串是否以指定的子串开头。 * @param {str_t*} str str对象。 * @param {const char*} text 子字符串。 * * @return {bool_t} 返回是否以指定的子串开头。 */ bool_t str_start_with(str_t* str, const char* text); /** * @method str_trim * 去除首尾指定的字符。 * @param {str_t*} str str对象。 * @param {const char*} text 要去除的字符集合。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_trim(str_t* str, const char* text); /** * @method str_trim_left * 去除首部指定的字符。 * @param {str_t*} str str对象。 * @param {const char*} text 要去除的字符集合。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_trim_left(str_t* str, const char* text); /** * @method str_trim_right * 去除尾部指定的字符。 * @param {str_t*} str str对象。 * @param {const char*} text 要去除的字符集合。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_trim_right(str_t* str, const char* text); /** * @method str_replace * 字符串替换。 * @param {str_t*} str str对象。 * @param {const char*} text 待替换的子串。 * @param {const char*} new_text 将替换成的子串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_replace(str_t* str, const char* text, const char* new_text); /** * @method str_to_lower * 将字符串转成小写。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_to_lower(str_t* str); /** * @method str_to_upper * 将字符串转成大写。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_to_upper(str_t* str); /** * @method str_expand_vars * 将字符串中的变量展开为obj中对应的属性值。 * * 变量的格式为${xxx}: * * * xxx为变量名时,${xxx}被展开为obj的属性xxx的值。 * * xxx为表达式时,${xxx}被展开为表达式的值,表达式中可以用变量,$为变量的前缀,如${$x+$y}。 * * xxx为变量名时,而不存在obj的属性时,${xxx}被移出。 * * @param {str_t*} str str对象。 * @param {const char*} src 字符串。 * @param {const tk_object_t*} obj obj对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_expand_vars(str_t* str, const char* src, const tk_object_t* obj); /** * @method str_common_prefix * 计算str和other的共同前缀,并设置到str中。 * @param {str_t*} str str对象。 * @param {const char*} other 另外一个字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_common_prefix(str_t* str, const char* other); /** * @method str_reset * 重置字符串为空。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_reset(str_t* str); /** * @method str_reverse * 前后颠倒字符串。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_reverse(str_t* str); /** * @method str_count * 统计字串出现的次数。 * @param {str_t*} str str对象。 * @param {const char*} substr 字串。 * * @return {uint32_t} 返回字符串出现的次数。 */ uint32_t str_count(str_t* str, const char* substr); /** * @method str_format * 通过格式设置字符串。 * @param {str_t*} str str对象。 * @param {uint32_t} size format生成的字符串的最大长度(用于预先分配内存)。 * @param {const char*} format 格式。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_format(str_t* str, uint32_t size, const char* format, ...); /** * @method str_append_format * 通过格式追加字符串。 * @param {str_t*} str str对象。 * @param {uint32_t} size format生成的字符串的最大长度(用于预先分配内存)。 * @param {const char*} format 格式。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_format(str_t* str, uint32_t size, const char* format, ...); /** * @method str_append_json_pair * 追加json键值对。 * @param {str_t*} str str对象。 * @param {const char*} key 键。 * @param {const value_t*} value 值。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_json_pair(str_t* str, const char* key, const value_t* value); #define STR_DESTROY(str) \ if (str != NULL) { \ str_destroy(str); \ str = NULL; \ } END_C_DECLS #endif /*TK_STR_H*/
0
repos/awtk/src
repos/awtk/src/tkc/ring_buffer.c
/** * File: ring_buffer.c * Author: AWTK Develop Team * Brief: ring_buffer * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2019-10-06 Li XianJing <[email protected]> created * */ #include "tkc/mem.h" #include "tkc/ring_buffer.h" ring_buffer_t* ring_buffer_create(uint32_t init_capacity, uint32_t max_capacity) { ring_buffer_t* ring_buffer = NULL; return_value_if_fail(init_capacity >= 32, NULL); ring_buffer = TKMEM_ZALLOC(ring_buffer_t); return_value_if_fail(ring_buffer != NULL, NULL); ring_buffer->data = (uint8_t*)TKMEM_ALLOC(init_capacity); if (ring_buffer->data != NULL) { ring_buffer->capacity = init_capacity; memset(ring_buffer->data, 0x00, init_capacity); ring_buffer->max_capacity = tk_max(init_capacity, max_capacity); } else { TKMEM_FREE(ring_buffer); ring_buffer = NULL; } return ring_buffer; } bool_t ring_buffer_is_full(ring_buffer_t* ring_buffer) { return_value_if_fail(ring_buffer != NULL, FALSE); return ring_buffer->full; } bool_t ring_buffer_is_empty(ring_buffer_t* ring_buffer) { return_value_if_fail(ring_buffer != NULL, FALSE); return (ring_buffer->full == FALSE) && (ring_buffer->r == ring_buffer->w); } uint32_t ring_buffer_size(ring_buffer_t* ring_buffer) { return_value_if_fail(ring_buffer != NULL, 0); if (ring_buffer->full) { return ring_buffer->capacity; } else { if (ring_buffer->w >= ring_buffer->r) { return ring_buffer->w - ring_buffer->r; } else { return ring_buffer->capacity - (ring_buffer->r - ring_buffer->w); } } } uint32_t ring_buffer_free_size(ring_buffer_t* ring_buffer) { return_value_if_fail(ring_buffer != NULL, 0); return ring_buffer->capacity - ring_buffer_size(ring_buffer); } uint32_t ring_buffer_capacity(ring_buffer_t* ring_buffer) { return_value_if_fail(ring_buffer != NULL, 0); return ring_buffer->capacity; } ret_t ring_buffer_reset(ring_buffer_t* ring_buffer) { return_value_if_fail(ring_buffer != NULL, RET_BAD_PARAMS); ring_buffer->full = FALSE; ring_buffer->r = ring_buffer->w; memset(ring_buffer->data, 0x00, ring_buffer->capacity); return RET_OK; } ret_t ring_buffer_set_read_cursor(ring_buffer_t* ring_buffer, uint32_t r) { ring_buffer->r = r % ring_buffer->capacity; ring_buffer->full = FALSE; return RET_OK; } ret_t ring_buffer_set_read_cursor_delta(ring_buffer_t* ring_buffer, uint32_t r_delta) { return ring_buffer_set_read_cursor(ring_buffer, ring_buffer->r + r_delta); } ret_t ring_buffer_set_write_cursor(ring_buffer_t* ring_buffer, uint32_t w) { ring_buffer->w = w % ring_buffer->capacity; if (ring_buffer->r == ring_buffer->w) { ring_buffer->full = TRUE; } return RET_OK; } ret_t ring_buffer_set_write_cursor_delta(ring_buffer_t* ring_buffer, uint32_t w_delta) { return ring_buffer_set_write_cursor(ring_buffer, ring_buffer->w + w_delta); } uint32_t ring_buffer_read(ring_buffer_t* ring_buffer, void* buff, uint32_t size) { return_value_if_fail(ring_buffer != NULL && buff != NULL, 0); if (size == 0) { return 0; } if (ring_buffer->r != ring_buffer->w || ring_buffer->full) { uint32_t ret = 0; uint32_t rsize = 0; uint8_t* d = (uint8_t*)buff; uint8_t* s = ring_buffer->data + ring_buffer->r; ring_buffer->full = FALSE; if (ring_buffer->r < ring_buffer->w) { rsize = ring_buffer->w - ring_buffer->r; rsize = tk_min(rsize, size); ret = rsize; memcpy(d, s, rsize); ring_buffer_set_read_cursor_delta(ring_buffer, rsize); } else { rsize = ring_buffer->capacity - ring_buffer->r; rsize = tk_min(rsize, size); ret = rsize; memcpy(d, s, rsize); ring_buffer_set_read_cursor_delta(ring_buffer, rsize); if (rsize < size) { size -= rsize; d += rsize; s = ring_buffer->data; rsize = tk_min(ring_buffer->w, size); if (rsize > 0) { memcpy(d, s, rsize); ret += rsize; } ring_buffer_set_read_cursor(ring_buffer, rsize); } } return ret; } return 0; } uint32_t ring_buffer_peek(ring_buffer_t* ring_buffer, void* buff, uint32_t size) { uint32_t r = 0; uint32_t ret = 0; bool_t full = FALSE; return_value_if_fail(ring_buffer != NULL && buff != NULL, 0); r = ring_buffer->r; full = ring_buffer->full; ret = ring_buffer_read(ring_buffer, buff, size); ring_buffer->r = r; ring_buffer->full = full; return ret; } uint32_t ring_buffer_write(ring_buffer_t* ring_buffer, const void* buff, uint32_t size) { return_value_if_fail(ring_buffer != NULL && buff != NULL, 0); ring_buffer_ensure_write_space(ring_buffer, size); if (size == 0 || ring_buffer_free_size(ring_buffer) == 0) { return 0; } if (ring_buffer->r != ring_buffer->w || !ring_buffer->full) { uint32_t ret = 0; uint32_t rsize = 0; uint8_t* s = (uint8_t*)buff; uint8_t* d = ring_buffer->data + ring_buffer->w; if (ring_buffer->w < ring_buffer->r) { rsize = ring_buffer->r - ring_buffer->w; rsize = tk_min(rsize, size); ret = rsize; memcpy(d, s, rsize); ring_buffer_set_write_cursor_delta(ring_buffer, rsize); } else { rsize = ring_buffer->capacity - ring_buffer->w; rsize = tk_min(rsize, size); ret = rsize; memcpy(d, s, rsize); ring_buffer_set_write_cursor_delta(ring_buffer, rsize); if (rsize < size) { size -= rsize; s += rsize; d = ring_buffer->data; rsize = tk_min(ring_buffer->r, size); if (rsize > 0) { memcpy(d, s, rsize); ret += rsize; } ring_buffer_set_write_cursor(ring_buffer, rsize); } } return ret; } return 0; } ret_t ring_buffer_read_len(ring_buffer_t* ring_buffer, void* buff, uint32_t size) { return_value_if_fail(ring_buffer != NULL && buff != NULL, RET_BAD_PARAMS); if (ring_buffer_size(ring_buffer) >= size) { return ring_buffer_read(ring_buffer, buff, size) == size ? RET_OK : RET_FAIL; } else { return RET_FAIL; } } ret_t ring_buffer_skip(ring_buffer_t* ring_buffer, uint32_t size) { return_value_if_fail(ring_buffer != NULL, RET_BAD_PARAMS); if (ring_buffer_size(ring_buffer) >= size && size > 0) { ring_buffer->full = FALSE; ring_buffer->r = (ring_buffer->r + size) % ring_buffer->capacity; return RET_OK; } else { return RET_FAIL; } } ret_t ring_buffer_ensure_write_space(ring_buffer_t* ring_buffer, uint32_t size) { uint32_t free_size = ring_buffer_free_size(ring_buffer); if (free_size >= size) { return RET_OK; } else if (ring_buffer->capacity == ring_buffer->max_capacity) { return RET_FAIL; } else { uint8_t* data = NULL; uint32_t old_size = ring_buffer_size(ring_buffer); uint32_t capacity = ring_buffer->capacity + (size - free_size); return_value_if_fail(capacity <= ring_buffer->max_capacity, RET_FAIL); data = (uint8_t*)TKMEM_ALLOC(capacity); return_value_if_fail(data != NULL, RET_OOM); return_value_if_fail(ring_buffer_read_len(ring_buffer, data, old_size) == RET_OK, RET_FAIL); TKMEM_FREE(ring_buffer->data); ring_buffer->r = 0; ring_buffer->w = old_size; ring_buffer->data = data; ring_buffer->capacity = capacity; return RET_OK; } } ret_t ring_buffer_write_len(ring_buffer_t* ring_buffer, const void* buff, uint32_t size) { return_value_if_fail(ring_buffer != NULL && buff != NULL, RET_BAD_PARAMS); if (ring_buffer_ensure_write_space(ring_buffer, size) == RET_OK) { return ring_buffer_write(ring_buffer, buff, size) == size ? RET_OK : RET_FAIL; } else { return RET_FAIL; } } ret_t ring_buffer_destroy(ring_buffer_t* ring_buffer) { return_value_if_fail(ring_buffer != NULL, RET_BAD_PARAMS); TKMEM_FREE(ring_buffer->data); memset(ring_buffer, 0x00, sizeof(ring_buffer_t)); TKMEM_FREE(ring_buffer); return RET_OK; }
0
repos/awtk/src
repos/awtk/src/tkc/data_writer.h
/** * File: data_writer.h * Author: AWTK Develop Team * Brief: data_writer * * Copyright (c) 2019 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2020-02-26 Li XianJing <[email protected]> created * */ #ifndef TK_DATA_WRITER_H #define TK_DATA_WRITER_H #include "tkc/types_def.h" BEGIN_C_DECLS struct _data_writer_t; typedef struct _data_writer_t data_writer_t; typedef int32_t (*data_writer_write_t)(data_writer_t* writer, uint64_t offset, const void* data, uint32_t size); typedef ret_t (*data_writer_truncate_t)(data_writer_t* writer, uint64_t size); typedef ret_t (*data_writer_flush_t)(data_writer_t* writer); typedef ret_t (*data_writer_destroy_t)(data_writer_t* writer); typedef struct _data_writer_vtable_t { data_writer_write_t write; data_writer_truncate_t truncate; data_writer_flush_t flush; data_writer_destroy_t destroy; } data_writer_vtable_t; /** * @class data_writer_t * 数据写入接口。 * * >对可写的媒介,如内存、文件、flash和其它媒介提供一个统一的写入接口。 * */ struct _data_writer_t { const data_writer_vtable_t* vt; }; /** * @method data_writer_write * 在指定位置写入数据。 * * @param {data_writer_t*} writer writer对象。 * @param {uint64_t} offset 偏移量。 * @param {const void*} data 数据缓冲区。 * @param {uint32_t} size 数据长度。 * * @return {int32_t} 返回实际读取数据的长度。 */ int32_t data_writer_write(data_writer_t* writer, uint64_t offset, const void* data, uint32_t size); /** * @method data_writer_truncate * 截去指定长度之后的数据。 * @param {data_writer_t*} writer writer对象。 * @param {uint64_t} size 保留长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t data_writer_truncate(data_writer_t* writer, uint64_t size); /** * @method data_writer_flush * flush数据。 * @param {data_writer_t*} writer writer对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t data_writer_flush(data_writer_t* writer); /** * @method data_writer_destroy * 销毁writer对象。 * @param {data_writer_t*} writer writer对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t data_writer_destroy(data_writer_t* writer); /** * @method data_writer_clear * 清除指定URL的数据。 * @param {const char*} url URL。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t data_writer_clear(const char* url); /** * @method data_writer_write_all * 写入全部数据。 * * @param {const char*} url URL。 * @param {const void*} data 数据缓冲区。 * @param {uint32_t} size 数据长度。 * * @return {int32_t} 返回实际写入数据的长度。 */ int32_t data_writer_write_all(const char* url, const void* data, uint32_t size); #define DATA_WRITER(writer) ((data_writer_t*)(writer)) END_C_DECLS #endif /*TK_DATA_WRITER_H*/
0
repos/awtk/src
repos/awtk/src/tkc/waitable_action_darray.c
/** * File: waitable_action_darray.c * Author: AWTK Develop Team * Brief: waitable_action_darray * * Copyright (c) 2020 - 2024 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2022-3-25 vih created * */ #include "tkc/mem.h" #include "tkc/event.h" #include "tkc/waitable_action_darray.h" static ret_t waitable_action_darray_destroy_qaction(qaction_t* action) { event_t event; /* 如果有回调,则回调里必须带 qaction 销毁操作或返回 RET_NOT_IMPL(由系统进行销毁) */ event.type = EVT_DESTROY; event.target = action; if (qaction_notify(action, &event) == RET_NOT_IMPL) { action->exec = NULL; qaction_destroy(action); } return RET_OK; } int on_darray_compare(const void* iter, const void* data) { qaction_t* qaction = (qaction_t*)iter; qaction_exec_t* exec = (qaction_exec_t*)data; return ((const char*)qaction->exec - (const char*)exec); } waitable_action_darray_t* waitable_action_darray_create(uint16_t capacity) { waitable_action_darray_t* q = TKMEM_ZALLOC(waitable_action_darray_t); return_value_if_fail(q != NULL, NULL); q->darray = darray_create(capacity, NULL, on_darray_compare); goto_error_if_fail(q->darray != NULL); q->mutex = tk_mutex_create(); goto_error_if_fail(q->mutex != NULL); q->sema_recv = tk_semaphore_create(0, NULL); goto_error_if_fail(q->sema_recv != NULL); q->sema_send = tk_semaphore_create(capacity, NULL); goto_error_if_fail(q->sema_send != NULL); return q; error: if (q != NULL) { if (q->darray != NULL) { darray_destroy(q->darray); } if (q->mutex != NULL) { tk_mutex_destroy(q->mutex); } if (q->sema_recv != NULL) { tk_semaphore_destroy(q->sema_recv); } if (q->sema_send != NULL) { tk_semaphore_destroy(q->sema_send); } TKMEM_FREE(q); } return NULL; } ret_t waitable_action_darray_recv(waitable_action_darray_t* q, qaction_t** action, uint32_t timeout_ms) { ret_t ret = RET_TIMEOUT; return_value_if_fail(q != NULL && action != NULL, RET_BAD_PARAMS); if (tk_semaphore_wait(q->sema_recv, timeout_ms) == RET_OK) { if (tk_mutex_lock(q->mutex) == RET_OK) { *action = darray_head(q->darray); ret = darray_remove_index(q->darray, 0); if (ret == RET_OK) { ENSURE(tk_semaphore_post(q->sema_send) == RET_OK); } ENSURE(tk_mutex_unlock(q->mutex) == RET_OK); } } return ret; } ret_t waitable_action_darray_send(waitable_action_darray_t* q, qaction_t* action, uint32_t timeout_ms) { ret_t ret = RET_TIMEOUT; return_value_if_fail(q != NULL && action != NULL, RET_BAD_PARAMS); if (tk_semaphore_wait(q->sema_send, timeout_ms) == RET_OK) { if (tk_mutex_lock(q->mutex) == RET_OK) { ret = darray_push(q->darray, action); if (ret == RET_OK) { ENSURE(tk_semaphore_post(q->sema_recv) == RET_OK); } ENSURE(tk_mutex_unlock(q->mutex) == RET_OK); } } return ret; } qaction_t* waitable_action_darray_find_ex(waitable_action_darray_t* q, tk_compare_t cmp, void* ctx) { qaction_t* action = NULL; return_value_if_fail(q != NULL && ctx != NULL, NULL); if (tk_mutex_lock(q->mutex) == RET_OK) { action = (qaction_t*)darray_find_ex(q->darray, cmp, ctx); ENSURE(tk_mutex_unlock(q->mutex) == RET_OK); } return action; } qaction_t* waitable_action_darray_find(waitable_action_darray_t* q, qaction_exec_t exec) { return waitable_action_darray_find_ex(q, NULL, (void*)exec); } ret_t waitable_action_darray_remove_ex(waitable_action_darray_t* q, tk_compare_t cmp, void* ctx) { ret_t ret = RET_FAIL; qaction_t* action; return_value_if_fail(q != NULL && ctx != NULL, RET_BAD_PARAMS); if (tk_semaphore_wait(q->sema_recv, 0) == RET_OK) { if (tk_mutex_lock(q->mutex) == RET_OK) { action = darray_find_ex(q->darray, cmp, ctx); ret = darray_remove_ex(q->darray, cmp, ctx); if (ret == RET_OK) { ENSURE(tk_semaphore_post(q->sema_send) == RET_OK); waitable_action_darray_destroy_qaction(action); } else { ENSURE(tk_semaphore_post(q->sema_recv) == RET_OK); } ENSURE(tk_mutex_unlock(q->mutex) == RET_OK); } } return ret; } ret_t waitable_action_darray_remove(waitable_action_darray_t* q, qaction_exec_t exec) { return waitable_action_darray_remove_ex(q, NULL, (void*)exec); } ret_t waitable_action_darray_replace(waitable_action_darray_t* q, qaction_t* new_action) { return waitable_action_darray_replace_ex(q, new_action->exec, new_action); } ret_t waitable_action_darray_replace_ex(waitable_action_darray_t* q, qaction_exec_t exec, qaction_t* new_action) { ret_t ret = RET_FAIL; int32_t index; return_value_if_fail(q != NULL && exec != NULL && new_action != NULL, RET_BAD_PARAMS); if (tk_mutex_lock(q->mutex) == RET_OK) { index = darray_find_index(q->darray, exec); if (index >= 0) { qaction_t* old; old = darray_get(q->darray, index); ret = darray_replace(q->darray, index, new_action); if (ret == RET_OK) { waitable_action_darray_destroy_qaction(old); } } ENSURE(tk_mutex_unlock(q->mutex) == RET_OK); } return ret; } ret_t waitable_action_darray_destroy(waitable_action_darray_t* q) { return_value_if_fail(q != NULL, RET_BAD_PARAMS); if (tk_mutex_lock(q->mutex) == RET_OK) { while (q->darray->size) { waitable_action_darray_destroy_qaction((qaction_t*)darray_pop(q->darray)); } ENSURE(tk_mutex_unlock(q->mutex) == RET_OK); } ENSURE(darray_destroy(q->darray) == RET_OK); ENSURE(tk_semaphore_destroy(q->sema_recv) == RET_OK); ENSURE(tk_semaphore_destroy(q->sema_send) == RET_OK); ENSURE(tk_mutex_destroy(q->mutex) == RET_OK); TKMEM_FREE(q); return RET_OK; }