diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index 2a05cd63..f334a226 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -14,6 +14,10 @@ jobs: - name: install tools run: sudo apt install debhelper lcov valgrind -yy + - name: Update git submodule + run: | + git submodule update --init + - name: Build run: | xmake config -m coverage -y -v @@ -23,6 +27,11 @@ jobs: run: | xmake run run-tests --memcheck + - name: "Run tests yutil" + run: | + xmake build yutil_test + xmake run yutil_test --memcheck + - name: Upload reports to Codecov run: bash <(curl -s https://codecov.io/bash); @@ -53,6 +62,11 @@ jobs: steps: - uses: actions/checkout@master - uses: xmake-io/github-action-setup-xmake@v1 + + - name: Update git submodule + run: | + git submodule update --init + - name: Build run: | xmake config -y -v @@ -61,6 +75,11 @@ jobs: - name: "Run tests" run: | xmake run run-tests + + - name: "Run tests yutil" + run: | + xmake build yutil_test + xmake run yutil_test - name: Package run: | diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..2c94926d --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "lib/yutil"] + path = lib/yutil + url = https://gitee.com/yidianyiko/yutil.git + branch = main diff --git a/include/LCUI/font/textlayer.h b/include/LCUI/font/textlayer.h index caaba548..029d4f5c 100755 --- a/include/LCUI/font/textlayer.h +++ b/include/LCUI/font/textlayer.h @@ -102,8 +102,8 @@ typedef struct LCUI_TextLayerRec_ { LCUI_BOOL enable_mulitiline; /**< 是否启用多行文本模式 */ LCUI_BOOL enable_autowrap; /**< 是否启用自动换行模式 */ LCUI_BOOL enable_style_tag; /**< 是否使用文本样式标签 */ - LinkedList dirty_rects; /**< 脏矩形记录 */ - LinkedList text_styles; /**< 样式缓存 */ + list_t dirty_rects; /**< 脏矩形记录 */ + list_t text_styles; /**< 样式缓存 */ LCUI_TextStyleRec text_default_style; /**< 文本全局样式 */ LCUI_TextRowListRec text_rows; /**< 文本行列表 */ struct { @@ -162,7 +162,7 @@ LCUI_API void TextLayer_ClearText(LCUI_TextLayer layer); /** 插入文本内容(宽字符版) */ LCUI_API int TextLayer_InsertTextW(LCUI_TextLayer layer, const wchar_t *wstr, - LinkedList *tag_stack); + list_t *tag_stack); /** 插入文本内容 */ LCUI_API int TextLayer_InsertTextA(LCUI_TextLayer layer, const char *str); @@ -172,7 +172,7 @@ LCUI_API int TextLayer_InsertText(LCUI_TextLayer layer, const char *utf8_str); /** 追加文本内容(宽字符版) */ LCUI_API int TextLayer_AppendTextW(LCUI_TextLayer layer, const wchar_t *wstr, - LinkedList *tag_stack); + list_t *tag_stack); /** 追加文本内容 */ LCUI_API int TextLayer_AppendTextA(LCUI_TextLayer layer, @@ -183,7 +183,7 @@ LCUI_API int TextLayer_AppendText(LCUI_TextLayer layer, const char *utf8_text); /** 设置文本内容(宽字符版) */ LCUI_API int TextLayer_SetTextW(LCUI_TextLayer layer, const wchar_t *wstr, - LinkedList *tag_stack); + list_t *tag_stack); /** 设置文本内容 */ LCUI_API int TextLayer_SetTextA(LCUI_TextLayer layer, const char *ascii_text); @@ -231,7 +231,7 @@ LCUI_API void TextLayer_EnableStyleTag(LCUI_TextLayer layer, LCUI_BOOL enabled); LCUI_API void TextLayer_ReloadCharBitmap(LCUI_TextLayer layer); /** 更新数据 */ -LCUI_API void TextLayer_Update(LCUI_TextLayer layer, LinkedList *rects); +LCUI_API void TextLayer_Update(LCUI_TextLayer layer, list_t *rects); /** * 将文本图层中的指定区域的内容绘制至目标图像中 diff --git a/include/LCUI/font/textstyle.h b/include/LCUI/font/textstyle.h index f7fc07c2..3c252443 100755 --- a/include/LCUI/font/textstyle.h +++ b/include/LCUI/font/textstyle.h @@ -85,7 +85,7 @@ int TextStyle_SetDefaultFont(LCUI_TextStyle ts); /*-------------------------- StyleTag --------------------------------*/ -#define StyleTags_Init LinkedList_Init +#define StyleTags_Init list_create /** 从字符串中获取样式标签的名字及样式属性 */ LCUI_API const wchar_t *ScanStyleTag(const wchar_t *wstr, wchar_t *name, @@ -94,16 +94,16 @@ LCUI_API const wchar_t *ScanStyleTag(const wchar_t *wstr, wchar_t *name, /** 在字符串中获取样式的结束标签,输出的是标签名 */ LCUI_API const wchar_t *ScanStyleEndingTag(const wchar_t *wstr, wchar_t *name); -LCUI_API void StyleTags_Clear(LinkedList *tags); +LCUI_API void StyleTags_Clear(list_t *tags); -LCUI_API LCUI_TextStyle StyleTags_GetTextStyle(LinkedList *tags); +LCUI_API LCUI_TextStyle StyleTags_GetTextStyle(list_t *tags); /** 处理样式标签 */ -LCUI_API const wchar_t* StyleTags_GetStart(LinkedList *tags, +LCUI_API const wchar_t* StyleTags_GetStart(list_t *tags, const wchar_t *str); /** 处理样式结束标签 */ -LCUI_API const wchar_t* StyleTags_GetEnd(LinkedList *tags, +LCUI_API const wchar_t* StyleTags_GetEnd(list_t *tags, const wchar_t *str); /*------------------------- End StyleTag -----------------------------*/ diff --git a/include/LCUI/gui/css_library.h b/include/LCUI/gui/css_library.h index a3611a0a..48982f69 100644 --- a/include/LCUI/gui/css_library.h +++ b/include/LCUI/gui/css_library.h @@ -31,7 +31,7 @@ #ifndef LCUI_CSS_LIBRARY_H #define LCUI_CSS_LIBRARY_H -#include +#include LCUI_BEGIN_HEADER @@ -161,13 +161,13 @@ typedef struct LCUI_StyleSheetRec_ { typedef const LCUI_StyleSheetRec *LCUI_CachedStyleSheet; -typedef LinkedList LCUI_StyleListRec; -typedef LinkedList* LCUI_StyleList; +typedef list_t LCUI_StyleListRec; +typedef list_t* LCUI_StyleList; typedef struct LCUI_StyleListNodeRec_ { int key; LCUI_StyleRec style; - LinkedListNode node; + list_node_t node; } LCUI_StyleListNodeRec, *LCUI_StyleListNode; /** 选择器结点结构 */ @@ -246,7 +246,7 @@ LCUI_API void Selector_Update(LCUI_Selector s); LCUI_API void Selector_Delete(LCUI_Selector s); -LCUI_API int SelectorNode_GetNames(LCUI_SelectorNode sn, LinkedList *names); +LCUI_API int SelectorNode_GetNames(LCUI_SelectorNode sn, list_t *names); LCUI_API int SelectorNode_Update(LCUI_SelectorNode node); @@ -270,7 +270,7 @@ LCUI_API int LCUI_PutStyleSheet(LCUI_Selector selector, LCUI_StyleSheet in_ss, * @param[out] list 找到的样式表列表 */ LCUI_API int LCUI_FindStyleSheetFromGroup(int group, const char *name, - LCUI_Selector s, LinkedList *list); + LCUI_Selector s, list_t *list); LCUI_API LCUI_CachedStyleSheet LCUI_GetCachedStyleSheet(LCUI_Selector s); diff --git a/include/LCUI/gui/css_parser.h b/include/LCUI/gui/css_parser.h index d625b6b9..c80615df 100644 --- a/include/LCUI/gui/css_parser.h +++ b/include/LCUI/gui/css_parser.h @@ -115,7 +115,7 @@ struct LCUI_CSSParserStyleContextRec_ { void (*style_handler)(int, LCUI_Style, void *); void *style_handler_arg; - LinkedList selectors; /**< 当前匹配到的选择器列表 */ + list_t selectors; /**< 当前匹配到的选择器列表 */ LCUI_StyleSheet sheet; /**< 当前缓存的样式表 */ LCUI_CSSPropertyParser parser; /**< 当前找到的样式属性解析器 */ }; diff --git a/include/LCUI/gui/widget.h b/include/LCUI/gui/widget.h index 86ebdbd2..505e3de2 100644 --- a/include/LCUI/gui/widget.h +++ b/include/LCUI/gui/widget.h @@ -31,8 +31,8 @@ #ifndef LCUI_WIDGET_BUILD_H #define LCUI_WIDGET_BUILD_H -#include #include +#include #include #include #include diff --git a/include/LCUI/gui/widget/canvas.h b/include/LCUI/gui/widget/canvas.h index 273511e3..013894b2 100644 --- a/include/LCUI/gui/widget/canvas.h +++ b/include/LCUI/gui/widget/canvas.h @@ -42,7 +42,7 @@ struct LCUI_CanvasRenderingContextRec_ { LCUI_Color fill_color; LCUI_Graph buffer; LCUI_Widget canvas; - LinkedListNode node; + list_node_t node; float scale; int width; diff --git a/include/LCUI/gui/widget_base.h b/include/LCUI/gui/widget_base.h index a1ef330d..af06842b 100755 --- a/include/LCUI/gui/widget_base.h +++ b/include/LCUI/gui/widget_base.h @@ -31,7 +31,7 @@ #ifndef LCUI_WIDGET_BASE_H #define LCUI_WIDGET_BASE_H -#include +#include #include LCUI_BEGIN_HEADER @@ -225,7 +225,7 @@ typedef struct LCUI_WidgetRulesRec_ { typedef struct LCUI_WidgetRulesDataRec_ { LCUI_WidgetRulesRec rules; - Dict *style_cache; + dict_t *style_cache; size_t default_max_update_count; size_t progress; } LCUI_WidgetRulesDataRec, *LCUI_WidgetRulesData; @@ -259,7 +259,7 @@ typedef struct LCUI_WidgetRec_ { strlist_t classes; strlist_t status; wchar_t *title; - Dict *attributes; + dict_t *attributes; LCUI_BOOL disabled; LCUI_BOOL event_blocked; @@ -314,25 +314,25 @@ typedef struct LCUI_WidgetRec_ { LCUI_Widget parent; /** List of child widgets */ - LinkedList children; + list_t children; /** List of child widgets in descending order by z-index */ - LinkedList children_show; + list_t children_show; /** * Position in the parent->children - * this == LinkedList_Get(&this->parent->children, this.index) + * this == list_get(&this->parent->children, this.index) */ size_t index; /** * Node in the parent->children - * &this->node == LinkedList_GetNode(&this->parent->children, this.index) + * &this->node == list_get_node_by_pos(&this->parent->children, this.index) */ - LinkedListNode node; + list_node_t node; /** Node in the parent->children_shoa */ - LinkedListNode node_show; + list_node_t node_show; } LCUI_WidgetRec; /* clang-format on */ diff --git a/include/LCUI/gui/widget_helper.h b/include/LCUI/gui/widget_helper.h index c94670f2..65e726d5 100644 --- a/include/LCUI/gui/widget_helper.h +++ b/include/LCUI/gui/widget_helper.h @@ -91,7 +91,7 @@ LCUI_API void Widget_SetOpacity(LCUI_Widget w, float opacity); LCUI_API void Widget_SetBoxSizing(LCUI_Widget w, LCUI_StyleValue sizing); /** Collect all child widget that have a ref attribute specified */ -LCUI_API Dict *Widget_CollectReferences(LCUI_Widget w); +LCUI_API dict_t *Widget_CollectReferences(LCUI_Widget w); /** * Get the first widget that match the type by testing the widget itself and diff --git a/include/LCUI/gui/widget_paint.h b/include/LCUI/gui/widget_paint.h index 34626129..7e1db3ca 100644 --- a/include/LCUI/gui/widget_paint.h +++ b/include/LCUI/gui/widget_paint.h @@ -49,7 +49,7 @@ LCUI_API LCUI_BOOL Widget_InvalidateArea(LCUI_Widget widget, * @param[out] rects 输出的区域列表 * @return 无效区域的数量 */ -LCUI_API size_t Widget_GetInvalidArea(LCUI_Widget w, LinkedList *rects); +LCUI_API size_t Widget_GetInvalidArea(LCUI_Widget w, list_t *rects); /** * 将部件中的矩形区域转换成指定范围框内有效的矩形区域 diff --git a/include/LCUI/timer.h b/include/LCUI/timer.h index 492d1182..345c3963 100644 --- a/include/LCUI/timer.h +++ b/include/LCUI/timer.h @@ -33,7 +33,7 @@ LCUI_BEGIN_HEADER -typedef void (*TimerCallback)(void *); +typedef void (*timer_callback)(void *); /** * 设置定时器 @@ -48,15 +48,12 @@ typedef void (*TimerCallback)(void *); * @return * 该定时器的标识符 **/ -LCUI_API int LCUITimer_Set(long int n_ms, TimerCallback callback, - void *arg, LCUI_BOOL reuse); - /** repeatedly calls a function, with a fixed time delay between each call. */ -LCUI_API int LCUI_SetTimeout(long int n_ms, TimerCallback callback, +LCUI_API int lcui_set_timeout(long int n_ms, timer_callback callback, void *arg); /** set a timer which execute a function once after the timer expires. */ -LCUI_API int LCUI_SetInterval(long int n_ms, TimerCallback callback, +LCUI_API int lcui_set_interval(long int n_ms, timer_callback callback, void *arg); /** @@ -68,7 +65,7 @@ LCUI_API int LCUI_SetInterval(long int n_ms, TimerCallback callback, * @return * 正常返回0,指定ID的定时器不存在则返回-1. */ -LCUI_API int LCUITimer_Free(int timer_id); +LCUI_API int lcui_destroy_timer(int timer_id); /** * 暂停定时器的倒计时 @@ -78,7 +75,7 @@ LCUI_API int LCUITimer_Free(int timer_id); * @return * 正常返回0,指定ID的定时器不存在则返回-1. * */ -LCUI_API int LCUITimer_Pause(int timer_id); +LCUI_API int lcui_pause_timer(int timer_id); /** * 继续定时器的倒计时 @@ -87,7 +84,7 @@ LCUI_API int LCUITimer_Pause(int timer_id); * @return * 正常返回0,指定ID的定时器不存在则返回-1. * */ -LCUI_API int LCUITimer_Continue(int timer_id); +LCUI_API int lcui_continue_timer(int timer_id); /** * 重设定时器的等待时间 @@ -98,16 +95,16 @@ LCUI_API int LCUITimer_Continue(int timer_id); * @return * 正常返回0,指定ID的定时器不存在则返回-1. * */ -LCUI_API int LCUITimer_Reset(int timer_id, long int n_ms); +LCUI_API int lcui_reset_timer(int timer_id, long int n_ms); /* Process all active timers */ -LCUI_API size_t LCUI_ProcessTimers(void); +LCUI_API size_t lcui_process_timers(); /* Init the timer module */ -LCUI_API void LCUI_InitTimer(void); +LCUI_API void lcui_init_timers(); /* Free the timer module */ -LCUI_API void LCUI_FreeTimer(void); +LCUI_API void lcui_destroy_timers(); LCUI_END_HEADER diff --git a/include/LCUI/util.h b/include/LCUI/util.h index 8dc18bc2..bdd20e4b 100644 --- a/include/LCUI/util.h +++ b/include/LCUI/util.h @@ -30,22 +30,13 @@ #ifndef LCUI_UTIL_H #define LCUI_UTIL_H -#include -#include -#include -#include -#include -#include +#include #include #include #include -#include -#include -#include #include #include -#include #include #include -#include + #endif diff --git a/include/LCUI/util/charset.h b/include/LCUI/util/charset.h deleted file mode 100644 index 9f137091..00000000 --- a/include/LCUI/util/charset.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * charset.h -- The charset opreation set. - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef LCUI_UTIL_CHARSET_H -#define LCUI_UTIL_CHARSET_H - -LCUI_BEGIN_HEADER - -enum EncodingType { ENCODING_ANSI, ENCODING_UTF8 }; - -#define LCUI_DecodeUTF8String(WSTR, STR, MAX_LEN) \ - LCUI_DecodeString(WSTR, STR, MAX_LEN, ENCODING_UTF8) - -#define LCUI_EncodeUTF8String(STR, WSTR, MAX_LEN) \ - LCUI_EncodeString(STR, WSTR, MAX_LEN, ENCODING_UTF8) - -LCUI_API size_t LCUI_DecodeString(wchar_t *wstr, const char *str, - size_t max_len, int encoding); - -LCUI_API size_t LCUI_EncodeString(char *str, const wchar_t *wstr, - size_t max_len, int encoding); -LCUI_END_HEADER - -#endif diff --git a/include/LCUI/util/dict.h b/include/LCUI/util/dict.h deleted file mode 100644 index 38150b44..00000000 --- a/include/LCUI/util/dict.h +++ /dev/null @@ -1,252 +0,0 @@ -/* Hash Tables Implementation. - * - * This file implements in-memory hash tables with insert/del/replace/find/ - * get-random-element operations. Hash tables will auto-resize if needed - * tables of power of two in size are used, collisions are handled by - * chaining. See the source code for more information... :) - * - * Copyright (c) 2006-2012, Salvatore Sanfilippo - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include - -#ifndef LCUI_UTIL_DICT_H -#define LCUI_UTIL_DICT_H - -LCUI_BEGIN_HEADER - -/** 哈希表节点结构 */ -typedef struct DictEntry { - void *key; - union { - void *val; - uint64_t u64; - int64_t s64; - } v; - struct DictEntry *next; /**< 指向下一个哈希节点(形成链表) */ -} DictEntry; - -/** 字典内数据的类型 */ -typedef struct DictType { - unsigned int(*hashFunction)(const void *key); - void *(*keyDup)(void *privdata, const void *key); - void *(*valDup)(void *privdata, const void *obj); - int(*keyCompare)(void *privdata, const void *key1, const void *key2); - void(*keyDestructor)(void *privdata, void *key); - void(*valDestructor)(void *privdata, void *obj); -} DictType; - -/** 哈希表结构 */ -typedef struct DictHashTable { - DictEntry **table; /**< 节点指针数组 */ - unsigned long size; /**< 桶的数量 */ - unsigned long sizemask; /**< mask 码,用于地址索引计算 */ - unsigned long used; /**< 已有节点数量 */ -} DictHashTable; - -/** 字典结构 */ -typedef struct Dict { - DictType *type; /**< 为哈希表中不同类型的值所使用的一族函数 */ - void *privdata; - DictHashTable ht[2]; /**< 每个字典使用两个哈希表 */ - int rehashidx; /**< rehash 进行到的索引位置,如果没有在 rehash ,就为 -1 */ - int iterators; /**< 当前正在使用的 iterator 的数量 */ -} Dict; - -/** 用于遍历字典的迭代器 */ -typedef struct DictIterator { - Dict *d; /**< 迭代器所指向的字典 */ - int table; /**< 使用的哈希表号码 */ - int index; /**< 迭代进行的索引 */ - int safe; /**< 是否安全 */ - DictEntry *entry; /**< 指向哈希表的当前节点 */ - DictEntry *next_entry; /**< 指向哈希表的下个节点 */ -} DictIterator; - -#define DICT_HT_INITIAL_SIZE 4 - -#define Dict_FreeVal(d, entry) \ - if ((d)->type->valDestructor) \ - (d)->type->valDestructor((d)->privdata, (entry)->v.val) - -#define Dict_SetVal(d, entry, _val_) do { \ - if ((d)->type->valDup) \ - entry->v.val = (d)->type->valDup((d)->privdata, _val_); \ - else \ - entry->v.val = (_val_); \ -} while(0) - -#define Dict_SetSignedIntegerVal(entry, _val_) \ - do { entry->v.s64 = _val_; } while(0) - -#define Dict_SetUnsignedIntegerVal(entry, _val_) \ - do { entry->v.u64 = _val_; } while(0) - -#define Dict_FreeKey(d, entry) \ - if ((d)->type->keyDestructor) \ - (d)->type->keyDestructor((d)->privdata, (entry)->key) - -#define Dict_SetKey(d, entry, _key_) do { \ - if ((d)->type->keyDup) \ - entry->key = (d)->type->keyDup((d)->privdata, _key_); \ - else \ - entry->key = (_key_); \ -} while(0) - -#define Dict_CompareKeys(d, key1, key2) \ - (((d)->type->keyCompare) ? \ - (d)->type->keyCompare((d)->privdata, key1, key2) : \ - (key1) == (key2)) - -#define Dict_HashKey(d, key) (d)->type->hashFunction(key) -#define DictEntry_GetKey(he) ((he)->key) -#define DictEntry_GetVal(he) ((he)->v.val) -#define DictEntry_GetSignedIntegerVal(he) ((he)->v.s64) -#define DictEntry_GetUnsignedIntegerVal(he) ((he)->v.u64) -#define Dict_Slots(d) ((d)->ht[0].size+(d)->ht[1].size) -#define Dict_Size(d) ((d)->ht[0].used+(d)->ht[1].used) -#define Dict_IsRehashing(ht) ((ht)->rehashidx != -1) - -/** 创建一个新字典 */ -LCUI_API Dict *Dict_Create(DictType *type, void *privdata); - -/** 对字典进行扩展 */ -LCUI_API int Dict_Expand(Dict *d, unsigned long size); - -/** - * 将元素添加到目标哈希表中 - * @param[in] d 字典指针 - * @param[in] key 新元素的关键字 - * @param[in] val 新元素的值 - * @returns 添加成功为 0,添加出错为 -1 - */ -LCUI_API int Dict_Add(Dict *d, void *key, void *val); -/** - * 将元素添加到目标哈希表中 - * 功能与 Dict_Add() 相同,但必须指定 valDup 才能添加成功 -*/ -LCUI_API int Dict_AddCopy(Dict *d, void *key, const void *val); - -/** 添加元素的底层实现函数(由 Dict_Add 调用) */ -LCUI_API DictEntry *Dict_AddRaw(Dict *d, void *key); - -/** - * 将新元素添加到字典,如果 key 已经存在,那么新元素覆盖旧元素。 - * @param[in] key 新元素的关键字 - * @param[in] val 新元素的值 - * @return 1 key 不存在,新建元素添加成功 - * @return 0 key 已经存在,旧元素被新元素覆盖 - */ -LCUI_API int Dict_Replace(Dict *d, void *key, void *val); -LCUI_API DictEntry *Dict_ReplaceRaw(Dict *d, void *key); -LCUI_API int Dict_Delete(Dict *d, const void *key); -LCUI_API int Dict_DeleteNoFree(Dict *d, const void *key); - -/** 删除字典,释放内存资源 */ -LCUI_API void Dict_Release(Dict *d); - -/** - * 在字典中按指定的 key 查找 - * 查找过程是典型的 separate chaining find 操作 - * 具体参见:http://en.wikipedia.org/wiki/Hash_table#Separate_chaining - */ -LCUI_API DictEntry * Dict_Find(Dict *d, const void *key); - -/** 查找给定 key 在字典 d 中的值 */ -LCUI_API void *Dict_FetchValue(Dict *d, const void *key); - -/** 重新调整字典的大小,缩减多余空间 */ -LCUI_API int Dict_Resize(Dict *d); - -/** - * 创建一个迭代器,用于遍历哈希表节点。 - * - * safe 属性指示迭代器是否安全,如果迭代器是安全的,那么它可以在遍历的过程中 - * 进行增删操作,反之,如果迭代器是不安全的,那么它只能执行 Dict_Next 操作。 - * - * 因为迭代进行的时候可以对列表的当前节点进行修改,为了避免修改造成指针丢失, - * 所以不仅要有指向当前节点的 entry 属性,还需要指向下一节点的 next_entry 属性 - */ -LCUI_API DictIterator *Dict_GetIterator(Dict *d); - -/** 创建一个安全迭代器 */ -LCUI_API DictIterator *Dict_GetSafeIterator(Dict *d); - -/** 迭代器的推进函数 */ -LCUI_API DictEntry *Dict_Next(DictIterator *iter); - -/** 删除迭代器 */ -LCUI_API void Dict_ReleaseIterator(DictIterator *iter); - -/** 从字典中随机获取一项 */ -LCUI_API DictEntry *Dict_GetRandomKey(Dict *d); - -/** 打印字典的统计信息 */ -LCUI_API void Dict_PrintStats(Dict *d); - -LCUI_API unsigned int Dict_GenHashFunction(const unsigned char *buf, int len); -LCUI_API unsigned int Dict_GenCaseHashFunction(const unsigned char *buf, int len); -LCUI_API unsigned int Dict_IntHashFunction(unsigned int key); - -/* Identity hash function for integer keys */ -LCUI_API unsigned int Dict_IdentityHashFunction(unsigned int key); - -/** 清空字典 */ -LCUI_API void Dict_Empty(Dict *d); -LCUI_API void Dict_EnableResize(void); -LCUI_API void Dict_DisableResize(void); - -/** - * 字典的 rehash 函数 - * @param[in] n 要执行 rehash 的元素数量 - * @return 0 所有元素 rehash 完毕 - * @return 1 还有元素没有 rehash -*/ -LCUI_API int Dict_Rehash(Dict *d, int n); - -/* - * 在指定的时间内完成 rehash 操作 - * @param[in] ms 进行 rehash 的时间,以毫秒为单位 - * @returns rehashes 完成 rehash 的元素的数量 - */ -LCUI_API int Dict_RehashMilliseconds(Dict *d, int ms); -LCUI_API void Dict_SetHashFunctionSeed(unsigned int initval); -LCUI_API unsigned int Dict_GetHashFunctionSeed(void); - -LCUI_API unsigned int StringKeyDict_KeyHash(const void *key); -LCUI_API int StringKeyDict_KeyCompare(void *privdata, const void *key1, - const void *key2); -LCUI_API void *StringKeyDict_KeyDup(void *privdata, const void *key); -LCUI_API void StringKeyDict_KeyDestructor(void *privdata, void *key); - -LCUI_API void Dict_InitStringKeyType(DictType *t); -LCUI_API void Dict_InitStringCopyKeyType(DictType *t); - -LCUI_END_HEADER - -#endif /* LCUI_UTIL_DICT_H */ diff --git a/include/LCUI/util/dirent.h b/include/LCUI/util/dirent.h deleted file mode 100644 index df2d9ca0..00000000 --- a/include/LCUI/util/dirent.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * dirent.h -- Directory entry operation set. - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef LCUI_UTIL_DIRENT_H -#define LCUI_UTIL_DIRENT_H - -LCUI_BEGIN_HEADER - -#ifdef _WIN32 -#include -typedef HANDLE LCUI_DirHandle; -typedef union LCUI_DirEntry_ { - WIN32_FIND_DATAA dataA; - WIN32_FIND_DATAW dataW; -} LCUI_DirEntry; - -#define PATH_DELIMITER '\\' -#else -#include -#define LCUI_DIRENT_NAME_LEN 256 - -typedef DIR* LCUI_DirHandle; -typedef struct LCUI_DirEntry_ { - struct dirent dirent; - wchar_t name[LCUI_DIRENT_NAME_LEN]; -} LCUI_DirEntry; - -#define PATH_DELIMITER '/' - -#endif - -typedef struct LCUI_Dir_ { - LCUI_DirHandle handle; - LCUI_DirEntry entry; - int cached; -} LCUI_Dir; - -#if defined(_UNICODE) || !defined(_WIN32) -#define LCUI_OpenDir LCUI_OpenDirW -#define LCUI_ReadDir LCUI_ReadDirW -#define LCUI_GetFileName LCUI_GetFileNameW -#else -#define LCUI_OpenDir LCUI_OpenDirA -#define LCUI_ReadDir LCUI_ReadDirA -#define LCUI_GetFileName LCUI_GetFileNameA -#endif - - -LCUI_API int LCUI_OpenDirW(const wchar_t *filepath, LCUI_Dir *dir); - -LCUI_API int LCUI_OpenDirA(const char *filepath, LCUI_Dir *dir); - -LCUI_API LCUI_DirEntry* LCUI_ReadDirA(LCUI_Dir *dir); - -LCUI_API LCUI_DirEntry* LCUI_ReadDirW(LCUI_Dir *dir); - -LCUI_API int LCUI_CloseDir(LCUI_Dir *dir); - -LCUI_API char *LCUI_GetFileNameA(LCUI_DirEntry *entry); - -LCUI_API wchar_t *LCUI_GetFileNameW(LCUI_DirEntry *entry); - -LCUI_API int LCUI_FileIsDirectory(LCUI_DirEntry *entry); - -LCUI_API int LCUI_FileIsRegular(LCUI_DirEntry *entry); - -LCUI_END_HEADER - -#endif diff --git a/include/LCUI/util/event.h b/include/LCUI/util/event.h index 915cdb7a..6d1eb0bb 100644 --- a/include/LCUI/util/event.h +++ b/include/LCUI/util/event.h @@ -43,8 +43,8 @@ typedef void(*LCUI_EventFunc)(LCUI_Event, void*); typedef struct LCUI_EventTriggerRec_ { int handler_base_id; /**< 事件处理器ID */ - RBTree events; /**< 事件绑定记录 */ - RBTree handlers; /**< 事件处理器记录 */ + rbtree_t events; /**< 事件绑定记录 */ + rbtree_t handlers; /**< 事件处理器记录 */ } LCUI_EventTriggerRec, *LCUI_EventTrigger; /** 构建一个事件触发器 */ diff --git a/include/LCUI/util/linkedlist.h b/include/LCUI/util/linkedlist.h deleted file mode 100644 index f593ec3a..00000000 --- a/include/LCUI/util/linkedlist.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * linkedlist.h -- Linked list - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef LCUI_UTIL_LINKEDLIST_H -#define LCUI_UTIL_LINKEDLIST_H - -LCUI_BEGIN_HEADER - -typedef struct LinkedListNodeRec_ LinkedListNode; -typedef struct LinkedListRec_ LinkedList; - -struct LinkedListNodeRec_ { - void *data; - LinkedListNode *prev, *next; -}; - -struct LinkedListRec_ { - size_t length; - LinkedListNode head, tail; -}; - -#define LinkedList_Each(node, list) \ - node = (list)->head.next; node; node = node->next - -#define LinkedList_EachReverse(node, list) \ - node = (list)->tail.prev; node && node != &(list)->head; node = node->prev - -#define LinkedList_ForEach(node, list) for( LinkedList_Each(node, list) ) -#define LinkedList_ForEachReverse(node, list) for( LinkedList_EachReverse(node, list) ) - -LCUI_API LinkedListNode *LinkedList_Append(LinkedList *list, void *data); -LCUI_API LinkedListNode *LinkedList_Insert(LinkedList *list, size_t pos, void *data); -LCUI_API LinkedListNode *LinkedList_GetNode(const LinkedList *list, size_t pos); -LCUI_API LinkedListNode *LinkedList_GetNodeAtTail(const LinkedList *list, size_t pos); -LCUI_API void LinkedList_Init(LinkedList *list); -LCUI_API void *LinkedList_Get(const LinkedList *list, size_t pos); -LCUI_API void LinkedList_Unlink(LinkedList *list, LinkedListNode *node); -LCUI_API void LinkedList_Link(LinkedList *list, LinkedListNode *cur, LinkedListNode *node); -LCUI_API void LinkedList_Delete(LinkedList *list, size_t pos); -LCUI_API void LinkedList_DeleteNode(LinkedList *list, LinkedListNode *node); -LCUI_API void LinkedList_AppendNode(LinkedList *list, LinkedListNode *node); -LCUI_API void LinkedList_InsertNode(LinkedList *list, size_t pos, LinkedListNode *node); -LCUI_API void LinkedList_ClearEx(LinkedList *list, void(*on_destroy)(void*), int free_node); -LCUI_API void LinkedList_Concat(LinkedList *list1, LinkedList *list2); -LCUI_API void LinkedListNode_Delete(LinkedListNode *node); - -#define LinkedList_Clear(list, func) LinkedList_ClearEx( list, func, 1 ) -#define LinkedList_ClearData(list, func) LinkedList_ClearEx( list, func, 0 ) - -LCUI_END_HEADER - -#endif diff --git a/include/LCUI/util/logger.h b/include/LCUI/util/logger.h deleted file mode 100644 index 93788511..00000000 --- a/include/LCUI/util/logger.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * logger.h -- Logger module - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef LCUI_UTIL_LOGGER_H -#define LCUI_UTIL_LOGGER_H - -LCUI_BEGIN_HEADER - -typedef enum LoggerLevel { - LOGGER_LEVEL_ALL, - LOGGER_LEVEL_DEBUG, - LOGGER_LEVEL_INFO, - LOGGER_LEVEL_WARNING, - LOGGER_LEVEL_ERROR, - LOGGER_LEVEL_OFF -} LoggerLevel; - -LCUI_API void Logger_SetLevel(LoggerLevel level); - -LCUI_API int Logger_Log(LoggerLevel level, const char* fmt, ...); - -LCUI_API int Logger_LogW(LoggerLevel level, const wchar_t* fmt, ...); - -LCUI_API void Logger_SetHandler(void (*handler)(const char*)); - -LCUI_API void Logger_SetHandlerW(void (*handler)(const wchar_t*)); - -#define Logger_Info(fmt, ...) Logger_Log(LOGGER_LEVEL_INFO, fmt, ##__VA_ARGS__) -#define Logger_Debug(fmt, ...) \ - Logger_Log(LOGGER_LEVEL_DEBUG, fmt, ##__VA_ARGS__) -#define Logger_Warning(fmt, ...) \ - Logger_Log(LOGGER_LEVEL_WARNING, fmt, ##__VA_ARGS__) -#define Logger_Error(fmt, ...) \ - Logger_Log(LOGGER_LEVEL_ERROR, fmt, ##__VA_ARGS__) -#define Logger_InfoW(fmt, ...) \ - Logger_LogW(LOGGER_LEVEL_INFO, fmt, ##__VA_ARGS__) -#define Logger_DebugW(fmt, ...) \ - Logger_LogW(LOGGER_LEVEL_DEBUG, fmt, ##__VA_ARGS__) -#define Logger_WarningW(fmt, ...) \ - Logger_LogW(LOGGER_LEVEL_WARNING, fmt, ##__VA_ARGS__) -#define Logger_ErrorW(fmt, ...) \ - Logger_LogW(LOGGER_LEVEL_ERROR, fmt, ##__VA_ARGS__) - -LCUI_END_HEADER - -#endif diff --git a/include/LCUI/util/math.h b/include/LCUI/util/math.h deleted file mode 100644 index 42d9b7a6..00000000 --- a/include/LCUI/util/math.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * math.h -- Some extension functions for math. - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef LCUI_UTIL_MATH_H -#define LCUI_UTIL_MATH_H - -#ifndef max -#define max(a,b) (((a) > (b)) ? (a) : (b)) -#endif - -#ifndef min -#define min(a,b) (((a) < (b)) ? (a) : (b)) -#endif - -LCUI_BEGIN_HEADER - -/** round double to interger */ -#define iround(X) (X < 0 ? (int)(X - 0.5) : (int)(X + 0.5)) - -LCUI_END_HEADER - -#endif diff --git a/include/LCUI/util/object.h b/include/LCUI/util/object.h index c61deb45..8e25f7cc 100644 --- a/include/LCUI/util/object.h +++ b/include/LCUI/util/object.h @@ -31,7 +31,7 @@ #define LCUI_OBJECT_H #include -#include +#include LCUI_BEGIN_HEADER @@ -62,7 +62,7 @@ typedef struct LCUI_ObjectRec_ { void *data; } value; size_t size; - LinkedList *watchers; + list_t *watchers; } LCUI_ObjectRec; LCUI_API LCUI_ObjectType ObjectType_New(const char *name); diff --git a/include/LCUI/util/rbtree.h b/include/LCUI/util/rbtree.h deleted file mode 100644 index 78567f6b..00000000 --- a/include/LCUI/util/rbtree.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * rbtree.h -- Red Black Trees - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef LCUI_UTIL_RBTREE_H -#define LCUI_UTIL_RBTREE_H - -LCUI_BEGIN_HEADER - -typedef struct RBTreeNodeRec_ RBTreeNode; - -struct RBTreeNodeRec_ { - unsigned char color; - int key; - union { - void *data; - char *str; - }; - RBTreeNode *parent, *left, *right; -}; - -typedef struct RBTreeRec_ { - int total_node; - int(*compare)(void*, const void*); - void(*destroy)(void*); - RBTreeNode *root; -} RBTree; - -#define RBTree_GetTotal(rbt) (rbt)->total_node; -#define RBTree_OnCompare(rbt, func) (rbt)->compare = func -#define RBTree_OnDestroy(rbt, func) (rbt)->destroy = func - -LCUI_API void RBTree_Init(RBTree *rbt); -LCUI_API void RBTree_Destroy(RBTree *rbt); -LCUI_API RBTreeNode *RBTree_First(const RBTree *rbt); -LCUI_API RBTreeNode *RBTree_Next(const RBTreeNode *node); -LCUI_API RBTreeNode* RBTree_Search(RBTree* rbt, int key); -LCUI_API void* RBTree_GetData(RBTree* rbt, int key); -LCUI_API RBTreeNode* RBTree_Insert(RBTree *rbt, int key, void *data); -LCUI_API int RBTree_Erase(RBTree *rbt, int key); -LCUI_API void RBTree_EraseNode(RBTree *rbt, RBTreeNode *node); -LCUI_API int RBTree_CustomErase(RBTree *rbt, const void *keydata); -LCUI_API RBTreeNode* RBTree_CustomSearch(RBTree* rbt, const void *keydata); -LCUI_API void* RBTree_CustomGetData(RBTree* rbt, const void *keydata); -LCUI_API RBTreeNode* RBTree_CustomInsert(RBTree *rbt, const void *keydata, void *data); - -LCUI_END_HEADER - -#endif diff --git a/include/LCUI/util/rect.h b/include/LCUI/util/rect.h index c27a646c..2bdd8172 100644 --- a/include/LCUI/util/rect.h +++ b/include/LCUI/util/rect.h @@ -125,16 +125,16 @@ INLINE LCUI_BOOL LCUIRect_IsEquals(const LCUI_Rect *a, const LCUI_Rect *b) a->height == b->height; } -LCUI_API int RectList_AddEx(LinkedList *list, LCUI_Rect *rect, +LCUI_API int RectList_AddEx(list_t *list, LCUI_Rect *rect, LCUI_BOOL auto_merge); /** 添加一个脏矩形记录 */ -LCUI_API int RectList_Add(LinkedList *list, LCUI_Rect *rect); +LCUI_API int RectList_Add(list_t *list, LCUI_Rect *rect); /** 删除脏矩形 */ -LCUI_API int RectList_Delete(LinkedList *list, LCUI_Rect *rect); +LCUI_API int RectList_Delete(list_t *list, LCUI_Rect *rect); -#define RectList_Clear(LIST) LinkedList_Clear(LIST, free) +#define RectList_Clear(LIST) list_destroy(LIST, free) LCUI_END_HEADER diff --git a/include/LCUI/util/string.h b/include/LCUI/util/string.h deleted file mode 100644 index be7f6a3b..00000000 --- a/include/LCUI/util/string.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * string.h -- The string operation set. - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef LCUI_UTIL_STRING_H -#define LCUI_UTIL_STRING_H - -LCUI_BEGIN_HEADER - -/** strdup() 的再实现版本,用于清除编译错误 */ -LCUI_API char *strdup2(const char *str); -LCUI_API wchar_t *wcsdup2(const wchar_t *str); - -/** 计算字符串占用的内存空间大小 */ -LCUI_API size_t strsize(const char *str); -LCUI_API size_t wcssize(const wchar_t *str); - -/** 将字符串中的字母转成小写字母 */ -LCUI_API size_t strtolower(char *outstr, const char *instr); - -LCUI_API size_t strntolower(char *outstr, size_t max_len, const char *instr); - -/** - * 清除字符串首尾的字符 - * @param[out] outstr 处理后的字符串 - * @param[in] instr 需要处理的字符串 - * @param[in] charlist 需要清除的字符列表,当为NULL时,默认清除空白符 - * @return 处理后的字符串的长度 - */ -LCUI_API size_t strtrim(char *outstr, const char *instr, const char *charlist); -LCUI_API size_t wcstrim(wchar_t *outstr, const wchar_t *instr, - const wchar_t *charlist); - -LCUI_API unsigned strhash(unsigned hash, const char *str); - -/** - * 字符串替换 - * @param[in][out] str 需要处理的字符串,替换成功后字符串内容也会被修改 - * @param[in] max_len 输出字符串的最大长度 - * @param[in] substr 字符串中需要被替换的子字符串 - * @param[in] newstr 替换的新字符串 - * @returns 替换后的字符串长度,若未替换,则返回 0 - */ -LCUI_API size_t wcsreplace(wchar_t *str, size_t max_len, const wchar_t *substr, - const wchar_t *newstr); - -LCUI_API size_t strreplace(char *str, size_t max_len, const char *substr, - const char *newstr); - -/** - * 分割命令行字符串 - * @param[in] cmd 需分割的命令行字符串 - * @param[out] outargv 分割后的命令行参数列表 - * @return 参数数量 - */ -LCUI_API int cmdsplit(const char *cmd, char ***outargv); - -/** - * 分割字符串 - * @param[in] instr 需分割的字符串 - * @param[in] sep 分割标记字符串 - * @param[out] outstrs 分割后的字符串列表 - */ -LCUI_API int strsplit(const char *instr, const char *sep, char ***outstrs); - -LCUI_END_HEADER - -#endif diff --git a/include/LCUI/util/strlist.h b/include/LCUI/util/strlist.h deleted file mode 100644 index 60797c1d..00000000 --- a/include/LCUI/util/strlist.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * strlist.h -- string list - * - * Copyright (c) 2019, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef LCUI_UTIL_STRLIST_H -#define LCUI_UTIL_STRLIST_H - -typedef char** strlist_t; - -LCUI_API int sortedstrlist_add(strlist_t *strlist, const char *str); - -LCUI_API int strlist_add_one(strlist_t *strlist, const char *str); - -LCUI_API int strlist_remove_one(strlist_t *strlist, const char *str); - -/** - * 向字符串组添加字符串 - * @param[in][out] strlist 字符串组 - * @param[in] str 字符串 - */ -LCUI_API int strlist_add(strlist_t *strlist, const char *str); - -/** - * 判断字符串组中是否包含指定字符串 - * @param[in][out] strlist 字符串组 - * @param[in] str 字符串 - * @returns 如果包含则返回 1, 否则返回 0 - */ -LCUI_API int strlist_has(strlist_t strlist, const char *str); - -/** - * 从字符串组中移除指定字符串 - * @param[in][out] strlist 字符串组 - * @param[in] str 字符串 - * @returns 如果删除成功则返回 1, 否则返回 0 - */ -LCUI_API int strlist_remove(strlist_t *strlist, const char *str); - -/** - * 向已排序的字符串组添加字符串 - * @param[in][out] strlist 字符串组 - * @param[in] str 字符串 - */ -LCUI_API int sortedstrlist_add(strlist_t *strlist, const char *str); - -/** 释放字符串组 */ -LCUI_API void strlist_free(strlist_t strs); - -#endif diff --git a/include/LCUI/util/strpool.h b/include/LCUI/util/strpool.h deleted file mode 100644 index 19484f1f..00000000 --- a/include/LCUI/util/strpool.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * strpool.h -- string pool - * - * Copyright (c) 2019, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef LCUI_UTIL_STRPOOL_H -#define LCUI_UTIL_STRPOOL_H - -typedef struct strpool strpool_t; - -LCUI_API strpool_t *strpool_create(void); - -LCUI_API char *strpool_alloc_str(strpool_t *pool, const char *str); - -LCUI_API int strpool_free_str(char *str); - -LCUI_API size_t strpool_size(strpool_t *pool); - -LCUI_API void strpool_destroy(strpool_t *pool); - -#endif diff --git a/include/LCUI/util/time.h b/include/LCUI/util/time.h deleted file mode 100644 index e0222f89..00000000 --- a/include/LCUI/util/time.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * time.c -- The time operation set. - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef LCUI_UTIL_TIME_H -#define LCUI_UTIL_TIME_H - -LCUI_BEGIN_HEADER - -LCUI_API void LCUITime_Init(void); - -LCUI_API int64_t LCUI_GetTime(void); - -LCUI_API int64_t LCUI_GetTimeDelta(int64_t start); - -LCUI_API void LCUI_Sleep(unsigned int s); - -LCUI_API void LCUI_MSleep(unsigned int ms); - - -LCUI_END_HEADER - -#endif diff --git a/include/LCUI_Build.h b/include/LCUI_Build.h index fcea9aa7..3bcbd530 100755 --- a/include/LCUI_Build.h +++ b/include/LCUI_Build.h @@ -60,7 +60,7 @@ #endif #define _DEBUG_MSG(format, ...) \ - Logger_Log(LOGGER_LEVEL_DEBUG, __FILE__ " %d: %s(): " format, \ + logger_log(LOGGER_LEVEL_DEBUG, __FILE__ " %d: %s(): " format, \ __LINE__, __FUNCTION__, ##__VA_ARGS__) #ifdef __cplusplus diff --git a/lib/css/src/css_library.c b/lib/css/src/css_library.c index 8daeebe6..91017370 100644 --- a/lib/css/src/css_library.c +++ b/lib/css/src/css_library.c @@ -74,7 +74,7 @@ typedef struct NamesFinderRec_ { /** 样式链接记录组 */ typedef struct StyleLinkGroupRec_ { - Dict *links; /**< 样式链接表 */ + dict_t *links; /**< 样式链接表 */ char *name; /**< 选择器名称 */ LCUI_SelectorNode snode; /**< 选择器结点 */ } StyleLinkGroupRec, *StyleLinkGroup; @@ -86,30 +86,30 @@ typedef struct StyleNodeRec_ { char *space; /**< 所属的空间 */ char *selector; /**< 选择器 */ LCUI_StyleList list; /**< 样式表 */ - LinkedListNode node; /**< 在链表中的结点 */ + list_node_t node; /**< 在链表中的结点 */ } StyleNodeRec, *StyleNode; /** 样式链接记录 */ typedef struct StyleLinkRec_ { char *selector; /**< 选择器 */ StyleLinkGroup group; /**< 所属组 */ - LinkedList styles; /**< 作用于当前选择器的样式 */ - Dict *parents; /**< 父级节点 */ + list_t styles; /**< 作用于当前选择器的样式 */ + dict_t *parents; /**< 父级节点 */ } StyleLinkRec, *StyleLink; static struct { LCUI_BOOL active; - LinkedList groups; /**< 样式组列表 */ - Dict *cache; /**< 样式表缓存,以选择器的 hash 值索引 */ - Dict *names; /**< 样式属性名称表,以值的名称索引 */ - Dict *value_keys; /**< 样式属性值表,以值的名称索引 */ - Dict *value_names; /**< 样式属性值名称表,以值索引 */ - DictType names_dict; /**< 样式属性名称表的类型 */ - DictType value_keys_dict; /**< 样式属性值表的类型 */ - DictType value_names_dict; /**< 样式属性值名称表的类型 */ - DictType style_link_dict; /**< 样式链接表的类型 */ - DictType style_group_dict; /**< 样式组的类型 */ - DictType cache_dict; /**< 样式表缓存的类型 */ + list_t groups; /**< 样式组列表 */ + dict_t *cache; /**< 样式表缓存,以选择器的 hash 值索引 */ + dict_t *names; /**< 样式属性名称表,以值的名称索引 */ + dict_t *value_keys; /**< 样式属性值表,以值的名称索引 */ + dict_t *value_names; /**< 样式属性值名称表,以值索引 */ + dict_type_t names_dict; /**< 样式属性名称表的类型 */ + dict_type_t value_keys_dict; /**< 样式属性值表的类型 */ + dict_type_t value_names_dict; /**< 样式属性值名称表的类型 */ + dict_type_t style_link_dict; /**< 样式链接表的类型 */ + dict_type_t style_group_dict; /**< 样式组的类型 */ + dict_type_t cache_dict; /**< 样式表缓存的类型 */ strpool_t *strpool; /**< 字符串池 */ int count; /**< 当前记录的属性数量 */ } library; @@ -241,14 +241,17 @@ static KeyNameGroupRec style_value_map[] = { static int LCUI_DirectAddStyleName(int key, const char *name) { - return Dict_AddCopy(library.names, &key, name); + if(!library.names->type->val_dup){ + return -2; + } + return dict_add(library.names, &key, name); } int LCUI_SetStyleName(int key, const char *name) { char *newname; - DictEntry *entry; - entry = Dict_Find(library.names, &key); + dict_entry_t *entry; + entry = dict_find(library.names, &key); if (entry) { newname = strdup2(name); free(entry->v.val); @@ -271,7 +274,7 @@ int LCUI_AddCSSPropertyName(const char *name) const char *LCUI_GetStyleName(int key) { - return Dict_FetchValue(library.names, &key); + return dict_fetch_value(library.names, &key); } static KeyNameGroup CreateKeyNameGroup(int key, const char *name) @@ -298,11 +301,11 @@ static void KeyNameGroupDestructor(void *privdata, void *data) int LCUI_AddStyleValue(int key, const char *name) { KeyNameGroup group = CreateKeyNameGroup(key, name); - if (Dict_Add(library.value_keys, group->name, group)) { + if (dict_add(library.value_keys, group->name, group)) { DestroyKeyNameGroup(group); return -1; } - if (Dict_Add(library.value_names, &group->key, group)) { + if (dict_add(library.value_names, &group->key, group)) { DestroyKeyNameGroup(group); return -2; } @@ -312,7 +315,7 @@ int LCUI_AddStyleValue(int key, const char *name) int LCUI_GetStyleValue(const char *str) { KeyNameGroup group; - group = Dict_FetchValue(library.value_keys, str); + group = dict_fetch_value(library.value_keys, str); if (group) { return group->key; } @@ -322,7 +325,7 @@ int LCUI_GetStyleValue(const char *str) const char *LCUI_GetStyleValueName(int val) { KeyNameGroup group; - group = Dict_FetchValue(library.value_names, &val); + group = dict_fetch_value(library.value_names, &val); if (group) { return group->name; } @@ -392,12 +395,12 @@ static void SelectorNode_Copy(LCUI_SelectorNode dst, LCUI_SelectorNode src) dst->fullname = src->fullname ? strdup2(src->fullname) : NULL; if (src->classes) { for (i = 0; src->classes[i]; ++i) { - sortedstrlist_add(&dst->classes, src->classes[i]); + strlist_sorted_add(&dst->classes, src->classes[i]); } } if (src->status) { for (i = 0; src->status[i]; ++i) { - sortedstrlist_add(&dst->status, src->status[i]); + strlist_sorted_add(&dst->status, src->status[i]); } } } @@ -449,7 +452,7 @@ LCUI_StyleList StyleList(void) LCUI_StyleList list; list = malloc(sizeof(LCUI_StyleListRec)); - LinkedList_Init(list); + list_create(list); return list; } @@ -499,7 +502,7 @@ static void DeleteStyleListNode(LCUI_StyleListNode node) void StyleList_Delete(LCUI_StyleList list) { - LinkedList_ClearData(list, (FuncPtr)DeleteStyleListNode); + list_destroy_without_node(list, (FuncPtr)DeleteStyleListNode); free(list); } @@ -534,10 +537,10 @@ void StyleSheet_Delete(LCUI_StyleSheet ss) LCUI_StyleListNode StyleList_GetNode(LCUI_StyleList list, int key) { - LinkedListNode *node; + list_node_t *node; LCUI_StyleListNode snode; - for (LinkedList_Each(node, list)) { + for (list_each(node, list)) { snode = node->data; if (snode->key == key) { return snode; @@ -548,13 +551,13 @@ LCUI_StyleListNode StyleList_GetNode(LCUI_StyleList list, int key) int StyleList_RemoveNode(LCUI_StyleList list, int key) { - LinkedListNode *node; + list_node_t *node; LCUI_StyleListNode snode; - for (LinkedList_Each(node, list)) { + for (list_each(node, list)) { snode = node->data; if (snode->key == key) { - LinkedList_Unlink(list, node); + list_unlink(list, node); DestroyStyle(&snode->style); free(snode); return 0; @@ -572,7 +575,7 @@ LCUI_StyleListNode StyleList_AddNode(LCUI_StyleList list, int key) node->style.is_valid = FALSE; node->style.type = LCUI_STYPE_NONE; node->node.data = node; - LinkedList_AppendNode(list, &node->node); + list_append_node(list, &node->node); return node; } @@ -622,11 +625,11 @@ int StyleSheet_MergeList(LCUI_StyleSheet ss, LCUI_StyleList list) { LCUI_Style s; LCUI_StyleListNode snode; - LinkedListNode *node; + list_node_t *node; size_t size; int i = 0, count = 0; - for (LinkedList_Each(node, list)) { + for (list_each(node, list)) { snode = node->data; if (snode->key > ss->length) { size = sizeof(LCUI_StyleRec) * (snode->key + 1); @@ -700,7 +703,7 @@ static void NamesFinder_Destroy(NamesFinder sfinder) } /* 生成选择器全名列表 */ -static int NamesFinder_Find(NamesFinder sfinder, LinkedList *list) +static int NamesFinder_Find(NamesFinder sfinder, list_t *list) { size_t len, old_len; int i, old_level, count = 0; @@ -715,7 +718,7 @@ static int NamesFinder_Find(NamesFinder sfinder, LinkedList *list) return 0; } strcpy(fullname, sfinder->node->type); - LinkedList_Append(list, strdup2(fullname)); + list_append(list, strdup2(fullname)); break; case LEVEL_ID: /* 按ID选择器生成选择器全名 */ @@ -725,7 +728,7 @@ static int NamesFinder_Find(NamesFinder sfinder, LinkedList *list) fullname[len++] = '#'; fullname[len] = 0; strcpy(fullname + len, sfinder->node->id); - LinkedList_Append(list, strdup2(fullname)); + list_append(list, strdup2(fullname)); break; case LEVEL_CLASS: if (!sfinder->node->classes) { @@ -743,7 +746,7 @@ static int NamesFinder_Find(NamesFinder sfinder, LinkedList *list) sfinder->level += 1; sfinder->class_i = i; strcpy(fullname + len, sfinder->node->classes[i]); - LinkedList_Append(list, strdup2(fullname)); + list_append(list, strdup2(fullname)); /* 将当前选择器名与其它层级的选择器名组合 */ while (sfinder->level < LEVEL_TOTAL_NUM) { count += NamesFinder_Find(sfinder, list); @@ -771,7 +774,7 @@ static int NamesFinder_Find(NamesFinder sfinder, LinkedList *list) continue; } strcpy(fullname + len, sfinder->node->classes[i]); - LinkedList_Append(list, strdup2(fullname)); + list_append(list, strdup2(fullname)); sfinder->class_i = i; count += NamesFinder_Find(sfinder, list); sfinder->class_i = 0; @@ -807,7 +810,7 @@ static int NamesFinder_Find(NamesFinder sfinder, LinkedList *list) for (i = 0; sfinder->node->status[i]; ++i) { sfinder->status_i = i; strcpy(fullname + len, sfinder->node->status[i]); - LinkedList_Append(list, strdup2(fullname)); + list_append(list, strdup2(fullname)); /** * 递归调用,以一层层拼接出像下面这样的选择器: * textview#main-btn-text:active:focus:hover @@ -829,7 +832,7 @@ static int NamesFinder_Find(NamesFinder sfinder, LinkedList *list) } fullname[len] = ':'; strcpy(fullname + len + 1, sfinder->node->status[i]); - LinkedList_Append(list, strdup2(fullname)); + list_append(list, strdup2(fullname)); sfinder->status_i = i; count += NamesFinder_Find(sfinder, list); sfinder->status_i = 0; @@ -869,12 +872,12 @@ static int SelectorNode_Save(LCUI_SelectorNode node, const char *name, int len, node->type = str; return TYPE_RANK; case ':': - if (sortedstrlist_add(&node->status, name) == 0) { + if (strlist_sorted_add(&node->status, name) == 0) { return PCLASS_RANK; } break; case '.': - if (sortedstrlist_add(&node->classes, name) == 0) { + if (strlist_sorted_add(&node->classes, name) == 0) { return CLASS_RANK; } break; @@ -893,7 +896,7 @@ static int SelectorNode_Save(LCUI_SelectorNode node, const char *name, int len, return 0; } -int SelectorNode_GetNames(LCUI_SelectorNode sn, LinkedList *names) +int SelectorNode_GetNames(LCUI_SelectorNode sn, list_t *names) { int count; NamesFinderRec sfinder; @@ -985,7 +988,7 @@ int Selector_AppendNode(LCUI_Selector selector, LCUI_SelectorNode node) const unsigned char *p; if (selector->length >= MAX_SELECTOR_DEPTH) { - Logger_Warning("[css] warning: the number of nodes in the " + logger_warning("[css] warning: the number of nodes in the " "selector has exceeded the %d limit\n", MAX_SELECTOR_DEPTH); return -1; @@ -1020,7 +1023,7 @@ LCUI_Selector Selector(const char *selector) if (!node && is_saving) { node = NEW(LCUI_SelectorNodeRec, 1); if (si >= MAX_SELECTOR_DEPTH) { - Logger_Warning( + logger_warning( "%s: selector node list is too long.\n", selector); return NULL; @@ -1045,7 +1048,7 @@ LCUI_Selector Selector(const char *selector) ni = 0; continue; } - Logger_Error("%s: invalid selector node at %ld.\n", + logger_error("%s: invalid selector node at %ld.\n", selector, p - selector - ni); SelectorNode_Delete(node); node = NULL; @@ -1070,7 +1073,7 @@ LCUI_Selector Selector(const char *selector) si++; continue; } - Logger_Error("%s: invalid selector node at %ld.\n", + logger_error("%s: invalid selector node at %ld.\n", selector, p - selector - ni); SelectorNode_Delete(node); node = NULL; @@ -1090,7 +1093,7 @@ LCUI_Selector Selector(const char *selector) name[ni] = 0; continue; } - Logger_Warning("%s: unknown char 0x%02x at %ld.\n", + logger_warning("%s: unknown char 0x%02x at %ld.\n", selector, *p, p - selector); return NULL; } @@ -1098,7 +1101,7 @@ LCUI_Selector Selector(const char *selector) if (!node) { node = NEW(LCUI_SelectorNodeRec, 1); if (si >= MAX_SELECTOR_DEPTH) { - Logger_Warning( + logger_warning( "%s: selector node list is too long.\n", selector); return NULL; @@ -1156,19 +1159,19 @@ static void DeleteStyleNode(StyleNode node) static StyleLink CreateStyleLink(void) { StyleLink link = NEW(StyleLinkRec, 1); - static DictType t; + static dict_type_t t; - Dict_InitStringCopyKeyType(&t); + dict_init_string_copy_key_type(&t); link->group = NULL; - LinkedList_Init(&link->styles); - link->parents = Dict_Create(&t, NULL); + list_create(&link->styles); + link->parents = dict_create(&t, NULL); return link; } static void DeleteStyleLink(StyleLink link) { - Dict_Release(link->parents); - LinkedList_ClearData(&link->styles, (FuncPtr)DeleteStyleNode); + dict_destroy(link->parents); + list_destroy_without_node(&link->styles, (FuncPtr)DeleteStyleNode); free(link->selector); link->selector = NULL; link->parents = NULL; @@ -1182,16 +1185,16 @@ static StyleLinkGroup CreateStyleLinkGroup(LCUI_SelectorNode snode) group->snode = NEW(LCUI_SelectorNodeRec, 1); SelectorNode_Copy(group->snode, snode); group->name = group->snode->fullname; - group->links = Dict_Create(&library.style_link_dict, NULL); + group->links = dict_create(&library.style_link_dict, NULL); return group; } static void DeleteStyleLinkGroup(StyleLinkGroup group) { - DictType *dtype; - dtype = group->links->privdata; + dict_type_t *dtype; + dtype = group->links->priv_data; SelectorNode_Delete(group->snode); - Dict_Release(group->links); + dict_destroy(group->links); free(dtype); free(group); } @@ -1203,20 +1206,20 @@ static void StyleLinkGroupDestructor(void *privdata, void *data) static void InitStyleGroupDict(void) { - DictType *dt = &library.style_group_dict; + dict_type_t *dt = &library.style_group_dict; - Dict_InitStringCopyKeyType(dt); - dt->valDestructor = StyleLinkGroupDestructor; + dict_init_string_copy_key_type(dt); + dt->val_destructor = StyleLinkGroupDestructor; } -static Dict *CreateStyleGroup(void) +static dict_t *CreateStyleGroup(void) { - return Dict_Create(&library.style_group_dict, NULL); + return dict_create(&library.style_group_dict, NULL); } -static void DeleteStyleGroup(Dict *dict) +static void DeleteStyleGroup(dict_t *dict) { - Dict_Release(dict); + dict_destroy(dict); } /** 根据选择器,选中匹配的样式表 */ @@ -1228,35 +1231,35 @@ static LCUI_StyleList LCUI_SelectStyleList(LCUI_Selector selector, StyleNode snode; StyleLinkGroup slg; LCUI_SelectorNode sn; - Dict *group, *parents; + dict_t *group, *parents; char buf[MAX_SELECTOR_LEN]; char fullname[MAX_SELECTOR_LEN]; link = NULL; parents = NULL; for (i = 0, right = selector->length - 1; right >= 0; --right, ++i) { - group = LinkedList_Get(&library.groups, i); + group = list_get(&library.groups, i); if (!group) { group = CreateStyleGroup(); - LinkedList_Append(&library.groups, group); + list_append(&library.groups, group); } sn = selector->nodes[right]; - slg = Dict_FetchValue(group, sn->fullname); + slg = dict_fetch_value(group, sn->fullname); if (!slg) { slg = CreateStyleLinkGroup(sn); - Dict_Add(group, sn->fullname, slg); + dict_add(group, sn->fullname, slg); } if (i == 0) { strcpy(fullname, "*"); } else { strcpy(fullname, buf); } - link = Dict_FetchValue(slg->links, fullname); + link = dict_fetch_value(slg->links, fullname); if (!link) { link = CreateStyleLink(); link->group = slg; link->selector = strdup2(fullname); - Dict_Add(slg->links, fullname, link); + dict_add(slg->links, fullname, link); } if (i == 0) { strcpy(buf, sn->fullname); @@ -1267,8 +1270,8 @@ static LCUI_StyleList LCUI_SelectStyleList(LCUI_Selector selector, } /* 如果有上一级的父链接记录,则将当前链接添加进去 */ if (parents) { - if (!Dict_FetchValue(parents, sn->fullname)) { - Dict_Add(parents, sn->fullname, link); + if (!dict_fetch_value(parents, sn->fullname)) { + dict_add(parents, sn->fullname, link); } } parents = link->parents; @@ -1288,7 +1291,7 @@ static LCUI_StyleList LCUI_SelectStyleList(LCUI_Selector selector, snode->rank = selector->rank; snode->selector = strdup2(fullname); snode->batch_num = selector->batch_num; - LinkedList_AppendNode(&link->styles, &snode->node); + list_append_node(&link->styles, &snode->node); return snode->list; } @@ -1296,7 +1299,7 @@ int LCUI_PutStyleSheet(LCUI_Selector selector, LCUI_StyleSheet in_ss, const char *space) { LCUI_StyleList list; - Dict_Empty(library.cache); + dict_empty(library.cache, NULL); list = LCUI_SelectStyleList(selector, space); if (list) { StyleList_Merge(list, in_ss); @@ -1304,21 +1307,21 @@ int LCUI_PutStyleSheet(LCUI_Selector selector, LCUI_StyleSheet in_ss, return 0; } -static size_t StyleLink_GetStyleSheets(StyleLink link, LinkedList *outlist) +static size_t StyleLink_GetStyleSheets(StyleLink link, list_t *outlist) { size_t i; LCUI_BOOL found; StyleNode snode, out_snode; - LinkedListNode *node, *out_node; + list_node_t *node, *out_node; if (!outlist) { return link->styles.length; } - for (LinkedList_Each(node, &link->styles)) { + for (list_each(node, &link->styles)) { i = 0; found = FALSE; snode = node->data; - for (LinkedList_Each(out_node, outlist)) { + for (list_each(out_node, outlist)) { out_snode = out_node->data; if (snode->rank > out_snode->rank) { found = TRUE; @@ -1335,80 +1338,80 @@ static size_t StyleLink_GetStyleSheets(StyleLink link, LinkedList *outlist) i += 1; } if (found) { - LinkedList_Insert(outlist, i, snode); + list_insert(outlist, i, snode); } else { - LinkedList_Append(outlist, snode); + list_append(outlist, snode); } } return link->styles.length; } static size_t LCUI_FindStyleSheetFromLink(StyleLink link, LCUI_Selector s, - int i, LinkedList *list) + int i, list_t *list) { size_t count = 0; StyleLink parent; - LinkedList names; - LinkedListNode *node; + list_t names; + list_node_t *node; LCUI_SelectorNode sn; - LinkedList_Init(&names); + list_create(&names); count += StyleLink_GetStyleSheets(link, list); while (--i >= 0) { sn = s->nodes[i]; SelectorNode_GetNames(sn, &names); - for (LinkedList_Each(node, &names)) { - parent = Dict_FetchValue(link->parents, node->data); + for (list_each(node, &names)) { + parent = dict_fetch_value(link->parents, node->data); if (!parent) { continue; } count += LCUI_FindStyleSheetFromLink(parent, s, i, list); } - LinkedList_Clear(&names, free); + list_destroy(&names, free); } return count; } int LCUI_FindStyleSheetFromGroup(int group, const char *name, LCUI_Selector s, - LinkedList *list) + list_t *list) { int i; size_t count; - Dict *groups; + dict_t *groups; StyleLinkGroup slg; - LinkedListNode *node; - LinkedList names; + list_node_t *node; + list_t names; - groups = LinkedList_Get(&library.groups, group); + groups = list_get(&library.groups, group); if (!groups || s->length < 1) { return 0; } count = 0; i = s->length - 1; - LinkedList_Init(&names); + list_create(&names); if (name) { - LinkedList_Append(&names, strdup2(name)); + list_append(&names, strdup2(name)); } else { SelectorNode_GetNames(s->nodes[i], &names); - LinkedList_Append(&names, strdup2("*")); + list_append(&names, strdup2("*")); } - for (LinkedList_Each(node, &names)) { - DictEntry *entry; - DictIterator *iter; + for (list_each(node, &names)) { + dict_entry_t *entry; + dict_iterator_t *iter; char *name = node->data; - slg = Dict_FetchValue(groups, name); + slg = dict_fetch_value(groups, name); if (!slg) { continue; } - iter = Dict_GetIterator(slg->links); - while ((entry = Dict_Next(iter))) { - StyleLink link = DictEntry_GetVal(entry); + iter = dict_get_iterator(slg->links); + while ((entry = dict_next(iter))) { + StyleLink link = dict_get_val(entry); count += LCUI_FindStyleSheetFromLink(link, s, i, list); } - Dict_ReleaseIterator(iter); + dict_destroy_iterator(iter); } - LinkedList_Clear(&names, free); + list_destroy(&names, free); return (int)count; } @@ -1418,69 +1421,69 @@ static void PrintStyleName(int key) name = LCUI_GetStyleName(key); if (name) { - Logger_Debug("\t%s", name); + logger_debug("\t%s", name); } else { - Logger_Debug("\t", key); + logger_debug("\t", key); } - Logger_Debug("%s: ", key > STYLE_KEY_TOTAL ? " (+)" : ""); + logger_debug("%s: ", key > STYLE_KEY_TOTAL ? " (+)" : ""); } static void PrintStyleValue(LCUI_Style s) { switch (s->type) { case LCUI_STYPE_AUTO: - Logger_Debug("auto"); + logger_debug("auto"); break; case LCUI_STYPE_BOOL: - Logger_Debug("%s", s->val_bool ? "true" : "false"); + logger_debug("%s", s->val_bool ? "true" : "false"); break; case LCUI_STYPE_COLOR: { LCUI_Color *clr = &s->val_color; if (clr->alpha < 255) { - Logger_Debug("rgba(%d,%d,%d,%g)", clr->r, clr->g, clr->b, + logger_debug("rgba(%d,%d,%d,%g)", clr->r, clr->g, clr->b, clr->a / 255.0); } else { - Logger_Debug("#%02x%02x%02x", clr->r, clr->g, clr->b); + logger_debug("#%02x%02x%02x", clr->r, clr->g, clr->b); } break; } case LCUI_STYPE_PX: - Logger_Debug("%gpx", s->val_px); + logger_debug("%gpx", s->val_px); break; case LCUI_STYPE_DIP: - Logger_Debug("%gdip", s->val_dip); + logger_debug("%gdip", s->val_dip); break; case LCUI_STYPE_SP: - Logger_Debug("%gsp", s->val_sp); + logger_debug("%gsp", s->val_sp); break; case LCUI_STYPE_STRING: - Logger_Debug("%s", s->val_string); + logger_debug("%s", s->val_string); break; case LCUI_STYPE_WSTRING: - Logger_Debug("%S", s->val_wstring); + logger_debug("%S", s->val_wstring); break; case LCUI_STYPE_SCALE: - Logger_Debug("%g%%", s->val_scale * 100); + logger_debug("%g%%", s->val_scale * 100); break; case LCUI_STYPE_STYLE: - Logger_Debug("%s", LCUI_GetStyleValueName(s->val_style)); + logger_debug("%s", LCUI_GetStyleValueName(s->val_style)); break; case LCUI_STYPE_INT: - Logger_Debug("%d", s->val_int); + logger_debug("%d", s->val_int); break; default: - Logger_Debug("%g", s->value); + logger_debug("%g", s->value); break; } - Logger_Debug(";\n"); + logger_debug(";\n"); } void LCUI_PrintStyleList(LCUI_StyleList list) { - LinkedListNode *node; + list_node_t *node; LCUI_StyleListNode snode; - for (LinkedList_Each(node, list)) { + for (list_each(node, list)) { snode = node->data; if (snode->style.is_valid) { PrintStyleName(snode->key); @@ -1513,15 +1516,15 @@ void LCUI_PrintSelector(LCUI_Selector selector) strcat(path, (*sn)->fullname); strcat(path, " "); } - Logger_Debug("path: %s (rank = %d, batch_num = %d)\n", path, + logger_debug("path: %s (rank = %d, batch_num = %d)\n", path, selector->rank, selector->batch_num); } static void LCUI_PrintStyleLink(StyleLink link, const char *selector) { - DictEntry *entry; - DictIterator *iter; - LinkedListNode *node; + dict_entry_t *entry; + dict_iterator_t *iter; + list_node_t *node; char fullname[MAX_SELECTOR_LEN]; if (selector) { @@ -1529,68 +1532,68 @@ static void LCUI_PrintStyleLink(StyleLink link, const char *selector) } else { strcpy(fullname, link->group->name); } - for (LinkedList_Each(node, &link->styles)) { + for (list_each(node, &link->styles)) { StyleNode snode = node->data; - Logger_Debug("\n[%s]", snode->space ? snode->space : ""); - Logger_Debug("[rank: %d]\n%s {\n", snode->rank, fullname); + logger_debug("\n[%s]", snode->space ? snode->space : ""); + logger_debug("[rank: %d]\n%s {\n", snode->rank, fullname); LCUI_PrintStyleList(snode->list); - Logger_Debug("}\n"); + logger_debug("}\n"); } - iter = Dict_GetIterator(link->parents); - while ((entry = Dict_Next(iter))) { - StyleLink parent = DictEntry_GetVal(entry); + iter = dict_get_iterator(link->parents); + while ((entry = dict_next(iter))) { + StyleLink parent = dict_get_val(entry); LCUI_PrintStyleLink(parent, fullname); } - Dict_ReleaseIterator(iter); + dict_destroy_iterator(iter); } void LCUI_PrintCSSLibrary(void) { - Dict *group; + dict_t *group; StyleLink link; StyleLinkGroup slg; - DictIterator *iter; - DictEntry *entry; + dict_iterator_t *iter; + dict_entry_t *entry; link = NULL; - Logger_Debug("style library begin\n"); - group = LinkedList_Get(&library.groups, 0); - iter = Dict_GetIterator(group); - while ((entry = Dict_Next(iter))) { - DictEntry *entry_slg; - DictIterator *iter_slg; + logger_debug("style library begin\n"); + group = list_get(&library.groups, 0); + iter = dict_get_iterator(group); + while ((entry = dict_next(iter))) { + dict_entry_t *entry_slg; + dict_iterator_t *iter_slg; - slg = DictEntry_GetVal(entry); - iter_slg = Dict_GetIterator(slg->links); - while ((entry_slg = Dict_Next(iter_slg))) { - link = DictEntry_GetVal(entry_slg); + slg = dict_get_val(entry); + iter_slg = dict_get_iterator(slg->links); + while ((entry_slg = dict_next(iter_slg))) { + link = dict_get_val(entry_slg); LCUI_PrintStyleLink(link, NULL); } - Dict_ReleaseIterator(iter_slg); + dict_destroy_iterator(iter_slg); } - Dict_ReleaseIterator(iter); - Logger_Debug("style library end\n"); + dict_destroy_iterator(iter); + logger_debug("style library end\n"); } LCUI_CachedStyleSheet LCUI_GetCachedStyleSheet(LCUI_Selector s) { - LinkedList list; - LinkedListNode *node; + list_t list; + list_node_t *node; LCUI_StyleSheet ss; - LinkedList_Init(&list); - ss = Dict_FetchValue(library.cache, &s->hash); + list_create(&list); + ss = dict_fetch_value(library.cache, &s->hash); if (ss) { return ss; } ss = StyleSheet(); LCUI_FindStyleSheet(s, &list); - for (LinkedList_Each(node, &list)) { + for (list_each(node, &list)) { StyleNode sn = node->data; StyleSheet_MergeList(ss, sn->list); } - LinkedList_Clear(&list, NULL); - Dict_Add(library.cache, &s->hash, ss); + list_destroy(&list, NULL); + dict_add(library.cache, &s->hash, ss); return ss; } @@ -1605,27 +1608,27 @@ void LCUI_GetStyleSheet(LCUI_Selector s, LCUI_StyleSheet out_ss) void LCUI_PrintStyleSheetsBySelector(LCUI_Selector s) { - LinkedList list; - LinkedListNode *node; + list_t list; + list_node_t *node; LCUI_StyleSheet ss; - LinkedList_Init(&list); + list_create(&list); ss = StyleSheet(); LCUI_FindStyleSheet(s, &list); - Logger_Debug("selector(%u) stylesheets begin\n", s->hash); - for (LinkedList_Each(node, &list)) { + logger_debug("selector(%u) stylesheets begin\n", s->hash); + for (list_each(node, &list)) { StyleNode sn = node->data; - Logger_Debug("\n[%s]", sn->space ? sn->space : ""); - Logger_Debug("[rank: %d]\n%s {\n", sn->rank, sn->selector); + logger_debug("\n[%s]", sn->space ? sn->space : ""); + logger_debug("[rank: %d]\n%s {\n", sn->rank, sn->selector); LCUI_PrintStyleList(sn->list); - Logger_Debug("}\n"); + logger_debug("}\n"); StyleSheet_MergeList(ss, sn->list); } - LinkedList_Clear(&list, NULL); - Logger_Debug("[selector(%u) final stylesheet] {\n", s->hash); + list_destroy(&list, NULL); + logger_debug("[selector(%u) final stylesheet] {\n", s->hash); LCUI_PrintStyleSheet(ss); - Logger_Debug("}\n"); + logger_debug("}\n"); StyleSheet_Delete(ss); - Logger_Debug("selector(%u) stylesheets end\n", s->hash); + logger_debug("selector(%u) stylesheets end\n", s->hash); } static void StyleSheetCacheDestructor(void *privdata, void *val) @@ -1645,7 +1648,7 @@ static void StyleNameDestructor(void *privdata, void *val) static unsigned int IntKeyDict_HashFunction(const void *key) { - return Dict_IdentityHashFunction(*(unsigned int *)key); + return (*(unsigned int *)key); } static int IntKeyDict_KeyCompare(void *privdata, const void *key1, @@ -1668,21 +1671,21 @@ static void *IntKeyDict_KeyDup(void *privdata, const void *key) static void InitStylesheetCache(void) { - DictType *dt = &library.cache_dict; + dict_type_t *dt = &library.cache_dict; - dt->valDup = NULL; - dt->keyDup = IntKeyDict_KeyDup; - dt->keyCompare = IntKeyDict_KeyCompare; - dt->hashFunction = IntKeyDict_HashFunction; - dt->keyDestructor = IntKeyDict_KeyDestructor; - dt->valDestructor = StyleSheetCacheDestructor; - dt->keyDestructor = IntKeyDict_KeyDestructor; - library.cache = Dict_Create(dt, NULL); + dt->val_dup = NULL; + dt->key_dup = IntKeyDict_KeyDup; + dt->key_compare = IntKeyDict_KeyCompare; + dt->hash_function = IntKeyDict_HashFunction; + dt->key_destructor = IntKeyDict_KeyDestructor; + dt->val_destructor = StyleSheetCacheDestructor; + dt->key_destructor = IntKeyDict_KeyDestructor; + library.cache = dict_create(dt, NULL); } static void DestroyStylesheetCache(void) { - Dict_Release(library.cache); + dict_destroy(library.cache); library.cache = NULL; } @@ -1693,49 +1696,49 @@ static void StyleLinkDestructor(void *privdata, void *data) static void InitStyleLinkDict(void) { - Dict_InitStringCopyKeyType(&library.style_link_dict); - library.style_link_dict.valDestructor = StyleLinkDestructor; + dict_init_string_copy_key_type(&library.style_link_dict); + library.style_link_dict.val_destructor = StyleLinkDestructor; } static void InitStyleNameLibrary(void) { - DictType *dt = &library.names_dict; + dict_type_t *dt = &library.names_dict; - dt->valDup = DupStyleName; - dt->keyDup = IntKeyDict_KeyDup; - dt->keyCompare = IntKeyDict_KeyCompare; - dt->valDestructor = StyleNameDestructor; - dt->hashFunction = IntKeyDict_HashFunction; - dt->keyDestructor = IntKeyDict_KeyDestructor; - library.names = Dict_Create(dt, NULL); + dt->val_dup = DupStyleName; + dt->key_dup = IntKeyDict_KeyDup; + dt->key_compare = IntKeyDict_KeyCompare; + dt->val_destructor = StyleNameDestructor; + dt->hash_function = IntKeyDict_HashFunction; + dt->key_destructor = IntKeyDict_KeyDestructor; + library.names = dict_create(dt, NULL); } static void DestroyStyleNameLibrary(void) { - Dict_Release(library.names); + dict_destroy(library.names); library.names = NULL; } static void InitStyleValueLibrary(void) { - DictType *keys_dt = &library.value_keys_dict; - DictType *names_dt = &library.value_names_dict; + dict_type_t *keys_dt = &library.value_keys_dict; + dict_type_t *names_dt = &library.value_names_dict; - memset(names_dt, 0, sizeof(DictType)); - names_dt->keyCompare = IntKeyDict_KeyCompare; - names_dt->hashFunction = IntKeyDict_HashFunction; - Dict_InitStringKeyType(keys_dt); - keys_dt->valDestructor = KeyNameGroupDestructor; + memset(names_dt, 0, sizeof(dict_type_t)); + names_dt->key_compare = IntKeyDict_KeyCompare; + names_dt->hash_function = IntKeyDict_HashFunction; + dict_init_string_key_type(keys_dt); + keys_dt->val_destructor = KeyNameGroupDestructor; /* value_keys 表用于存放 key 和 name 数据 */ - library.value_keys = Dict_Create(keys_dt, NULL); + library.value_keys = dict_create(keys_dt, NULL); /* value_names 表仅引用 value_keys 里的数据 */ - library.value_names = Dict_Create(names_dt, NULL); + library.value_names = dict_create(names_dt, NULL); } static void DestroyStyleValueLibrary(void) { - Dict_Release(library.value_names); - Dict_Release(library.value_keys); + dict_destroy(library.value_names); + dict_destroy(library.value_keys); library.value_keys = NULL; library.value_names = NULL; } @@ -1750,7 +1753,7 @@ void LCUI_InitCSSLibrary(void) InitStylesheetCache(); InitStyleNameLibrary(); InitStyleValueLibrary(); - LinkedList_Init(&library.groups); + list_create(&library.groups); skn_end = style_name_map + LEN(style_name_map); for (skn = style_name_map; skn < skn_end; ++skn) { LCUI_DirectAddStyleName(skn->key, skn->name); @@ -1769,6 +1772,6 @@ void LCUI_FreeCSSLibrary(void) DestroyStylesheetCache(); DestroyStyleNameLibrary(); DestroyStyleValueLibrary(); - LinkedList_Clear(&library.groups, (FuncPtr)DeleteStyleGroup); + list_destroy(&library.groups, (FuncPtr)DeleteStyleGroup); strpool_destroy(library.strpool); } diff --git a/lib/css/src/css_parser.c b/lib/css/src/css_parser.c index f6d2f7f8..b874ddf6 100644 --- a/lib/css/src/css_parser.c +++ b/lib/css/src/css_parser.c @@ -46,8 +46,8 @@ static struct CSSParserModule { int count; - DictType dicttype; /**< 解析器表的字典类型数据 */ - Dict *parsers; /**< 解析器表,以名称进行索引 */ + dict_type_t dicttype; /**< 解析器表的字典类型数据 */ + dict_t *parsers; /**< 解析器表,以名称进行索引 */ } self; void CSSStyleParser_SetCSSProperty(LCUI_CSSParserStyleContext ctx, int key, @@ -901,12 +901,12 @@ int CSSParser_BeginParseComment(LCUI_CSSParserContext ctx) static void CSSParser_EndParseSheet(LCUI_CSSParserContext ctx) { - LinkedListNode *node; + list_node_t *node; /* 将记录的样式表添加至匹配到的选择器中 */ - for (LinkedList_Each(node, &ctx->style.selectors)) { + for (list_each(node, &ctx->style.selectors)) { LCUI_PutStyleSheet(node->data, ctx->style.sheet, ctx->space); } - LinkedList_Clear(&ctx->style.selectors, (FuncPtr)Selector_Delete); + list_destroy(&ctx->style.selectors, (FuncPtr)Selector_Delete); StyleSheet_Delete(ctx->style.sheet); } @@ -927,7 +927,7 @@ static int CSSParser_ParseSelector(LCUI_CSSParserContext ctx) if (!s) { return -1; } - LinkedList_Append(&ctx->style.selectors, s); + list_append(&ctx->style.selectors, s); break; default: CSSParser_GetChar(ctx); @@ -1155,7 +1155,7 @@ LCUI_CSSParserContext CSSParser_Begin(size_t buffer_size, const char *space) ctx->parsers[CSS_TARGET_VALUE].parse = CSSParser_ParseStyleValue; ctx->parsers[CSS_TARGET_COMMENT].parse = CSSParser_ParseComment; ctx->comment.prev_target = CSS_TARGET_NONE; - LinkedList_Init(&ctx->style.selectors); + list_create(&ctx->style.selectors); memset(&ctx->rule, 0, sizeof(ctx->rule)); CSSParser_InitFontFaceRuleParser(ctx); return ctx; @@ -1163,7 +1163,7 @@ LCUI_CSSParserContext CSSParser_Begin(size_t buffer_size, const char *space) void CSSParser_End(LCUI_CSSParserContext ctx) { - LinkedList_Clear(&ctx->style.selectors, (FuncPtr)Selector_Delete); + list_destroy(&ctx->style.selectors, (FuncPtr)Selector_Delete); CSSParser_FreeFontFaceRuleParser(ctx); if (ctx->space) { free(ctx->space); @@ -1177,7 +1177,7 @@ void CSSParser_End(LCUI_CSSParserContext ctx) LCUI_CSSPropertyParser LCUI_GetCSSPropertyParser(const char *name) { - return Dict_FetchValue(self.parsers, name); + return dict_fetch_value(self.parsers, name); } int LCUI_AddCSSPropertyParser(LCUI_CSSPropertyParser sp) @@ -1186,7 +1186,7 @@ int LCUI_AddCSSPropertyParser(LCUI_CSSPropertyParser sp) if (!sp->name || strlen(sp->name) < 1) { return -1; } - if (Dict_FetchValue(self.parsers, sp->name)) { + if (dict_fetch_value(self.parsers, sp->name)) { return -2; } self.count += 1; @@ -1194,7 +1194,7 @@ int LCUI_AddCSSPropertyParser(LCUI_CSSPropertyParser sp) new_sp->key = sp->key; new_sp->parse = sp->parse; new_sp->name = strdup2(sp->name); - Dict_Add(self.parsers, new_sp->name, new_sp); + dict_add(self.parsers, new_sp->name, new_sp); return 0; } @@ -1210,9 +1210,9 @@ void LCUI_InitCSSParser(void) LCUI_CSSPropertyParser new_sp, sp, sp_end; self.count = 0; - Dict_InitStringKeyType(&self.dicttype); - self.dicttype.valDestructor = DestroyStyleParser; - self.parsers = Dict_Create(&self.dicttype, NULL); + dict_init_string_key_type(&self.dicttype); + self.dicttype.val_destructor = DestroyStyleParser; + self.parsers = dict_create(&self.dicttype, NULL); sp_end = style_parser_map + LEN(style_parser_map); for (sp = style_parser_map; sp < sp_end; ++sp) { new_sp = malloc(sizeof(LCUI_CSSPropertyParserRec)); @@ -1228,11 +1228,11 @@ void LCUI_InitCSSParser(void) } else { new_sp->name = strdup2(sp->name); } - Dict_Add(self.parsers, new_sp->name, new_sp); + dict_add(self.parsers, new_sp->name, new_sp); } } void LCUI_FreeCSSParser(void) { - Dict_Release(self.parsers); + dict_destroy(self.parsers); } diff --git a/lib/css/src/css_rule_font_face.c b/lib/css/src/css_rule_font_face.c index 1dd61435..9286b318 100644 --- a/lib/css/src/css_rule_font_face.c +++ b/lib/css/src/css_rule_font_face.c @@ -28,7 +28,6 @@ * POSSIBILITY OF SUCH DAMAGE. */ - #include #include #include @@ -36,8 +35,7 @@ #include #include #include -#include -#include +#include #include #include diff --git a/lib/font/src/fontlibrary.c b/lib/font/src/fontlibrary.c index c83bb9a8..451da7a4 100644 --- a/lib/font/src/fontlibrary.c +++ b/lib/font/src/fontlibrary.c @@ -73,9 +73,9 @@ static struct LCUI_FontLibraryModule { int count; /**< 计数器,主要用于为字体信息生成标识号 */ int font_cache_num; /**< 字体信息缓存区的数量 */ LCUI_BOOL active; /**< 标记,指示数据库是否初始化 */ - Dict *font_families; /**< 字族信息库,以字族名称索引字体信息 */ - DictType font_families_type; /**< 字族信息库的字典类型数据 */ - RBTree bitmap_cache; /**< 字体位图缓存区 */ + dict_t *font_families; /**< 字族信息库,以字族名称索引字体信息 */ + dict_type_t font_families_type; /**< 字族信息库的字典类型数据 */ + rbtree_t bitmap_cache; /**< 字体位图缓存区 */ LCUI_FontCache *font_cache; /**< 字体信息缓存区 */ LCUI_Font default_font; /**< 默认字体的信息 */ LCUI_Font incore_font; /**< 内置字体的信息 */ @@ -87,12 +87,12 @@ static struct LCUI_FontLibraryModule { #define FontBitmap_IsValid(fbmp) \ ((fbmp) && (fbmp)->width > 0 && (fbmp)->rows > 0) -#define SelectChar(ch) (RBTree *)RBTree_GetData(&fontlib.bitmap_cache, ch) -#define SelectFont(ch, font_id) (RBTree *)RBTree_GetData(ch, font_id) -#define SelectBitmap(font, size) (LCUI_FontBitmap *)RBTree_GetData(font, size) +#define SelectChar(ch) (rbtree_t *)rbtree_get_data_by_key(&fontlib.bitmap_cache, ch) +#define SelectFont(ch, font_id) (rbtree_t *)rbtree_get_data_by_key(ch, font_id) +#define SelectBitmap(font, size) (LCUI_FontBitmap *)rbtree_get_data_by_key(font, size) #define SelectFontFamliy(family_name) \ (LCUI_FontFamilyNode) \ - Dict_FetchValue(fontlib.font_families, family_name); + dict_fetch_value(fontlib.font_families, family_name); #define SelectFontStyle(FNODE, S) (&(FNODE)->styles[S]) #define SelectFontWeight(SNODE, W) ((SNODE)->weights[W / 100 - 1]) #define ClearFontWeight(SNODE, W) \ @@ -141,7 +141,7 @@ static int SetFontCache(LCUI_Font font) LCUI_FontCache *caches, cache; if (font->id > FONT_CACHE_MAX_SIZE) { - Logger_Error("[font] font cache size is the max size\n"); + logger_error("[font] font cache size is the max size\n"); return -1; } while (font->id >= fontlib.font_cache_num * FONT_CACHE_SIZE) { @@ -251,7 +251,7 @@ static void DestroyFontBitmap(void *arg) static void DestroyTreeNode(void *arg) { - RBTree_Destroy(arg); + rbtree_destroy(arg); free(arg); } @@ -265,7 +265,7 @@ int LCUIFont_Add(LCUI_Font font) node = NEW(LCUI_FontFamilyNodeRec, 1); node->family_name = strdup2(font->family_name); memset(node->styles, 0, sizeof(node->styles)); - Dict_Add(fontlib.font_families, node->family_name, node); + dict_add(fontlib.font_families, node->family_name, node); } snode = SelectFontStyle(node, font->style); exists_font = SelectFontWeight(snode, font->weight); @@ -431,7 +431,6 @@ static LCUI_FontWeight FindBolderWeight(LCUI_FontStyleNode snode, static LCUI_FontWeight FindLighterWeight(LCUI_FontStyleNode snode, LCUI_FontWeight weight) { - int i; for (weight -= 100; weight >= FONT_WEIGHT_THIN; weight -= 100) { if (SelectFontWeight(snode, weight)) { return weight; @@ -513,7 +512,7 @@ void LCUIFont_SetDefault(int id) LCUI_Font font = LCUIFont_GetById(id); if (font) { fontlib.default_font = font; - Logger_Debug("[font] select: %s\n", font->family_name); + logger_debug("[font] select: %s\n", font->family_name); } } @@ -521,7 +520,7 @@ LCUI_FontBitmap *LCUIFont_AddBitmap(wchar_t ch, int font_id, int size, const LCUI_FontBitmap *bmp) { LCUI_FontBitmap *bmp_cache; - RBTree *tree_font, *tree_bmp; + rbtree_t *tree_font, *tree_bmp; if (!fontlib.active) { return NULL; @@ -529,13 +528,13 @@ LCUI_FontBitmap *LCUIFont_AddBitmap(wchar_t ch, int font_id, int size, /* 获取字符的字体信息集 */ tree_font = SelectChar(ch); if (!tree_font) { - tree_font = NEW(RBTree, 1); + tree_font = NEW(rbtree_t, 1); if (!tree_font) { return NULL; } - RBTree_Init(tree_font); - RBTree_OnDestroy(tree_font, DestroyTreeNode); - RBTree_Insert(&fontlib.bitmap_cache, ch, tree_font); + rbtree_init(tree_font); + rbtree_set_destroy_func(tree_font, DestroyTreeNode); + rbtree_insert_by_key(&fontlib.bitmap_cache, ch, tree_font); } /* 当字体ID不大于0时,使用内置字体 */ if (font_id <= 0) { @@ -544,13 +543,13 @@ LCUI_FontBitmap *LCUIFont_AddBitmap(wchar_t ch, int font_id, int size, /* 获取相应字体样式标识号的字体位图库 */ tree_bmp = SelectFont(tree_font, font_id); if (!tree_bmp) { - tree_bmp = NEW(RBTree, 1); + tree_bmp = NEW(rbtree_t, 1); if (!tree_bmp) { return NULL; } - RBTree_Init(tree_bmp); - RBTree_OnDestroy(tree_bmp, DestroyFontBitmap); - RBTree_Insert(tree_font, font_id, tree_bmp); + rbtree_init(tree_bmp); + rbtree_set_destroy_func(tree_bmp, DestroyFontBitmap); + rbtree_insert_by_key(tree_font, font_id, tree_bmp); } /* 在字体位图库中获取指定像素大小的字体位图 */ bmp_cache = SelectBitmap(tree_bmp, size); @@ -559,7 +558,7 @@ LCUI_FontBitmap *LCUIFont_AddBitmap(wchar_t ch, int font_id, int size, if (!bmp_cache) { return NULL; } - RBTree_Insert(tree_bmp, size, bmp_cache); + rbtree_insert_by_key(tree_bmp, size, bmp_cache); } /* 拷贝数据至该空间内 */ memcpy(bmp_cache, bmp, sizeof(LCUI_FontBitmap)); @@ -570,7 +569,7 @@ int LCUIFont_GetBitmap(wchar_t ch, int font_id, int size, const LCUI_FontBitmap **bmp) { int ret; - RBTree *ctx; + rbtree_t *ctx; LCUI_FontBitmap bmp_cache; *bmp = NULL; @@ -619,19 +618,19 @@ static int LCUIFont_LoadFileEx(LCUI_FontEngine *engine, const char *file) LCUI_Font *fonts; int i, num_fonts, id; - Logger_Debug("[font] load file: %s\n", file); + logger_debug("[font] load file: %s\n", file); if (!engine) { return -1; } num_fonts = engine->open(file, &fonts); if (num_fonts < 1) { - Logger_Debug("[font] failed to load file: %s\n", file); + logger_debug("[font] failed to load file: %s\n", file); return -2; } for (i = 0; i < num_fonts; ++i) { fonts[i]->engine = engine; id = LCUIFont_Add(fonts[i]); - Logger_Debug("[font] add font: %d, family: %s, style name: %s, weight: %d\n", + logger_debug("[font] add font: %d, family: %s, style name: %s, weight: %d\n", id, fonts[i]->family_name, fonts[i]->style_name, fonts[i]->weight); } free(fonts); @@ -830,11 +829,11 @@ static void LCUIFont_InitBase(void) fontlib.font_cache_num = 1; fontlib.font_cache = NEW(LCUI_FontCache, 1); fontlib.font_cache[0] = FontCache(); - RBTree_Init(&fontlib.bitmap_cache); - Dict_InitStringKeyType(&fontlib.font_families_type); - fontlib.font_families_type.valDestructor = DestroyFontFamilyNode; - fontlib.font_families = Dict_Create(&fontlib.font_families_type, NULL); - RBTree_OnDestroy(&fontlib.bitmap_cache, DestroyTreeNode); + rbtree_init(&fontlib.bitmap_cache); + dict_init_string_key_type(&fontlib.font_families_type); + fontlib.font_families_type.val_destructor = DestroyFontFamilyNode; + fontlib.font_families = dict_create(&fontlib.font_families_type, NULL); + rbtree_set_destroy_func(&fontlib.bitmap_cache, DestroyTreeNode); fontlib.active = TRUE; } @@ -855,10 +854,10 @@ static void LCUIFont_InitEngine(void) } #endif if (fontlib.engine && fontlib.engine != &fontlib.engines[0]) { - Logger_Debug("[font] current font engine is: %s\n", + logger_debug("[font] current font engine is: %s\n", fontlib.engine->name); } else { - Logger_Warning("[font] warning: not font engine support!\n"); + logger_warning("[font] warning: not font engine support!\n"); } } @@ -872,8 +871,8 @@ static void LCUIFont_FreeBase(void) --fontlib.font_cache_num; DeleteFontCache(fontlib.font_cache[fontlib.font_cache_num]); } - Dict_Release(fontlib.font_families); - RBTree_Destroy(&fontlib.bitmap_cache); + dict_destroy(fontlib.font_families); + rbtree_destroy(&fontlib.bitmap_cache); free(fontlib.font_cache); fontlib.font_cache = NULL; } @@ -974,7 +973,7 @@ static void LCUIFont_LoadDefaultFonts(void) #ifdef LCUI_BUILD_IN_WIN32 LCUIFont_LoadFontsForWindows(); #elif defined(USE_FONTCONFIG) - Logger_Debug("[font] fontconfig enabled\n"); + logger_debug("[font] fontconfig enabled\n"); LCUIFont_LoadFontsByFontConfig(); #else LCUIFont_LoadFontsForLinux(); diff --git a/lib/font/src/freetype.c b/lib/font/src/freetype.c index ba0b2cde..5018dc3e 100644 --- a/lib/font/src/freetype.c +++ b/lib/font/src/freetype.c @@ -32,7 +32,7 @@ #include #ifdef USE_FREETYPE #include -#include +#include #include #include #include diff --git a/lib/font/src/in_core_font.c b/lib/font/src/in_core_font.c index 2c44ecdc..4ce2585c 100644 --- a/lib/font/src/in_core_font.c +++ b/lib/font/src/in_core_font.c @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include enum in_core_font_type { diff --git a/lib/image/src/jpeg.c b/lib/image/src/jpeg.c index 8d19d44e..cd7e1035 100644 --- a/lib/image/src/jpeg.c +++ b/lib/image/src/jpeg.c @@ -34,7 +34,7 @@ #include #include "config.h" #include -#include +#include #include #include @@ -73,7 +73,7 @@ METHODDEF(void) JPEGReader_OnErrorExit(j_common_ptr cinfo) char msg[JMSG_LENGTH_MAX]; LCUI_JPEGError err = (LCUI_JPEGError)cinfo->err; cinfo->err->format_message(cinfo, msg); - Logger_Error("%s\n", msg); + logger_error("%s\n", msg); longjmp(*err->reader->env, 1); } @@ -230,7 +230,7 @@ int LCUI_InitJPEGReader(LCUI_ImageReader reader) jpeg_reader->err.reader = reader; return 0; #else - Logger_Warning("warning: not JPEG support!"); + logger_warning("warning: not JPEG support!"); #endif return -1; } @@ -284,7 +284,7 @@ int LCUI_ReadJPEG(LCUI_ImageReader reader, LCUI_Graph *graph) } return 0; #else - Logger_Warning("warning: not JPEG support!"); + logger_warning("warning: not JPEG support!"); #endif return -ENOSYS; } diff --git a/lib/image/src/png.c b/lib/image/src/png.c index e87ee420..d5fb13f0 100644 --- a/lib/image/src/png.c +++ b/lib/image/src/png.c @@ -105,7 +105,7 @@ int LCUI_InitPNGReader(LCUI_ImageReader reader) error: LCUI_DestroyImageReader(reader); #else - Logger_Warning("warning: not PNG support!"); + logger_warning("warning: not PNG support!"); #endif return -1; } @@ -153,7 +153,7 @@ int LCUI_ReadPNGHeader(LCUI_ImageReader reader) } return 0; #else - Logger_Warning("warning: not PNG support!"); + logger_warning("warning: not PNG support!"); return -ENOSYS; #endif } @@ -220,7 +220,7 @@ int LCUI_ReadPNG(LCUI_ImageReader reader, LCUI_Graph *graph) } return ret; #else - Logger_Warning("warning: not PNG support!"); + logger_warning("warning: not PNG support!"); return -ENOSYS; #endif } @@ -238,13 +238,13 @@ int LCUI_WritePNGFile(const char *file_name, const LCUI_Graph *graph) int y; if (!Graph_IsValid(graph)) { - Logger_Error("graph is not valid\n"); + logger_error("graph is not valid\n"); return -1; } /* create file */ fp = fopen(file_name, "wb"); if (!fp) { - Logger_Error("file %s could not be opened for writing\n", + logger_error("file %s could not be opened for writing\n", file_name); return -1; } @@ -253,19 +253,19 @@ int LCUI_WritePNGFile(const char *file_name, const LCUI_Graph *graph) png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { fclose(fp); - Logger_Error("png_create_write_struct failed\n"); + logger_error("png_create_write_struct failed\n"); return -1; } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { fclose(fp); - Logger_Error("png_create_info_struct failed\n"); + logger_error("png_create_info_struct failed\n"); png_destroy_write_struct(&png_ptr, &info_ptr); return -1; } if (setjmp(png_jmpbuf(png_ptr))) { fclose(fp); - Logger_Error("error during init_io\n"); + logger_error("error during init_io\n"); png_destroy_write_struct(&png_ptr, &info_ptr); return -1; } @@ -334,7 +334,7 @@ int LCUI_WritePNGFile(const char *file_name, const LCUI_Graph *graph) fclose(fp); return 0; #else - Logger_Warning("warning: not PNG support!"); + logger_warning("warning: not PNG support!"); return -ENOSYS; #endif } diff --git a/lib/paint/src/background.c b/lib/paint/src/background.c index 61db9a96..c196d4f1 100644 --- a/lib/paint/src/background.c +++ b/lib/paint/src/background.c @@ -73,13 +73,13 @@ void Background_Paint(const LCUI_Background *bg, /* 根据宽高的缩放比例,计算实际需要引用的区域 */ if (width != bg->image->width) { scale = 1.0 * bg->image->width / width; - rect.x = iround(rect.x * scale); - rect.width = iround(rect.width * scale); + rect.x = y_iround(rect.x * scale); + rect.width = y_iround(rect.width * scale); } if (height != bg->image->height) { scale = 1.0 * bg->image->height / height; - rect.y = iround(rect.y * scale); - rect.height = iround(rect.height * scale); + rect.y = y_iround(rect.y * scale); + rect.height = y_iround(rect.height * scale); } /* 引用源背景图像的一块区域 */ Graph_QuoteReadOnly(&graph, bg->image, &rect); diff --git a/lib/paint/src/border.c b/lib/paint/src/border.c index 4f33033a..d3692e28 100644 --- a/lib/paint/src/border.c +++ b/lib/paint/src/border.c @@ -54,9 +54,9 @@ double outer_d, inner_d; \ \ const double r = CIRCLE_R(radius); \ - const double radius_x = max(0, r - yline->width); \ - const double radius_y = max(0, r - xline->width); \ - const int width = max(radius, yline->width); \ + const double radius_x = y_max(0, r - yline->width); \ + const double radius_y = y_max(0, r - xline->width); \ + const int width = y_max(radius, yline->width); \ \ LCUI_Rect rect; \ LCUI_ARGB *p; \ @@ -102,7 +102,7 @@ static int DrawBorderTopLeft(LCUI_Graph *dst, int bound_left, int bound_top, if (!Graph_IsValid(dst)) { return -1; } - right = min(rect.width, bound_left + width); + right = y_min(rect.width, bound_left + width); for (y = 0; y < rect.height; ++y) { outer_x = 0; split_x = 0; @@ -122,10 +122,10 @@ static int DrawBorderTopLeft(LCUI_Graph *dst, int bound_left, int bound_top, outer_x = bound_left + outer_x; inner_x = bound_left + inner_x; /* Limit coordinates into the current drawing region */ - outer_x = max(0, min(right, outer_x)); - inner_x = max(0, min(right, inner_x)); - outer_xi = max(0, (int)outer_x - (int)radius / 2); - inner_xi = min(right, (int)inner_x + (int)radius / 2); + outer_x = y_max(0, y_min(right, outer_x)); + inner_x = y_max(0, y_min(right, inner_x)); + outer_xi = y_max(0, (int)outer_x - (int)radius / 2); + inner_xi = y_min(right, (int)inner_x + (int)radius / 2); p = Graph_GetPixelPointer(dst, rect.x, rect.y + y); /* Clear the outer pixels */ for (x = 0; x < outer_xi; ++x, ++p) { @@ -195,7 +195,7 @@ static int DrawBorderTopRight(LCUI_Graph *dst, int bound_left, int bound_top, if (!Graph_IsValid(dst)) { return -1; } - right = min(rect.width, bound_left + width); + right = y_min(rect.width, bound_left + width); for (y = 0; y < rect.height; ++y) { outer_x = width; split_x = 0; @@ -216,10 +216,10 @@ static int DrawBorderTopRight(LCUI_Graph *dst, int bound_left, int bound_top, outer_x = bound_left + outer_x; inner_x = bound_left + inner_x; /* Limit coordinates into the current drawing region */ - outer_x = max(0, min(right, outer_x)); - inner_x = max(-1.0, min(outer_x, inner_x)); - inner_xi = max(0, (int)inner_x - (int)radius / 2); - outer_xi = min(right, (int)outer_x + (int)radius / 2); + outer_x = y_max(0, y_min(right, outer_x)); + inner_x = y_max(-1.0, y_min(outer_x, inner_x)); + inner_xi = y_max(0, (int)inner_x - (int)radius / 2); + outer_xi = y_min(right, (int)outer_x + (int)radius / 2); p = Graph_GetPixelPointer(dst, rect.x + inner_xi, rect.y + y); for (x = inner_xi; x < outer_xi; ++x, ++p) { outer_d = -1.0; @@ -268,7 +268,7 @@ static int DrawBorderBottomLeft(LCUI_Graph *dst, int bound_left, int bound_top, { BorderRenderContext(); - int height = max(radius, xline->width); + int height = y_max(radius, xline->width); double cirlce_center_x = bound_left + r; double circle_center_y = bound_top + height - 1.0 * radius - 0.5; double split_k = 1.0 * yline->width / xline->width; @@ -282,7 +282,7 @@ static int DrawBorderBottomLeft(LCUI_Graph *dst, int bound_left, int bound_top, if (!Graph_IsValid(dst)) { return -1; } - right = min(rect.width, bound_left + width); + right = y_min(rect.width, bound_left + width); for (y = 0; y < rect.height; ++y) { outer_x = 0; split_x = 0; @@ -302,10 +302,10 @@ static int DrawBorderBottomLeft(LCUI_Graph *dst, int bound_left, int bound_top, outer_x = bound_left + outer_x; inner_x = bound_left + inner_x; /* Limit coordinates into the current drawing region */ - outer_x = max(0, min(right, outer_x)); - inner_x = max(0, min(right, inner_x)); - outer_xi = max(0, (int)outer_x - (int)radius / 2); - inner_xi = min(right, (int)inner_x + (int)radius / 2); + outer_x = y_max(0, y_min(right, outer_x)); + inner_x = y_max(0, y_min(right, inner_x)); + outer_xi = y_max(0, (int)outer_x - (int)radius / 2); + inner_xi = y_min(right, (int)inner_x + (int)radius / 2); p = Graph_GetPixelPointer(dst, rect.x, rect.y + y); for (x = 0; x < outer_xi; ++x, ++p) { p->alpha = 0; @@ -356,7 +356,7 @@ static int DrawBorderBottomRight(LCUI_Graph *dst, int bound_left, int bound_top, { BorderRenderContext(); - int height = max(radius, xline->width); + int height = y_max(radius, xline->width); double circle_center_y = bound_top + height - 1.0 * radius - 0.5; double circle_center_x = bound_left + width - 1.0 * radius - 0.5; double split_k = 1.0 * yline->width / xline->width; @@ -370,7 +370,7 @@ static int DrawBorderBottomRight(LCUI_Graph *dst, int bound_left, int bound_top, if (!Graph_IsValid(dst)) { return -1; } - right = min(rect.width, bound_left + width); + right = y_min(rect.width, bound_left + width); for (y = 0; y < rect.height; ++y) { outer_x = width; split_x = 0; @@ -391,10 +391,10 @@ static int DrawBorderBottomRight(LCUI_Graph *dst, int bound_left, int bound_top, } outer_x = bound_left + outer_x; inner_x = bound_left + inner_x; - outer_x = max(0, min(right, outer_x)); - inner_x = max(-1.0, min(outer_x, inner_x)); - inner_xi = max(0, (int)inner_x - (int)radius / 2); - outer_xi = min(right, (int)outer_x + (int)radius / 2); + outer_x = y_max(0, y_min(right, outer_x)); + inner_x = y_max(-1.0, y_min(outer_x, inner_x)); + inner_xi = y_max(0, (int)inner_x - (int)radius / 2); + outer_xi = y_min(right, (int)outer_x + (int)radius / 2); p = Graph_GetPixelPointer(dst, rect.x + inner_xi, rect.y + y); for (x = inner_xi; x < outer_xi; ++x, ++p) { outer_d = -1.0; @@ -468,7 +468,7 @@ static int CropContentTopLeft(LCUI_Graph *dst, int bound_left, int bound_top, y = ToGeoY(yi, center_y); x = ellipse_x(radius_x + 1.0, radius_y + 1.0, y); outer_xi = (int)(center_x - x); - outer_xi = max(0, min(outer_xi, rect.width)); + outer_xi = y_max(0, y_min(outer_xi, rect.width)); p = Graph_GetPixelPointer(dst, rect.x, rect.y + yi); for (xi = 0; xi < outer_xi; ++xi, ++p) { p->alpha = 0; @@ -528,9 +528,9 @@ static int CropContentTopRight(LCUI_Graph *dst, int bound_left, int bound_top, } for (yi = 0; yi < rect.height; ++yi) { y = ToGeoY(yi, center_y); - x = ellipse_x(max(0, radius_x - 1), max(0, radius_y - 1), y); + x = ellipse_x(y_max(0, radius_x - 1), y_max(0, radius_y - 1), y); outer_xi = (int)(center_x + x); - outer_xi = max(0, outer_xi); + outer_xi = y_max(0, outer_xi); p = Graph_GetPixelPointer(dst, rect.x + outer_xi, rect.y + yi); if (radius_x == radius_y) { for (xi = outer_xi; xi < rect.width; ++xi, ++p) { @@ -589,7 +589,7 @@ static int CropContentBottomLeft(LCUI_Graph *dst, int bound_left, int bound_top, y = ToGeoY(yi, center_y); x = ellipse_x(radius_x + 1.0, radius_y + 1.0, y); outer_xi = (int)(center_x - x); - outer_xi = max(0, min(outer_xi, rect.width)); + outer_xi = y_max(0, y_min(outer_xi, rect.width)); p = Graph_GetPixelPointer(dst, rect.x, rect.y + yi); for (xi = 0; xi < outer_xi; ++xi, ++p) { p->alpha = 0; @@ -649,9 +649,9 @@ static int CropContentBottomRight(LCUI_Graph *dst, int bound_left, } for (yi = 0; yi < rect.height; ++yi) { y = ToGeoY(yi, center_y); - x = ellipse_x(max(0, radius_x - 1), max(0, radius_y - 1), y); + x = ellipse_x(y_max(0, radius_x - 1), y_max(0, radius_y - 1), y); outer_xi = (int)(center_x + x); - outer_xi = max(0, outer_xi); + outer_xi = y_max(0, outer_xi); p = Graph_GetPixelPointer(dst, rect.x + outer_xi, rect.y + yi); if (radius_x == radius_y) { for (xi = outer_xi; xi < rect.width; ++xi, ++p) { @@ -768,14 +768,14 @@ int Border_Paint(const LCUI_Border *border, const LCUI_Rect *box, LCUI_Rect bound, rect; int bound_top, bound_left; - int tl_width = max(border->top_left_radius, border->left.width); - int tl_height = max(border->top_left_radius, border->top.width); - int tr_width = max(border->top_right_radius, border->right.width); - int tr_height = max(border->top_right_radius, border->top.width); - int bl_width = max(border->bottom_left_radius, border->left.width); - int bl_height = max(border->bottom_left_radius, border->bottom.width); - int br_width = max(border->bottom_right_radius, border->right.width); - int br_height = max(border->bottom_right_radius, border->bottom.width); + int tl_width = y_max(border->top_left_radius, border->left.width); + int tl_height = y_max(border->top_left_radius, border->top.width); + int tr_width = y_max(border->top_right_radius, border->right.width); + int tr_height = y_max(border->top_right_radius, border->top.width); + int bl_width = y_max(border->bottom_left_radius, border->left.width); + int bl_height = y_max(border->bottom_left_radius, border->bottom.width); + int br_width = y_max(border->bottom_right_radius, border->right.width); + int br_height = y_max(border->bottom_right_radius, border->bottom.width); if (!Graph_IsValid(&paint->canvas)) { return -1; diff --git a/lib/paint/src/boxshadow.c b/lib/paint/src/boxshadow.c index e12240d0..4d8a2967 100644 --- a/lib/paint/src/boxshadow.c +++ b/lib/paint/src/boxshadow.c @@ -150,12 +150,12 @@ void BoxShadow_GetCanvasRect(const LCUI_BoxShadow *shadow, shadow_rect.y = content_rect->y - SHADOW_WIDTH(shadow) + shadow->y; shadow_rect.width = BoxShadow_GetWidth(shadow, content_rect->width); shadow_rect.height = BoxShadow_GetHeight(shadow, content_rect->height); - canvas_rect->x = min(content_rect->x, shadow_rect.x); - canvas_rect->y = min(content_rect->y, shadow_rect.y); - canvas_rect->width = max(shadow_rect.x + shadow_rect.width, + canvas_rect->x = y_min(content_rect->x, shadow_rect.x); + canvas_rect->y = y_min(content_rect->y, shadow_rect.y); + canvas_rect->width = y_max(shadow_rect.x + shadow_rect.width, content_rect->x + content_rect->width) - canvas_rect->x; - canvas_rect->height = max(shadow_rect.y + shadow_rect.height, + canvas_rect->height = y_max(shadow_rect.y + shadow_rect.height, content_rect->y + content_rect->height) - canvas_rect->y; } @@ -334,9 +334,9 @@ static LCUI_BOOL BoxShadow_PaintCircleBlur(BoxShadowRenderingContext ctx, { double d; double y2; - double r = max(0, CIRCLE_R(radius)); + double r = y_max(0, CIRCLE_R(radius)); double outer_r2 = POW2(r); - double inner_r = max(0, r - BLUR_WIDTH(ctx->shadow)); + double inner_r = y_max(0, r - BLUR_WIDTH(ctx->shadow)); double inner_smooth_r2 = POW2(inner_r + 1.0); int x, y; @@ -403,7 +403,7 @@ static LCUI_BOOL BoxShadow_PaintTopLeftBlur(BoxShadowRenderingContext ctx) LCUI_Rect rect; radius = FULL_SHADOW_WIDTH(ctx) + ctx->shadow->top_left_radius; - radius = min(ctx->max_radius, radius); + radius = y_min(ctx->max_radius, radius); rect.width = radius; rect.height = rect.width; rect.x = ctx->shadow_box.x; @@ -418,7 +418,7 @@ static LCUI_BOOL BoxShadow_PaintTopRightBlur(BoxShadowRenderingContext ctx) LCUI_Rect rect; radius = FULL_SHADOW_WIDTH(ctx) + ctx->shadow->top_right_radius; - radius = min(ctx->max_radius, radius); + radius = y_min(ctx->max_radius, radius); rect.width = radius; rect.height = rect.width; rect.x = ctx->shadow_box.x + ctx->shadow_box.width - rect.width; @@ -432,7 +432,7 @@ static LCUI_BOOL BoxShadow_PaintBottomLeftBlur(BoxShadowRenderingContext ctx) LCUI_Rect rect; radius = FULL_SHADOW_WIDTH(ctx) + ctx->shadow->bottom_left_radius; - radius = min(ctx->max_radius, radius); + radius = y_min(ctx->max_radius, radius); rect.width = radius; rect.height = rect.width; rect.x = ctx->shadow_box.x; @@ -446,7 +446,7 @@ static LCUI_BOOL BoxShadow_PaintBottomRightBlur(BoxShadowRenderingContext ctx) LCUI_Rect rect; radius = FULL_SHADOW_WIDTH(ctx) + ctx->shadow->bottom_right_radius; - radius = min(ctx->max_radius, radius); + radius = y_min(ctx->max_radius, radius); rect.width = radius; rect.height = rect.width; rect.x = ctx->shadow_box.x + ctx->shadow_box.width - rect.width; @@ -514,12 +514,12 @@ static void BoxShadow_ClearContentRect(BoxShadowRenderingContext ctx) LCUI_Rect rect; LCUI_Rect bound; LCUI_Graph canvas; - LinkedList rects; - LinkedListNode *node; + list_t rects; + list_node_t *node; /* Initialize a queue for recording the area after the split content * area */ - LinkedList_Init(&rects); + list_create(&rects); RectList_Add(&rects, &ctx->content_box); r = ctx->shadow->top_left_radius; @@ -587,7 +587,7 @@ static void BoxShadow_ClearContentRect(BoxShadowRenderingContext ctx) } /* Clear pixels in the remaining areas of the content area */ - for (LinkedList_Each(node, &rects)) { + for (list_each(node, &rects)) { if (LCUIRect_GetOverlayRect(&ctx->paint->rect, node->data, &rect)) { rect.x -= ctx->paint->rect.x; @@ -619,7 +619,7 @@ int BoxShadow_Paint(const LCUI_BoxShadow *shadow, const LCUI_Rect *box, ctx.box = box; ctx.shadow = shadow; ctx.max_radius = - min(content_width, content_height) / 2 + SHADOW_WIDTH(shadow); + y_min(content_width, content_height) / 2 + SHADOW_WIDTH(shadow); ctx.shadow_box.x = BoxShadow_GetX(shadow); ctx.shadow_box.y = BoxShadow_GetY(shadow); ctx.shadow_box.width = BoxShadow_GetWidth(shadow, content_width); diff --git a/lib/paint/src/graph.c b/lib/paint/src/graph.c index 586ffbb2..5cfb476b 100644 --- a/lib/paint/src/graph.c +++ b/lib/paint/src/graph.c @@ -739,7 +739,7 @@ int Graph_Create(LCUI_Graph *graph, unsigned width, unsigned height) { size_t size; if (width > 10000 || height > 10000) { - Logger_Error("graph size is too large!"); + logger_error("graph size is too large!"); abort(); } if (width < 1 || height < 1) { @@ -1043,7 +1043,7 @@ int Graph_ZoomBilinear(const LCUI_Graph *graph, LCUI_Graph *buff, if (graph->color_type != LCUI_COLOR_TYPE_RGB && graph->color_type != LCUI_COLOR_TYPE_ARGB) { /* fall back to nearest scaling */ - Logger_Debug("[graph] unable to perform bilinear scaling, " + logger_debug("[graph] unable to perform bilinear scaling, " "fallback...\n"); return Graph_Zoom(graph, buff, keep_scale, width, height); } diff --git a/lib/platform/src/cursor.c b/lib/platform/src/cursor.c index 8dea3924..f9c021e6 100644 --- a/lib/platform/src/cursor.c +++ b/lib/platform/src/cursor.c @@ -157,10 +157,10 @@ void LCUICursor_GetRect(LCUI_Rect *rect) { float scale; scale = LCUIMetrics_GetScale(); - rect->x = iround(cursor.pos.x / scale); - rect->y = iround(cursor.pos.y / scale); - rect->width = iround(cursor.graph.width / scale); - rect->height = iround(cursor.graph.height / scale); + rect->x = y_iround(cursor.pos.x / scale); + rect->y = y_iround(cursor.pos.y / scale); + rect->width = y_iround(cursor.graph.width / scale); + rect->height = y_iround(cursor.graph.height / scale); } void LCUICursor_Refresh(void) diff --git a/lib/platform/src/display.c b/lib/platform/src/display.c index 2c76b684..ace81bd4 100644 --- a/lib/platform/src/display.c +++ b/lib/platform/src/display.c @@ -65,10 +65,10 @@ typedef struct SurfaceRecordRec_ { LCUI_BOOL rendered; /** dirty rectangles for rendering */ - LinkedList rects; + list_t rects; /** flashing rect list */ - LinkedList flash_rects; + list_t flash_rects; LCUI_Surface surface; LCUI_Widget widget; @@ -78,8 +78,8 @@ static struct LCUI_DisplayModule { unsigned width, height; LCUI_BOOL active; LCUI_DisplayMode mode; - LinkedList surfaces; - LinkedList rects; + list_t surfaces; + list_t rects; LCUI_DisplayDriver driver; LCUI_SettingsRec settings; int settings_change_handler_id; @@ -88,7 +88,7 @@ static struct LCUI_DisplayModule { /* clang-format on */ #define LCUIDisplay_CleanSurfaces() \ - LinkedList_Clear(&display.surfaces, OnDestroySurfaceRecord) + list_destroy(&display.surfaces, OnDestroySurfaceRecord) INLINE int is_rect_equals(const LCUI_Rect *a, const LCUI_Rect *b) { @@ -101,8 +101,8 @@ static void OnDestroySurfaceRecord(void *data) SurfaceRecord record = data; Surface_Close(record->surface); - LinkedList_Clear(&record->rects, free); - LinkedList_Clear(&record->flash_rects, free); + list_destroy(&record->rects, free); + list_destroy(&record->flash_rects, free); free(record); } @@ -127,7 +127,7 @@ static size_t LCUIDisplay_RenderFlashRect(SurfaceRecord record, if (!paint) { return 0; } - period = LCUI_GetTimeDelta(flash_rect->paint_time); + period = get_time_delta(flash_rect->paint_time); count = Widget_Render(record->widget, paint); if (period >= duraion) { flash_rect->paint_time = 0; @@ -158,14 +158,14 @@ static size_t LCUIDisplay_UpdateFlashRects(SurfaceRecord record) { size_t count = 0; FlashRect flash_rect; - LinkedListNode *node, *prev; + list_node_t *node, *prev; - for (LinkedList_Each(node, &record->flash_rects)) { + for (list_each(node, &record->flash_rects)) { flash_rect = node->data; if (flash_rect->paint_time == 0) { prev = node->prev; free(node->data); - LinkedList_DeleteNode(&record->flash_rects, node); + list_delete_node(&record->flash_rects, node); node = prev; continue; } @@ -177,21 +177,21 @@ static size_t LCUIDisplay_UpdateFlashRects(SurfaceRecord record) static void LCUIDisplay_AppendFlashRects(SurfaceRecord record, LCUI_Rect *rect) { - LinkedListNode *node; + list_node_t *node; FlashRect flash_rect; - for (LinkedList_Each(node, &record->flash_rects)) { + for (list_each(node, &record->flash_rects)) { flash_rect = node->data; if (is_rect_equals(&flash_rect->rect, rect)) { - flash_rect->paint_time = LCUI_GetTime(); + flash_rect->paint_time = get_time_ms(); return; } } flash_rect = NEW(FlashRectRec, 1); flash_rect->rect = *rect; - flash_rect->paint_time = LCUI_GetTime(); - LinkedList_Append(&record->flash_rects, flash_rect); + flash_rect->paint_time = get_time_ms(); + list_append(&record->flash_rects, flash_rect); } static void GetRenderingLayerSize(int *width, int *height) @@ -201,13 +201,13 @@ static void GetRenderingLayerSize(int *width, int *height) *width = (int)(LCUIDisplay_GetWidth() * scale); *height = (int)(LCUIDisplay_GetHeight() * scale); *height = - max(200, *height / display.settings.parallel_rendering_threads + 1); + y_max(200, *height / display.settings.parallel_rendering_threads + 1); } -static void SurfaceRecord_DumpRects(SurfaceRecord record, LinkedList *rects) +static void SurfaceRecord_DumpRects(SurfaceRecord record, list_t *rects) { typedef struct DirtyLayerRec { - LinkedList rects; + list_t rects; LCUI_Rect rect; int diry; } DirtyLayerRec, *DirtyLayer; @@ -221,7 +221,7 @@ static void SurfaceRecord_DumpRects(SurfaceRecord record, LinkedList *rects) LCUI_Rect *sub_rect; DirtyLayer layer; DirtyLayerRec *layers; - LinkedListNode *node; + list_node_t *node; GetRenderingLayerSize(&layer_width, &layer_height); max_dirty = (int)(0.8 * layer_width * layer_height); @@ -234,10 +234,10 @@ static void SurfaceRecord_DumpRects(SurfaceRecord record, LinkedList *rects) layer->rect.x = 0; layer->rect.width = layer_width; layer->rect.height = layer_height; - LinkedList_Init(&layer->rects); + list_create(&layer->rects); } sub_rect = malloc(sizeof(LCUI_Rect)); - for (LinkedList_Each(node, &record->rects)) { + for (list_each(node, &record->rects)) { rect = *(LCUI_Rect *)node->data; for (i = 0; i < display.settings.parallel_rendering_threads; ++i) { @@ -249,7 +249,7 @@ static void SurfaceRecord_DumpRects(SurfaceRecord record, LinkedList *rects) sub_rect)) { continue; } - LinkedList_Append(&layer->rects, sub_rect); + list_append(&layer->rects, sub_rect); rect.y += sub_rect->height; rect.height -= sub_rect->height; layer->diry += sub_rect->width * sub_rect->height; @@ -265,7 +265,7 @@ static void SurfaceRecord_DumpRects(SurfaceRecord record, LinkedList *rects) RectList_AddEx(rects, &layer->rect, FALSE); RectList_Clear(&layer->rects); } else { - LinkedList_Concat(rects, &layer->rects); + list_concat(rects, &layer->rects); } } RectList_Clear(&record->rects); @@ -309,17 +309,17 @@ static size_t LCUIDisplay_RenderSurface(SurfaceRecord record) int layer_height; size_t count = 0; LCUI_Rect **rect_array; - LinkedList rects; - LinkedListNode *node; + list_t rects; + list_node_t *node; - LinkedList_Init(&rects); + list_create(&rects); GetRenderingLayerSize(&layer_width, &layer_height); SurfaceRecord_DumpRects(record, &rects); if (rects.length < 1) { return 0; } rect_array = (LCUI_Rect **)malloc(sizeof(LCUI_Rect *) * rects.length); - for (LinkedList_Each(node, &rects)) { + for (list_each(node, &rects)) { LCUI_SysEventRec ev; rect_array[i] = node->data; @@ -358,13 +358,13 @@ static size_t LCUIDisplay_RenderSurface(SurfaceRecord record) void LCUIDisplay_Update(void) { LCUI_Surface surface; - LinkedListNode *node; + list_node_t *node; SurfaceRecord record = NULL; if (!display.active) { return; } - for (LinkedList_Each(node, &display.surfaces)) { + for (list_each(node, &display.surfaces)) { record = node->data; surface = record->surface; if (record->widget && surface && Surface_IsReady(surface)) { @@ -375,18 +375,18 @@ void LCUIDisplay_Update(void) if (display.mode == LCUI_DMODE_SEAMLESS || !record) { return; } - LinkedList_Concat(&record->rects, &display.rects); + list_concat(&record->rects, &display.rects); } size_t LCUIDisplay_Render(void) { size_t count = 0; - LinkedListNode *node; + list_node_t *node; if (!display.active) { return 0; } - for (LinkedList_Each(node, &display.surfaces)) { + for (list_each(node, &display.surfaces)) { count += LCUIDisplay_RenderSurface(node->data); count += LCUIDisplay_UpdateFlashRects(node->data); } @@ -395,12 +395,12 @@ size_t LCUIDisplay_Render(void) void LCUIDisplay_Present(void) { - LinkedListNode *sn; + list_node_t *sn; if (!display.active) { return; } - for (LinkedList_Each(sn, &display.surfaces)) { + for (list_each(sn, &display.surfaces)) { SurfaceRecord record = sn->data; LCUI_Surface surface = record->surface; if (!surface || !Surface_IsReady(surface)) { @@ -433,9 +433,9 @@ void LCUIDisplay_InvalidateArea(LCUI_Rect *rect) static LCUI_Widget LCUIDisplay_GetBindWidget(LCUI_Surface surface) { SurfaceRecord record; - LinkedListNode *node; + list_node_t *node; - for (LinkedList_Each(node, &display.surfaces)) { + for (list_each(node, &display.surfaces)) { record = node->data; if (record && record->surface == surface) { return record->widget; @@ -447,9 +447,9 @@ static LCUI_Widget LCUIDisplay_GetBindWidget(LCUI_Surface surface) static LCUI_Surface LCUIDisplay_GetBindSurface(LCUI_Widget widget) { SurfaceRecord record; - LinkedListNode *node; + list_node_t *node; - for (LinkedList_Each(node, &display.surfaces)) { + for (list_each(node, &display.surfaces)) { record = node->data; if (record && record->widget == widget) { return record->surface; @@ -472,9 +472,9 @@ LCUI_Surface LCUIDisplay_GetSurfaceOwner(LCUI_Widget w) LCUI_Surface LCUIDisplay_GetSurfaceByHandle(void *handle) { - LinkedListNode *node; + list_node_t *node; - for (LinkedList_Each(node, &display.surfaces)) { + for (list_each(node, &display.surfaces)) { SurfaceRecord record = node->data; if (Surface_GetHandle(record->surface) == handle) { return record->surface; @@ -496,7 +496,7 @@ static void LCUIDisplay_BindSurface(LCUI_Widget widget) record->surface = Surface_New(); record->widget = widget; record->rendered = FALSE; - LinkedList_Init(&record->flash_rects); + list_create(&record->flash_rects); LCUIMetrics_ComputeRectActual(&rect, &widget->box.canvas); if (Widget_CheckStyleValid(widget, key_top) && Widget_CheckStyleValid(widget, key_left)) { @@ -510,20 +510,20 @@ static void LCUIDisplay_BindSurface(LCUI_Widget widget) Surface_Hide(record->surface); } Widget_InvalidateArea(widget, NULL, SV_GRAPH_BOX); - LinkedList_Append(&display.surfaces, record); + list_append(&display.surfaces, record); } /** 解除 widget 与 sruface 的绑定 */ static void LCUIDisplay_UnbindSurface(LCUI_Widget widget) { SurfaceRecord record; - LinkedListNode *node; + list_node_t *node; - for (LinkedList_Each(node, &display.surfaces)) { + for (list_each(node, &display.surfaces)) { record = node->data; if (record && record->widget == widget) { Surface_Close(record->surface); - LinkedList_DeleteNode(&display.surfaces, node); + list_delete_node(&display.surfaces, node); break; } } @@ -580,7 +580,7 @@ static int LCUIDisplay_FullScreen(void) static int LCUIDisplay_Seamless(void) { - LinkedListNode *node; + list_node_t *node; LCUI_Widget root = LCUIWidget_GetRoot(); switch (display.mode) { @@ -592,7 +592,7 @@ static int LCUIDisplay_Seamless(void) LCUIDisplay_CleanSurfaces(); break; } - for (LinkedList_Each(node, &root->children)) { + for (list_each(node, &root->children)) { LCUIDisplay_BindSurface(node->data); } display.mode = LCUI_DMODE_SEAMLESS; @@ -657,7 +657,7 @@ int LCUIDisplay_GetWidth(void) } if (display.mode == LCUI_DMODE_WINDOWED || display.mode == LCUI_DMODE_FULLSCREEN) { - return iround(LCUIWidget_GetRoot()->width); + return y_iround(LCUIWidget_GetRoot()->width); } return display.driver->getWidth(); } @@ -669,7 +669,7 @@ int LCUIDisplay_GetHeight(void) } if (display.mode == LCUI_DMODE_WINDOWED || display.mode == LCUI_DMODE_FULLSCREEN) { - return iround(LCUIWidget_GetRoot()->height); + return y_iround(LCUIWidget_GetRoot()->height); } return display.driver->getHeight(); } @@ -683,15 +683,15 @@ void Surface_Close(LCUI_Surface surface) void Surface_Destroy(LCUI_Surface surface) { - LinkedListNode *node; + list_node_t *node; if (!display.active) { return; } - for (LinkedList_Each(node, &display.surfaces)) { + for (list_each(node, &display.surfaces)) { SurfaceRecord record = node->data; if (record && record->surface == surface) { - LinkedList_DeleteNode(&display.surfaces, node); + list_delete_node(&display.surfaces, node); display.driver->destroy(surface); free(record); break; @@ -869,11 +869,11 @@ static void OnSurfaceEvent(LCUI_Widget w, LCUI_WidgetEvent e, void *arg) static void OnPaint(LCUI_Event e, void *arg) { LCUI_RectF rect; - LinkedListNode *node; + list_node_t *node; SurfaceRecord record; LCUI_DisplayEvent dpy_ev = arg; - for (LinkedList_Each(node, &display.surfaces)) { + for (list_each(node, &display.surfaces)) { record = node->data; if (record && record->surface != dpy_ev->surface) { continue; @@ -910,19 +910,19 @@ static void OnMinMaxInfo(LCUI_Event e, void *arg) int height = Surface_GetHeight(s); if (style->min_width >= 0) { - dpy_ev->minmaxinfo.min_width = iround(style->min_width); + dpy_ev->minmaxinfo.min_width = y_iround(style->min_width); resizable = resizable || width < style->min_width; } if (style->max_width >= 0) { - dpy_ev->minmaxinfo.max_width = iround(style->max_width); + dpy_ev->minmaxinfo.max_width = y_iround(style->max_width); resizable = resizable || width > style->max_width; } if (style->min_height >= 0) { - dpy_ev->minmaxinfo.min_height = iround(style->min_height); + dpy_ev->minmaxinfo.min_height = y_iround(style->min_height); resizable = resizable || height < style->min_height; } if (style->max_height >= 0) { - dpy_ev->minmaxinfo.max_height = iround(style->max_height); + dpy_ev->minmaxinfo.max_height = y_iround(style->max_height); resizable = resizable || height > style->max_height; } if (resizable) { @@ -948,7 +948,7 @@ int LCUI_InitDisplay(LCUI_DisplayDriver driver) if (display.active) { return -1; } - Logger_Debug("[display] init ...\n"); + logger_debug("[display] init ...\n"); display.mode = 0; display.driver = driver; display.active = TRUE; @@ -958,13 +958,13 @@ int LCUI_InitDisplay(LCUI_DisplayDriver driver) display.settings_change_handler_id = LCUI_BindEvent( LCUI_SETTINGS_CHANGE, OnSettingsChangeEvent, NULL, NULL); - LinkedList_Init(&display.rects); - LinkedList_Init(&display.surfaces); + list_create(&display.rects); + list_create(&display.surfaces); if (!display.driver) { display.driver = LCUI_CreateDisplayDriver(); } if (!display.driver) { - Logger_Warning("[display] init failed\n"); + logger_warning("[display] init failed\n"); LCUIDisplay_SetMode(LCUI_DMODE_DEFAULT); LCUIDisplay_Update(); return -2; @@ -977,7 +977,7 @@ int LCUI_InitDisplay(LCUI_DisplayDriver driver) Widget_BindEvent(root, "surface", OnSurfaceEvent, NULL, NULL); LCUIDisplay_SetMode(LCUI_DMODE_DEFAULT); LCUIDisplay_Update(); - Logger_Debug("[display] init ok, driver name: %s\n", + logger_debug("[display] init ok, driver name: %s\n", display.driver->name); return 0; } diff --git a/lib/platform/src/ime.c b/lib/platform/src/ime.c index 8966bf6e..f1c6bce4 100644 --- a/lib/platform/src/ime.c +++ b/lib/platform/src/ime.c @@ -45,12 +45,12 @@ typedef struct LCUI_IMERec_ { int id; char *name; LCUI_IMEHandlerRec handler; - LinkedListNode node; + list_node_t node; } LCUI_IMERec, *LCUI_IME; static struct LCUI_InputMethodEngine { int id_count; - LinkedList list; + list_t list; LCUI_IME ime; LCUI_BOOL enable_caps_lock; @@ -59,8 +59,8 @@ static struct LCUI_InputMethodEngine { static LCUI_IME LCUIIME_Find(int ime_id) { - LinkedListNode *node; - for (LinkedList_Each(node, &self.list)) { + list_node_t *node; + for (list_each(node, &self.list)) { LCUI_IME ime = node->data; if (ime->id == ime_id) { return ime; @@ -71,8 +71,8 @@ static LCUI_IME LCUIIME_Find(int ime_id) static LCUI_IME LCUIIME_FindByName(const char *name) { - LinkedListNode *node; - for (LinkedList_Each(node, &self.list)) { + list_node_t *node; + for (list_each(node, &self.list)) { LCUI_IME ime = node->data; if (strcmp(ime->name, name) == 0) { return ime; @@ -105,7 +105,7 @@ int LCUIIME_Register(const char *name, LCUI_IMEHandler handler) ime->node.data = ime; strncpy(ime->name, name, len); memcpy(&ime->handler, handler, sizeof(LCUI_IMEHandlerRec)); - LinkedList_AppendNode(&self.list, &ime->node); + list_append_node(&self.list, &ime->node); return ime->id; } @@ -120,7 +120,7 @@ static LCUI_BOOL LCUIIME_Open(LCUI_IME ime) static LCUI_BOOL LCUIIME_Close(LCUI_IME ime) { if (ime && ime->handler.close) { - Logger_Debug("[ime] close engine: %s\n", ime->name); + logger_debug("[ime] close engine: %s\n", ime->name); return ime->handler.close(); } return FALSE; @@ -131,7 +131,7 @@ LCUI_BOOL LCUIIME_Select(int ime_id) LCUI_IME ime = LCUIIME_Find(ime_id); if (ime) { LCUIIME_Close(self.ime); - Logger_Debug("[ime] select engine: %s\n", ime->name); + logger_debug("[ime] select engine: %s\n", ime->name); self.ime = ime; LCUIIME_Open(self.ime); return TRUE; @@ -256,7 +256,7 @@ static void LCUIIME_OnKeyDown(LCUI_SysEvent e, void *arg) void LCUI_InitIME(void) { - LinkedList_Init(&self.list); + list_create(&self.list); self.active = TRUE; LCUI_BindEvent(LCUI_KEYDOWN, LCUIIME_OnKeyDown, NULL, NULL); #ifdef WINAPI_FAMILY_APP @@ -281,5 +281,5 @@ void LCUI_FreeIME(void) { self.active = FALSE; LCUIIME_Close(self.ime); - LinkedList_ClearData(&self.list, LCUIIME_OnDestroy); + list_destroy_without_node(&self.list, LCUIIME_OnDestroy); } diff --git a/lib/platform/src/keyboard.c b/lib/platform/src/keyboard.c index f558e340..cbb5de75 100644 --- a/lib/platform/src/keyboard.c +++ b/lib/platform/src/keyboard.c @@ -42,7 +42,7 @@ typedef struct KeyStateNodeRec_ { static struct LCUIKeyboardModule { LCUI_Mutex mutex; - RBTree state_tree; + rbtree_t state_tree; } self; /** 检测指定键值的按键是否处于按下状态 */ @@ -50,7 +50,7 @@ LCUI_BOOL LCUIKeyboard_IsHit(int key_code) { KeyStateNode node; LCUIMutex_Lock(&self.mutex); - node = RBTree_GetData(&self.state_tree, key_code); + node = rbtree_get_data_by_key(&self.state_tree, key_code); LCUIMutex_Unlock(&self.mutex); if (node && node->state == LCUI_KSTATE_PRESSED) { return TRUE; @@ -70,7 +70,7 @@ LCUI_BOOL LCUIKeyboard_IsDoubleHit(int key_code, int interval_time) /* 计算当前时间(单位:毫秒) */ ct = clock() * 1000 / CLOCKS_PER_SEC; LCUIMutex_Lock(&self.mutex); - node = RBTree_GetData(&self.state_tree, key_code); + node = rbtree_get_data_by_key(&self.state_tree, key_code); LCUIMutex_Unlock(&self.mutex); if (!node) { return FALSE; @@ -94,13 +94,13 @@ void LCUIKeyboard_HitKey(int key_code) KeyStateNode node; LCUIMutex_Lock(&self.mutex); ct = clock() * 1000 / CLOCKS_PER_SEC; - node = RBTree_GetData(&self.state_tree, key_code); + node = rbtree_get_data_by_key(&self.state_tree, key_code); if (!node) { node = NEW(KeyStateNodeRec, 1); node->interval_time = -1; node->hit_time = ct; node->state = LCUI_KSTATE_PRESSED; - RBTree_Insert(&self.state_tree, key_code, node); + rbtree_insert_by_key(&self.state_tree, key_code, node); LCUIMutex_Unlock(&self.mutex); return; } @@ -119,7 +119,7 @@ void LCUIKeyboard_ReleaseKey(int key_code) { KeyStateNode node; LCUIMutex_Lock(&self.mutex); - node = RBTree_GetData(&self.state_tree, key_code); + node = rbtree_get_data_by_key(&self.state_tree, key_code); if (node) { node->state = LCUI_KSTATE_RELEASE; } @@ -138,14 +138,14 @@ static void OnKeyboardEvent(LCUI_SysEvent e, void *arg) void LCUI_InitKeyboard(void) { LCUIMutex_Init(&self.mutex); - RBTree_Init(&self.state_tree); - RBTree_OnDestroy(&self.state_tree, free); + rbtree_init(&self.state_tree); + rbtree_set_destroy_func(&self.state_tree, free); LCUI_BindEvent(LCUI_KEYDOWN, OnKeyboardEvent, NULL, NULL); LCUI_BindEvent(LCUI_KEYUP, OnKeyboardEvent, NULL, NULL); } void LCUI_FreeKeyboard(void) { - RBTree_Destroy(&self.state_tree); + rbtree_destroy(&self.state_tree); LCUIMutex_Destroy(&self.mutex); } diff --git a/lib/platform/src/linux/linux_display.c b/lib/platform/src/linux/linux_display.c index 86440882..67f9d862 100644 --- a/lib/platform/src/linux/linux_display.c +++ b/lib/platform/src/linux/linux_display.c @@ -48,7 +48,7 @@ LCUI_DisplayDriver LCUI_CreateLinuxDisplayDriver(void) LCUI_DisplayDriver driver = NULL; #ifdef USE_LIBX11 driver_type = X11; - Logger_Debug("[display] init x11 display driver ...\n"); + logger_debug("[display] init x11 display driver ...\n"); driver = LCUI_CreateLinuxX11DisplayDriver(); #endif #ifdef LCUI_VIDEO_DRIVER_FRAMEBUFFER diff --git a/lib/platform/src/linux/linux_fbdisplay.c b/lib/platform/src/linux/linux_fbdisplay.c index 8cb30cba..4027dd43 100644 --- a/lib/platform/src/linux/linux_fbdisplay.c +++ b/lib/platform/src/linux/linux_fbdisplay.c @@ -73,7 +73,7 @@ typedef struct LCUI_SurfaceRec_ { LCUI_Rect actual_rect; LCUI_Mutex mutex; LCUI_Graph canvas; - LinkedList rects; + list_t rects; LCUI_SurfaceTasks tasks; } LCUI_SurfaceRec; @@ -122,8 +122,8 @@ static void FBSurface_RunTask(LCUI_Surface surface, int type) switch (type) { case TASK_RESIZE: LCUIMutex_Lock(&surface->mutex); - task->width = max(task->width, MIN_WIDTH); - task->height = max(task->height, MIN_HEIGHT); + task->width = y_max(task->width, MIN_WIDTH); + task->height = y_max(task->height, MIN_HEIGHT); FBSurface_OnResize(surface, task->width, task->height); LCUIMutex_Unlock(&surface->mutex); break; @@ -324,12 +324,12 @@ static void FBDisplay_SyncRect(LCUI_Surface surface, LCUI_Rect *rect) static void FBSurface_Present(LCUI_Surface surface) { - LinkedListNode *node; + list_node_t *node; LCUIMutex_Lock(&surface->mutex); - for (LinkedList_Each(node, &surface->rects)) { + for (list_each(node, &surface->rects)) { FBDisplay_SyncRect(surface, node->data); } - LinkedList_Clear(&surface->rects, free); + list_destroy(&surface->rects, free); LCUIMutex_Unlock(&surface->mutex); } @@ -467,7 +467,7 @@ static void FBDisplay_InitSurface(void) Graph_Init(&surface->canvas); LCUIMutex_Init(&surface->mutex); - LinkedList_Init(&surface->rects); + list_create(&surface->rects); display.surface_count = 0; surface->canvas.color_type = LCUI_COLOR_TYPE_ARGB; FBSurface_Resize(surface, display.width, display.height); @@ -479,10 +479,10 @@ static int FBDisplay_Init(void) if (!display.fb.dev_path) { display.fb.dev_path = "/dev/fb0"; } - Logger_Debug("[display] open framebuffer device: %s\n", display.fb.dev_path); + logger_debug("[display] open framebuffer device: %s\n", display.fb.dev_path); display.fb.dev_fd = open(display.fb.dev_path, O_RDWR); if (display.fb.dev_fd == -1) { - Logger_Error("[display] open framebuffer device failed\n"); + logger_error("[display] open framebuffer device failed\n"); return -1; } ioctl(display.fb.dev_fd, FBIOGET_VSCREENINFO, &display.fb.var_info); @@ -493,7 +493,7 @@ static int FBDisplay_Init(void) display.fb.mem = mmap(NULL, display.fb.mem_len, PROT_READ | PROT_WRITE, MAP_SHARED, display.fb.dev_fd, 0); if ((void *)-1 == display.fb.mem) { - Logger_Error("[display] framebuffer mmap failed\n"); + logger_error("[display] framebuffer mmap failed\n"); return -1; } FBDisplay_PrintInfo(); diff --git a/lib/platform/src/linux/linux_keyboard.c b/lib/platform/src/linux/linux_keyboard.c index 15a15d7a..9c648262 100644 --- a/lib/platform/src/linux/linux_keyboard.c +++ b/lib/platform/src/linux/linux_keyboard.c @@ -70,7 +70,7 @@ static void LinuxKeybnoardThread(void *arg) struct input_event data; keyboard.active = TRUE; - Logger_Debug("[input] keyboard driver thread: %lld\n", keyboard.tid); + logger_debug("[input] keyboard driver thread: %lld\n", keyboard.tid); while (keyboard.active) { bytes = read(keyboard.dev_fd, &data, sizeof(data)); if (bytes > 0 && data.type == EV_KEY) { @@ -88,7 +88,7 @@ static int InitLinuxKeybord(void) } if ((keyboard.dev_fd = open(keyboard.dev_path, O_RDONLY | O_NONBLOCK)) < 0) { - Logger_Error("[input] open keyboard device failed"); + logger_error("[input] open keyboard device failed"); return -1; } LCUIThread_Create(&keyboard.tid, LinuxKeybnoardThread, NULL); @@ -249,7 +249,7 @@ static int InitLinuxKeybord(void) } keyboard.active = TRUE; LCUIThread_Create(&keyboard.tid, LinuxKeybnoardThread, NULL); - Logger_Debug("[input] keyboard driver thread: %lld\n", keyboard.tid); + logger_debug("[input] keyboard driver thread: %lld\n", keyboard.tid); return 0; } diff --git a/lib/platform/src/linux/linux_mouse.c b/lib/platform/src/linux/linux_mouse.c index b438df9e..14f263d4 100644 --- a/lib/platform/src/linux/linux_mouse.c +++ b/lib/platform/src/linux/linux_mouse.c @@ -94,10 +94,10 @@ static void DispatchMouseEvent(void *arg1, void *arg2) mouse.x += buf[1]; mouse.y -= buf[2]; - mouse.x = max(0, mouse.x); - mouse.y = max(0, mouse.y); - mouse.x = min(LCUIDisplay_GetWidth(), mouse.x); - mouse.y = min(LCUIDisplay_GetHeight(), mouse.y); + mouse.x = y_max(0, mouse.x); + mouse.y = y_max(0, mouse.y); + mouse.x = y_min(LCUIDisplay_GetWidth(), mouse.x); + mouse.y = y_min(LCUIDisplay_GetHeight(), mouse.y); ev.type = LCUI_MOUSEMOVE; ev.motion.x = mouse.x; ev.motion.y = mouse.y; @@ -149,13 +149,13 @@ static int InitLinuxMouse(void) if (!mouse.dev_path) { mouse.dev_path = "/dev/input/mice"; } - Logger_Debug("[input] open mouse device: %s\n", mouse.dev_path); + logger_debug("[input] open mouse device: %s\n", mouse.dev_path); if ((mouse.dev_fd = open(mouse.dev_path, O_RDONLY)) < 0) { - Logger_Error("[input] open mouse device failed\n"); + logger_error("[input] open mouse device failed\n"); return -1; } LCUIThread_Create(&mouse.tid, LinuxMouseThread, NULL); - Logger_Debug("[input] mouse driver thread: %lld\n", mouse.tid); + logger_debug("[input] mouse driver thread: %lld\n", mouse.tid); return 0; } diff --git a/lib/platform/src/linux/linux_x11display.c b/lib/platform/src/linux/linux_x11display.c index 2de93d12..9322dd7f 100644 --- a/lib/platform/src/linux/linux_x11display.c +++ b/lib/platform/src/linux/linux_x11display.c @@ -81,13 +81,13 @@ typedef struct LCUI_SurfaceRec_ { LCUI_Graph fb; /**< 帧缓存,它里面的数据会映射到窗口中 */ LCUI_Mutex mutex; /**< 互斥锁 */ LCUI_SurfaceTasks tasks; - LinkedList rects; /**< 列表,记录当前需要重绘的区域 */ - LinkedListNode node; /**< 在表面列表中的结点 */ + list_t rects; /**< 列表,记录当前需要重绘的区域 */ + list_node_t node; /**< 在表面列表中的结点 */ } LCUI_SurfaceRec; static struct X11_Display { LCUI_BOOL is_inited; /**< 标记,标识当前模块是否已经初始化 */ - LinkedList surfaces; /**< 表面列表 */ + list_t surfaces; /**< 表面列表 */ LCUI_X11AppDriver app; /**< X11 应用驱动 */ LCUI_EventTrigger trigger; /**< 事件触发器 */ } x11 = { 0 }; @@ -110,8 +110,8 @@ static void X11Surface_ReleaseTask(LCUI_Surface surface, int type) static LCUI_Surface GetSurfaceByWindow(Window win) { - LinkedListNode *node; - LinkedList_ForEach(node, &x11.surfaces) + list_node_t *node; + for(list_each(node, &x11.surfaces)) { if (((LCUI_Surface)node->data)->window == win) { return node->data; @@ -146,7 +146,7 @@ static void X11Surface_OnResize(LCUI_Surface s, int width, int height) s->fb.color_type = LCUI_COLOR_TYPE_ARGB; break; default: - Logger_Error("[x11display] unsupport depth: %d.\n", depth); + logger_error("[x11display] unsupport depth: %d.\n", depth); break; } Graph_Create(&s->fb, width, height); @@ -155,14 +155,14 @@ static void X11Surface_OnResize(LCUI_Surface s, int width, int height) (char *)(s->fb.bytes), width, height, 32, 0); if (!s->ximage) { Graph_Free(&s->fb); - Logger_Error("[x11display] create XImage faild.\n"); + logger_error("[x11display] create XImage faild.\n"); return; } gcv.graphics_exposures = False; s->gc = XCreateGC(x11.app->display, s->window, GCGraphicsExposures, &gcv); if (!s->gc) { - Logger_Error("[x11display] create graphics context faild.\n"); + logger_error("[x11display] create graphics context faild.\n"); return; } } @@ -204,7 +204,7 @@ static void X11Surface_RunTask(LCUI_Surface surface, int type) break; } case TASK_DELETE: - LinkedList_Unlink(&x11.surfaces, &surface->node); + list_unlink(&x11.surfaces, &surface->node); default: break; } @@ -240,7 +240,7 @@ static void OnDestroySurface(void *data) LCUI_Surface s = data; X11Surface_ClearTasks(s); - LinkedList_Clear(&s->rects, free); + list_destroy(&s->rects, free); if (s->ximage) { XDestroyImage(s->ximage); } @@ -275,9 +275,9 @@ static LCUI_Surface X11Surface_New(void) surface->height = MIN_HEIGHT; Graph_Init(&surface->fb); LCUIMutex_Init(&surface->mutex); - LinkedList_Init(&surface->rects); + list_create(&surface->rects); surface->fb.color_type = LCUI_COLOR_TYPE_ARGB; - LinkedList_AppendNode(&x11.surfaces, &surface->node); + list_append_node(&x11.surfaces, &surface->node); LCUI_PostSimpleTask(X11Surface_OnCreate, surface, NULL); return surface; } @@ -311,12 +311,12 @@ static void X11Surface_SetCaptionW(LCUI_Surface surface, const wchar_t *wstr) task = &surface->tasks[TASK_SET_CAPTION]; X11Surface_ReleaseTask(surface, TASK_SET_CAPTION); if (wstr) { - len = LCUI_EncodeString(NULL, wstr, 0, ENCODING_UTF8) + 1; + len = encode_string(NULL, wstr, 0, ENCODING_UTF8) + 1; caption = malloc(sizeof(char) * len); if (!caption) { return; } - len = LCUI_EncodeString(caption, wstr, len, ENCODING_UTF8); + len = encode_string(caption, wstr, len, ENCODING_UTF8); task->caption = caption; task->caption[len] = 0; task->caption_len = len; @@ -357,7 +357,7 @@ static void X11Surface_EndPaint(LCUI_Surface surface, LCUI_PaintContext paint) LCUI_Rect *r; r = NEW(LCUI_Rect, 1); *r = paint->rect; - LinkedList_Append(&surface->rects, r); + list_append(&surface->rects, r); free(paint); LCUIMutex_Unlock(&surface->mutex); } @@ -365,15 +365,15 @@ static void X11Surface_EndPaint(LCUI_Surface surface, LCUI_PaintContext paint) /** 将帧缓存中的数据呈现至Surface的窗口内 */ static void X11Surface_Present(LCUI_Surface surface) { - LinkedListNode *node; + list_node_t *node; LCUIMutex_Lock(&surface->mutex); - for (LinkedList_Each(node, &surface->rects)) { + for (list_each(node, &surface->rects)) { LCUI_Rect *rect = node->data; XPutImage(x11.app->display, surface->window, surface->gc, surface->ximage, rect->x, rect->y, rect->x, rect->y, rect->width, rect->height); } - LinkedList_Clear(&surface->rects, free); + list_destroy(&surface->rects, free); LCUIMutex_Unlock(&surface->mutex); } @@ -490,7 +490,7 @@ LCUI_DisplayDriver LCUI_CreateLinuxX11DisplayDriver(void) driver->bindEvent = X11Display_BindEvent; driver->getSurfaceWidth = X11Surface_GetWidth; driver->getSurfaceHeight = X11Surface_GetHeight; - LinkedList_Init(&x11.surfaces); + list_create(&x11.surfaces); LCUI_BindSysEvent(Expose, OnExpose, NULL, NULL); LCUI_BindSysEvent(ConfigureNotify, OnConfigureNotify, NULL, NULL); x11.trigger = EventTrigger(); @@ -501,7 +501,7 @@ LCUI_DisplayDriver LCUI_CreateLinuxX11DisplayDriver(void) void LCUI_DestroyLinuxX11DisplayDriver(LCUI_DisplayDriver driver) { EventTrigger_Destroy(x11.trigger); - LinkedList_ClearData(&x11.surfaces, OnDestroySurface); + list_destroy_without_node(&x11.surfaces, OnDestroySurface); LCUI_UnbindSysEvent(ConfigureNotify, OnConfigureNotify); LCUI_UnbindSysEvent(Expose, OnExpose); x11.trigger = NULL; diff --git a/lib/platform/src/steptimer.c b/lib/platform/src/steptimer.c index bdc4ec67..90564630 100644 --- a/lib/platform/src/steptimer.c +++ b/lib/platform/src/steptimer.c @@ -61,8 +61,8 @@ StepTimer StepTimer_Create(void) timer->current_fps = 0; timer->pause_time = 0; timer->one_frame_remain_time = 10; - timer->prev_frame_start_time = LCUI_GetTime(); - timer->prev_fps_update_time = LCUI_GetTime(); + timer->prev_frame_start_time = get_time_ms(); + timer->prev_fps_update_time = get_time_ms(); LCUICond_Init(&timer->cond); LCUIMutex_Init(&timer->mutex); return timer; @@ -94,7 +94,7 @@ void StepTimer_Remain(StepTimer timer) return; } lost_ms = 0; - current_time = LCUI_GetTime(); + current_time = get_time_ms(); LCUIMutex_Lock(&timer->mutex); n_ms = (unsigned int)(current_time - timer->prev_frame_start_time); if (n_ms > timer->one_frame_remain_time) { @@ -107,16 +107,16 @@ void StepTimer_Remain(StepTimer timer) /* 睡眠一段时间 */ while (lost_ms < n_ms && timer->state == STATE_RUN) { LCUICond_TimedWait(&timer->cond, &timer->mutex, n_ms - lost_ms); - lost_ms = (unsigned int)LCUI_GetTimeDelta(current_time); + lost_ms = (unsigned int)get_time_delta(current_time); } /* 睡眠结束后,如果当前状态为 PAUSE,则说明睡眠是因为要暂停而终止的 */ if (timer->state == STATE_PAUSE) { - current_time = LCUI_GetTime(); + current_time = get_time_ms(); /* 等待状态改为“继续” */ while (timer->state == STATE_PAUSE) { LCUICond_Wait(&timer->cond, &timer->mutex); } - lost_ms = (unsigned int)LCUI_GetTimeDelta(current_time); + lost_ms = (unsigned int)get_time_delta(current_time); timer->pause_time = lost_ms; timer->prev_frame_start_time += lost_ms; LCUIMutex_Unlock(&timer->mutex); @@ -124,7 +124,7 @@ void StepTimer_Remain(StepTimer timer) } normal_exit:; - current_time = LCUI_GetTime(); + current_time = get_time_ms(); if (current_time - timer->prev_fps_update_time >= 1000) { timer->current_fps = timer->temp_fps; timer->prev_fps_update_time = current_time; diff --git a/lib/platform/src/uwp/uwp_input.cpp b/lib/platform/src/uwp/uwp_input.cpp index ca83727f..7d8356a1 100644 --- a/lib/platform/src/uwp/uwp_input.cpp +++ b/lib/platform/src/uwp/uwp_input.cpp @@ -42,12 +42,12 @@ using namespace Windows::Devices::Input; using namespace Windows::Foundation; using namespace Windows::System; -static LCUI_TouchPoint AddTouchPoint(LinkedList *points, +static LCUI_TouchPoint AddTouchPoint(list_t *points, PointerPoint^ point, int state) { - LinkedListNode *node; + list_node_t *node; LCUI_TouchPoint tp = NULL; - for (LinkedList_Each(node, points)) { + for (list_each(node, points)) { tp = (LCUI_TouchPoint)node->data; if (tp->id == point->PointerId) { break; @@ -59,36 +59,36 @@ static LCUI_TouchPoint AddTouchPoint(LinkedList *points, tp->id = point->PointerId; /* 将第一个触点作为主触点 */ tp->is_primary = points->length == 0; - LinkedList_Append(points, tp); + list_append(points, tp); } tp->state = state; - tp->x = iround(point->Position.X); - tp->y = iround(point->Position.Y); + tp->x = y_iround(point->Position.X); + tp->y = y_iround(point->Position.Y); return tp; } -static void ClearInvalidTouchPoints(LinkedList *points) +static void ClearInvalidTouchPoints(list_t *points) { LCUI_TouchPoint tp; - LinkedListNode *node, *next; + list_node_t *node, *next; node = points->head.next; while (node) { next = node->next; tp = (LCUI_TouchPoint)node->data; if (tp->state == LCUI_TOUCHUP) { - LinkedList_DeleteNode(points, node); + list_delete_node(points, node); } node = next; } } -static int CreateTouchEvent(LCUI_SysEvent e, LinkedList *points) +static int CreateTouchEvent(LCUI_SysEvent e, list_t *points) { int i = 0; - LinkedListNode *node; + list_node_t *node; LCUI_TouchPoint list; list = NEW(LCUI_TouchPointRec, points->length); - for (LinkedList_Each(node, points)) { + for (list_each(node, points)) { list[i++] = *(LCUI_TouchPoint)node->data; } return LCUI_CreateTouchEvent(e, list, (int)points->length); @@ -99,7 +99,7 @@ InputDriver::InputDriver() m_mouse.actived = false; m_mouse.leftButtonPressed = false; m_mouse.rightButtonPressed = false; - LinkedList_Init(&m_touch.points); + list_create(&m_touch.points); } void InputDriver::OnPointerPressed(CoreWindow^ sender, @@ -141,8 +141,8 @@ void InputDriver::OnPointerPressed(CoreWindow^ sender, m_mouse.position = position; } ev.type = LCUI_MOUSEDOWN; - pos.x = iround(position.X); - pos.y = iround(position.Y); + pos.x = y_iround(position.X); + pos.y = y_iround(position.Y); ev.button.x = pos.x; ev.button.y = pos.y; LCUICursor_SetPos(pos); @@ -176,13 +176,13 @@ void InputDriver::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args) m_mouse.actived = true; m_mouse.position = position; } - pos.x = iround(position.X); - pos.y = iround(position.Y); + pos.x = y_iround(position.X); + pos.y = y_iround(position.Y); ev.type = LCUI_MOUSEMOVE; ev.motion.x = pos.x; ev.motion.y = pos.y; - ev.motion.xrel = iround(position.X - m_mouse.position.Y); - ev.motion.yrel = iround(position.Y - m_mouse.position.Y); + ev.motion.xrel = y_iround(position.X - m_mouse.position.Y); + ev.motion.yrel = y_iround(position.Y - m_mouse.position.Y); m_mouse.position = position; LCUI_TriggerEvent(&ev, NULL); LCUI_DestroyEvent(&ev); @@ -225,8 +225,8 @@ void InputDriver::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args) default:return; } ev.type = LCUI_MOUSEUP; - pos.x = iround(position.X); - pos.y = iround(position.Y); + pos.x = y_iround(position.X); + pos.y = y_iround(position.Y); ev.button.x = pos.x; ev.button.y = pos.y; LCUI_TriggerEvent(&ev, NULL); diff --git a/lib/platform/src/uwp/uwp_input.h b/lib/platform/src/uwp/uwp_input.h index c20ccda7..4a35fbe7 100644 --- a/lib/platform/src/uwp/uwp_input.h +++ b/lib/platform/src/uwp/uwp_input.h @@ -54,7 +54,7 @@ namespace LCUICore { Windows::Foundation::Point position; } m_mouse; struct { - LinkedList points; + list_t points; } m_touch; }; } diff --git a/lib/platform/src/windows/windows_display.c b/lib/platform/src/windows/windows_display.c index 5384ee7d..81cd4c41 100644 --- a/lib/platform/src/windows/windows_display.c +++ b/lib/platform/src/windows/windows_display.c @@ -81,13 +81,13 @@ struct LCUI_SurfaceRec_ { LCUI_BOOL is_ready; /**< 是否已经准备好 */ LCUI_Graph fb; /**< 帧缓存,保存当前窗口内呈现的图像内容 */ LCUI_SurfaceTask tasks[TASK_TOTAL_NUM]; /**< 任务缓存 */ - LinkedListNode node; /**< 在链表中的结点 */ + list_node_t node; /**< 在链表中的结点 */ }; /** windows 下图形显示功能所需的数据 */ static struct WIN_Display { LCUI_BOOL active; /**< 是否已经初始化 */ - LinkedList surfaces; /**< surface 记录 */ + list_t surfaces; /**< surface 记录 */ LCUI_EventTrigger trigger; /**< 事件触发器 */ } win; @@ -96,8 +96,8 @@ static struct WIN_Display { /** 根据 hwnd 获取 Surface */ static LCUI_Surface GetSurfaceByHWND(HWND hwnd) { - LinkedListNode *node; - for (LinkedList_Each(node, &win.surfaces)) { + list_node_t *node; + for (list_each(node, &win.surfaces)) { if (((LCUI_Surface)node->data)->hwnd == hwnd) { return node->data; } @@ -146,7 +146,7 @@ static void WinSurface_ExecDestroy(LCUI_Surface surface) static void WinSurface_Destroy(LCUI_Surface surface) { - LinkedList_Unlink(&win.surfaces, &surface->node); + list_unlink(&win.surfaces, &surface->node); WinSurface_ExecDestroy(surface); } @@ -204,7 +204,7 @@ static LCUI_Surface WinSurface_New(void) for (i = 0; i < TASK_TOTAL_NUM; ++i) { surface->tasks[i].is_valid = FALSE; } - LinkedList_AppendNode(&win.surfaces, &surface->node); + list_append_node(&win.surfaces, &surface->node); LCUI_PostSimpleTask(OnCreateSurface, surface, NULL); return surface; } @@ -565,7 +565,7 @@ LCUI_DisplayDriver LCUI_CreateWinDisplay(void) LCUI_BindSysEvent(WM_SIZE, OnWMSize, NULL, NULL); LCUI_BindSysEvent(WM_PAINT, OnWMPaint, NULL, NULL); LCUI_BindSysEvent(WM_GETMINMAXINFO, OnWMGetMinMaxInfo, NULL, NULL); - LinkedList_Init(&win.surfaces); + list_create(&win.surfaces); win.trigger = EventTrigger(); win.active = TRUE; return driver; @@ -577,7 +577,7 @@ void LCUI_DestroyWinDisplay(LCUI_DisplayDriver driver) LCUI_UnbindSysEvent(WM_SIZE, OnWMSize); LCUI_UnbindSysEvent(WM_PAINT, OnWMPaint); LCUI_UnbindSysEvent(WM_GETMINMAXINFO, OnWMGetMinMaxInfo); - LinkedList_ClearData(&win.surfaces, WinSurface_OnDestroy); + list_destroy_without_node(&win.surfaces, WinSurface_OnDestroy); EventTrigger_Destroy(win.trigger); free(driver); } diff --git a/lib/platform/src/windows/windows_ime.c b/lib/platform/src/windows/windows_ime.c index 4a6cd376..09df69a0 100644 --- a/lib/platform/src/windows/windows_ime.c +++ b/lib/platform/src/windows/windows_ime.c @@ -36,6 +36,7 @@ #include #include #include +#include #include #include LCUI_EVENTS_H diff --git a/lib/platform/src/windows/windows_keyboard.c b/lib/platform/src/windows/windows_keyboard.c index f04598f0..95577d1c 100644 --- a/lib/platform/src/windows/windows_keyboard.c +++ b/lib/platform/src/windows/windows_keyboard.c @@ -31,6 +31,7 @@ #include #ifdef LCUI_BUILD_IN_WIN32 #include +#include #include #include LCUI_EVENTS_H #include LCUI_KEYBOARD_H diff --git a/lib/platform/src/windows/windows_mouse.c b/lib/platform/src/windows/windows_mouse.c index b884a1d2..6f3eb243 100644 --- a/lib/platform/src/windows/windows_mouse.c +++ b/lib/platform/src/windows/windows_mouse.c @@ -31,6 +31,7 @@ #include "config.h" #include #ifdef LCUI_BUILD_IN_WIN32 +#include #include #include #include diff --git a/lib/text/src/textlayer.c b/lib/text/src/textlayer.c index 1e1b6134..b455ce28 100644 --- a/lib/text/src/textlayer.c +++ b/lib/text/src/textlayer.c @@ -32,8 +32,7 @@ #include #include #include -#include -#include +#include #include #include #include @@ -44,7 +43,7 @@ typedef enum { TEXT_ACTION_INSERT, TEXT_ACTION_APPEND } TextAction; TextRowList_InsertNewRow(ROWLIST, (ROWLIST)->length) #define TextLayer_GetRow(layer, n) \ (n >= layer->text_rows.length) ? NULL : layer->text_rows.rows[n] -#define GetDefaultLineHeight(H) iround(H * 1.42857143) +#define GetDefaultLineHeight(H) y_iround(H * 1.42857143) #define ISALPHA(CH) (CH >= 'a' && CH <= 'z') || (CH >= 'A' && CH <= 'Z') /* 根据对齐方式,计算文本行的起始X轴位置 */ @@ -299,12 +298,12 @@ LCUI_TextLayer TextLayer_New(void) layer->enable_style_tag = FALSE; layer->word_break = LCUI_WORD_BREAK_NORMAL; TextStyle_Init(&layer->text_default_style); - LinkedList_Init(&layer->text_styles); + list_create(&layer->text_styles); layer->task.typeset_start_row = 0; layer->task.update_typeset = 0; layer->task.update_bitmap = 0; layer->task.redraw_all = 0; - LinkedList_Init(&layer->dirty_rects); + list_create(&layer->dirty_rects); TextRowList_InsertNewRow(&layer->text_rows, 0); return layer; } @@ -332,7 +331,7 @@ static void OnDestroyTextStyle(void *data) static void TextLayer_DestroyStyleCache(LCUI_TextLayer layer) { - LinkedList_Clear(&layer->text_styles, OnDestroyTextStyle); + list_destroy(&layer->text_styles, OnDestroyTextStyle); } /** 销毁TextLayer */ @@ -664,7 +663,7 @@ static void TextLayer_TextTypeset(LCUI_TextLayer layer, int start_row) static const wchar_t *TextLayer_ProcessStyleTag(LCUI_TextLayer layer, const wchar_t *p, - LinkedList *tags, + list_t *tags, LCUI_TextStyle *style) { LCUI_TextStyle s; @@ -674,7 +673,7 @@ static const wchar_t *TextLayer_ProcessStyleTag(LCUI_TextLayer layer, s = StyleTags_GetTextStyle(tags); if (s) { TextStyle_Merge(s, &layer->text_default_style); - LinkedList_Append(&layer->text_styles, s); + list_append(&layer->text_styles, s); } *style = s; return pp; @@ -684,7 +683,7 @@ static const wchar_t *TextLayer_ProcessStyleTag(LCUI_TextLayer layer, s = StyleTags_GetTextStyle(tags); if (s) { TextStyle_Merge(s, &layer->text_default_style); - LinkedList_Append(&layer->text_styles, s); + list_append(&layer->text_styles, s); } *style = s; return pp; @@ -694,12 +693,12 @@ static const wchar_t *TextLayer_ProcessStyleTag(LCUI_TextLayer layer, /** 对文本进行预处理 */ static int TextLayer_ProcessText(LCUI_TextLayer layer, const wchar_t *wstr, - TextAction action, LinkedList *tags) + TextAction action, list_t *tags) { LCUI_EOLChar eol; LCUI_TextRow txtrow; LCUI_TextCharRec txtchar; - LinkedList tmp_tags; + list_t tmp_tags; const wchar_t *p; int cur_col, cur_row, start_row, ins_x, ins_y; LCUI_BOOL need_typeset, rect_has_added; @@ -765,7 +764,7 @@ static int TextLayer_ProcessText(LCUI_TextLayer layer, const wchar_t *wstr, } /* 将当前行中的插入点为截点,进行断行 */ TextLayer_BreakTextRow(layer, ins_y, ins_x, eol); - layer->width = max(layer->width, txtrow->width); + layer->width = y_max(layer->width, txtrow->width); need_typeset = TRUE; ++layer->length; ins_x = 0; @@ -782,7 +781,7 @@ static int TextLayer_ProcessText(LCUI_TextLayer layer, const wchar_t *wstr, } /* 更新当前行的尺寸 */ TextLayer_UpdateRowSize(layer, txtrow); - layer->width = max(layer->width, txtrow->width); + layer->width = y_max(layer->width, txtrow->width); if (action == TEXT_ACTION_INSERT) { layer->insert_x = ins_x; layer->insert_y = ins_y; @@ -804,7 +803,7 @@ static int TextLayer_ProcessText(LCUI_TextLayer layer, const wchar_t *wstr, /** 插入文本内容(宽字符版) */ int TextLayer_InsertTextW(LCUI_TextLayer layer, const wchar_t *wstr, - LinkedList *tags) + list_t *tags) { return TextLayer_ProcessText(layer, wstr, TEXT_ACTION_INSERT, tags); } @@ -823,7 +822,7 @@ int TextLayer_InsertText(LCUI_TextLayer layer, const char *utf8_str) /** 追加文本内容(宽字符版) */ int TextLayer_AppendTextW(LCUI_TextLayer layer, const wchar_t *wstr, - LinkedList *tag_stack) + list_t *tag_stack) { return TextLayer_ProcessText(layer, wstr, TEXT_ACTION_APPEND, tag_stack); @@ -843,7 +842,7 @@ int TextLayer_AppendText(LCUI_TextLayer layer, const char *utf8_text) /** 设置文本内容(宽字符版) */ int TextLayer_SetTextW(LCUI_TextLayer layer, const wchar_t *wstr, - LinkedList *tag_stack) + list_t *tag_stack) { TextLayer_ClearText(layer); return TextLayer_AppendTextW(layer, wstr, tag_stack); @@ -1166,12 +1165,12 @@ void TextLayer_EnableStyleTag(LCUI_TextLayer layer, LCUI_BOOL enable) static void TextLayer_UpdateTextStyleCache(LCUI_TextLayer layer) { - LinkedListNode *node; + list_node_t *node; if (!layer->text_default_style.has_family) { TextStyle_SetDefaultFont(&layer->text_default_style); } /* 替换缺省字体,确保能够正确应用字体设置 */ - for (LinkedList_Each(node, &layer->text_styles)) { + for (list_each(node, &layer->text_styles)) { TextStyle_Merge(node->data, &layer->text_default_style); } } @@ -1192,7 +1191,7 @@ void TextLayer_ReloadCharBitmap(LCUI_TextLayer layer) } } -void TextLayer_Update(LCUI_TextLayer layer, LinkedList *rects) +void TextLayer_Update(LCUI_TextLayer layer, list_t *rects) { if (layer->task.update_bitmap) { TextLayer_InvalidateRowsRect(layer, 0, -1); @@ -1217,7 +1216,7 @@ void TextLayer_Update(LCUI_TextLayer layer, LinkedList *rects) layer->task.redraw_all = TRUE; } if (rects) { - LinkedList_Concat(rects, &layer->dirty_rects); + list_concat(rects, &layer->dirty_rects); } } diff --git a/lib/text/src/textstyle.c b/lib/text/src/textstyle.c index 39e51d49..3ea4ceea 100644 --- a/lib/text/src/textstyle.c +++ b/lib/text/src/textstyle.c @@ -33,9 +33,8 @@ #include #include #include -#include +#include #include -#include #include typedef enum LCUI_TextStyleTagType_ { @@ -213,16 +212,16 @@ int TextStyle_SetDefaultFont(LCUI_TextStyle ts) /*-------------------------- StyleTag --------------------------------*/ -void StyleTags_Clear(LinkedList *tags) +void StyleTags_Clear(list_t *tags) { - LinkedList_Clear(tags, free); + list_destroy(tags, free); } /** 获取当前的文本样式 */ -LCUI_TextStyle StyleTags_GetTextStyle(LinkedList *tags) +LCUI_TextStyle StyleTags_GetTextStyle(list_t *tags) { int count = 0; - LinkedListNode *node; + list_node_t *node; LCUI_TextStyleTag *tag; LCUI_TextStyle style; LCUI_BOOL found_tags[TEXT_STYLE_TOTAL_NUM] = { 0 }; @@ -233,7 +232,7 @@ LCUI_TextStyle StyleTags_GetTextStyle(LinkedList *tags) style = malloc(sizeof(LCUI_TextStyleRec)); TextStyle_Init(style); /* 根据已经记录的各种样式,生成当前应有的文本样式 */ - for (LinkedList_EachReverse(node, tags)) { + for (list_each_reverse(node, tags)) { tag = node->data; switch (tag->id) { case TEXT_STYLE_COLOR: @@ -275,7 +274,7 @@ LCUI_TextStyle StyleTags_GetTextStyle(LinkedList *tags) break; } style->has_pixel_size = TRUE; - style->pixel_size = iround(tag->style.px); + style->pixel_size = y_iround(tag->style.px); found_tags[tag->id] = TRUE; ++count; break; @@ -293,19 +292,19 @@ LCUI_TextStyle StyleTags_GetTextStyle(LinkedList *tags) } /** 将指定标签的样式数据从队列中删除,只删除队列尾部第一个匹配的标签 */ -static void StyleTags_Delete(LinkedList *tags, int id) +static void StyleTags_Delete(list_t *tags, int id) { LCUI_TextStyleTag *tag; - LinkedListNode *node; + list_node_t *node; DEBUG_MSG("delete start, total tag: %d\n", total); if (tags->length <= 0) { return; } - for (LinkedList_Each(node, tags)) { + for (list_each(node, tags)) { tag = node->data; if (tag->id == id) { free(tag); - LinkedList_DeleteNode(tags, node); + list_delete_node(tags, node); break; } } @@ -523,14 +522,14 @@ static const wchar_t *ScanStyleTagData(const wchar_t *wstr, } /** 处理样式标签 */ -const wchar_t *StyleTags_GetStart(LinkedList *tags, const wchar_t *str) +const wchar_t *StyleTags_GetStart(list_t *tags, const wchar_t *str) { const wchar_t *q; LCUI_TextStyleTag *tag = NEW(LCUI_TextStyleTag, 1); q = ScanStyleTagData(str, tag); if (q) { /* 将标签样式数据加入队列 */ - LinkedList_Insert(tags, 0, tag); + list_insert(tags, 0, tag); } else { free(tag); } @@ -538,7 +537,7 @@ const wchar_t *StyleTags_GetStart(LinkedList *tags, const wchar_t *str) } /** 处理样式结束标签 */ -const wchar_t* StyleTags_GetEnd(LinkedList *tags, const wchar_t *str) +const wchar_t* StyleTags_GetEnd(list_t *tags, const wchar_t *str) { const wchar_t *p; wchar_t tagname[256]; diff --git a/lib/thread/src/pthread/thread.c b/lib/thread/src/pthread/thread.c index 578f6c5f..12f30a65 100644 --- a/lib/thread/src/pthread/thread.c +++ b/lib/thread/src/pthread/thread.c @@ -36,13 +36,13 @@ typedef struct LCUI_ThreadContextRec { void (*func)(void *); void *arg; LCUI_Thread tid; - LinkedListNode node; + list_node_t node; } LCUI_ThreadContextRec, *LCUI_ThreadContext; static struct LCUIThreadModule { LCUI_BOOL is_inited; LCUI_Mutex mutex; - LinkedList threads; + list_t threads; } self; static void *LCUIThread_Run(void *arg) @@ -50,7 +50,7 @@ static void *LCUIThread_Run(void *arg) LCUI_ThreadContext ctx = arg; ctx->func(ctx->arg); LCUIMutex_Lock(&self.mutex); - LinkedList_Unlink(&self.threads, &ctx->node); + list_unlink(&self.threads, &ctx->node); LCUIMutex_Unlock(&self.mutex); free(ctx); pthread_exit(NULL); @@ -58,9 +58,9 @@ static void *LCUIThread_Run(void *arg) static LCUI_ThreadContext LCUIThread_Find(LCUI_Thread tid) { - LinkedListNode *node; + list_node_t *node; LCUI_ThreadContext ctx; - for (LinkedList_Each(node, &self.threads)) { + for (list_each(node, &self.threads)) { ctx = node->data; if (ctx && ctx->tid == tid) { return ctx; @@ -75,7 +75,7 @@ static LCUI_ThreadContext LCUIThread_Get(LCUI_Thread tid) LCUIMutex_Lock(&self.mutex); ctx = LCUIThread_Find(tid); if (ctx) { - LinkedList_Unlink(&self.threads, &ctx->node); + list_unlink(&self.threads, &ctx->node); } LCUIMutex_Unlock(&self.mutex); return ctx; @@ -86,7 +86,7 @@ int LCUIThread_Create(LCUI_Thread *thread, void (*func)(void *), void *arg) int ret; LCUI_ThreadContext ctx; if (!self.is_inited) { - LinkedList_Init(&self.threads); + list_create(&self.threads); LCUIMutex_Init(&self.mutex); self.is_inited = TRUE; } @@ -103,7 +103,7 @@ int LCUIThread_Create(LCUI_Thread *thread, void (*func)(void *), void *arg) return ret; } LCUIMutex_Lock(&self.mutex); - LinkedList_AppendNode(&self.threads, &ctx->node); + list_append_node(&self.threads, &ctx->node); LCUIMutex_Unlock(&self.mutex); *thread = ctx->tid; return ret; diff --git a/lib/thread/src/windows/thread.c b/lib/thread/src/windows/thread.c index c9056d2c..6dd0db05 100644 --- a/lib/thread/src/windows/thread.c +++ b/lib/thread/src/windows/thread.c @@ -39,13 +39,13 @@ typedef struct _LCUI_ThreadContextRec_ { void *arg; void *retval; LCUI_BOOL has_waiter; - LinkedListNode node; + list_node_t node; } LCUI_ThreadContextRec, *LCUI_ThreadContext; static struct LCUIThreadModule { LCUI_BOOL active; LCUI_Mutex mutex; - LinkedList threads; + list_t threads; } self; static unsigned __stdcall run_thread(void *arg) @@ -62,7 +62,7 @@ int LCUIThread_Create(LCUI_Thread *tid, void(*func)(void*), void *arg) LCUI_ThreadContext ctx; if (!self.active) { - LinkedList_Init(&self.threads); + list_create(&self.threads); LCUIMutex_Init(&self.mutex); self.active = TRUE; } @@ -81,7 +81,7 @@ int LCUIThread_Create(LCUI_Thread *tid, void(*func)(void*), void *arg) return -1; } LCUIMutex_Lock(&self.mutex); - LinkedList_AppendNode(&self.threads, &ctx->node); + list_append_node(&self.threads, &ctx->node); LCUIMutex_Unlock(&self.mutex); *tid = ctx->tid; return 0; @@ -89,10 +89,10 @@ int LCUIThread_Create(LCUI_Thread *tid, void(*func)(void*), void *arg) static LCUI_ThreadContext LCUIThread_Find(LCUI_Thread tid) { - LinkedListNode *node; + list_node_t *node; LCUI_ThreadContext ctx; - for (LinkedList_Each(node, &self.threads)) { + for (list_each(node, &self.threads)) { ctx = node->data; if (ctx && ctx->tid == tid) { return ctx; @@ -108,7 +108,7 @@ static LCUI_ThreadContext LCUIThread_Get(LCUI_Thread tid) LCUIMutex_Lock(&self.mutex); ctx = LCUIThread_Find(tid); if (ctx) { - LinkedList_Unlink(&self.threads, &ctx->node); + list_unlink(&self.threads, &ctx->node); } LCUIMutex_Unlock(&self.mutex); return ctx; diff --git a/lib/timer/src/timer.c b/lib/timer/src/timer.c index 6f20e51b..04be046c 100644 --- a/lib/timer/src/timer.c +++ b/lib/timer/src/timer.c @@ -33,235 +33,82 @@ #include #include #include - -#define STATE_RUN 1 -#define STATE_PAUSE 0 +#include /*----------------------------- Timer --------------------------------*/ -typedef struct TimerRec_ { - int state; /**< 状态 */ - long int id; /**< 定时器ID */ - LCUI_BOOL reuse; /**< 是否重复使用该定时器 */ - - int64_t start_time; /**< 定时器启动时的时间 */ - int64_t pause_time; /**< 定时器暂停时的时间 */ - long int total_ms; /**< 定时时间(单位:毫秒) */ - long int pause_ms; /**< 定时器处于暂停状态的时长(单位:毫秒) */ - - void (*callback)(void *); /**< 回调函数 */ - void *arg; /**< 函数的参数 */ - - LinkedListNode node; /**< 位于定时器列表中的节点 */ -} TimerRec, *Timer; - -static struct TimerModule { - int id_count; /**< 定时器ID计数 */ - LCUI_BOOL active; /**< 定时器线程是否正在运行 */ - LCUI_Mutex mutex; /**< 定时器记录操作互斥锁 */ - LinkedList timers; /**< 定时器数据记录 */ -} self; +static timer_list_t* main_timer_list = NULL; +static LCUI_Mutex mutex; /**< 定时器记录操作互斥锁 */ /*----------------------------- Private ------------------------------*/ -/** 更新定时器在定时器列表中的位置 */ -static void TimerList_AddNode(LinkedListNode *node) +int lcui_destroy_timer(int timer_id) { - Timer timer; - int64_t t, tt; - LinkedListNode *cur; - /* 计算该定时器的剩余定时时长 */ - timer = node->data; - t = LCUI_GetTimeDelta(timer->start_time); - t = timer->total_ms - t + timer->pause_ms; - for (LinkedList_Each(cur, &self.timers)) { - timer = cur->data; - tt = LCUI_GetTimeDelta(timer->start_time); - tt = timer->total_ms - tt + timer->pause_ms; - if (t <= tt) { - LinkedList_Link(&self.timers, cur->prev, node); - return; - } - } - LinkedList_AppendNode(&self.timers, node); + int ret; + LCUIMutex_Lock(&mutex); + ret = timer_destroy(main_timer_list, timer_id); + LCUIMutex_Unlock(&mutex); + return ret; } -static Timer FindTimer(int timer_id) +int lcui_pause_timer(int timer_id) { - Timer timer; - LinkedListNode *node; - for (LinkedList_Each(node, &self.timers)) { - timer = node->data; - if (timer && timer->id == timer_id) { - return timer; - } - } - return NULL; + int ret; + LCUIMutex_Lock(&mutex); + ret = timer_pause(main_timer_list, timer_id); + LCUIMutex_Unlock(&mutex); + return ret; } -int LCUITimer_Set(long int n_ms, void(*func)(void *), void *arg, - LCUI_BOOL reuse) +int lcui_continue_timer(int timer_id) { - Timer timer; - if (!self.active) { - return -1; - } - LCUIMutex_Lock(&self.mutex); - timer = malloc(sizeof(TimerRec)); - timer->arg = arg; - timer->callback = func; - timer->reuse = reuse; - timer->pause_ms = 0; - timer->total_ms = n_ms; - timer->state = STATE_RUN; - timer->id = ++self.id_count; - timer->start_time = LCUI_GetTime(); - timer->node.next = NULL; - timer->node.prev = NULL; - timer->node.data = timer; - TimerList_AddNode(&timer->node); - LCUIMutex_Unlock(&self.mutex); - DEBUG_MSG("set timer, id: %ld, total_ms: %ld\n", timer->id, - timer->total_ms); - return timer->id; + int ret; + LCUIMutex_Lock(&mutex); + ret = timer_continue(main_timer_list, timer_id); + LCUIMutex_Unlock(&mutex); + return ret; } -int LCUITimer_Free(int timer_id) +int lcui_reset_timer(int timer_id, long int n_ms) { - Timer timer; - if (!self.active) { - return -2; - } - LCUIMutex_Lock(&self.mutex); - timer = FindTimer(timer_id); - if (!timer) { - LCUIMutex_Unlock(&self.mutex); - return -1; - } - LinkedList_Unlink(&self.timers, &timer->node); - free(timer); - LCUIMutex_Unlock(&self.mutex); - return 0; + int ret; + LCUIMutex_Lock(&mutex); + ret = timer_reset(main_timer_list, timer_id, n_ms); + LCUIMutex_Unlock(&mutex); + return ret; } -int LCUITimer_Pause(int timer_id) +int lcui_set_timeout(long int n_ms, void(*callback)(void *), void *arg) { - Timer timer; - if (!self.active) { - return -2; - } - LCUIMutex_Lock(&self.mutex); - timer = FindTimer(timer_id); - if (timer) { - /* 记录暂停时的时间 */ - timer->pause_time = LCUI_GetTime(); - timer->state = STATE_PAUSE; - } - LCUIMutex_Unlock(&self.mutex); - return timer ? 0 : -1; + return timer_list_add_timeout(main_timer_list, n_ms, callback, arg); } -int LCUITimer_Continue(int timer_id) +int lcui_set_interval(long int n_ms, void(*callback)(void *), void *arg) { - Timer timer; - if (!self.active) { - return -2; - } - LCUIMutex_Lock(&self.mutex); - timer = FindTimer(timer_id); - if (timer) { - /* 计算处于暂停状态的时长 */ - timer->pause_ms += - (long int)LCUI_GetTimeDelta(timer->pause_time); - timer->state = STATE_RUN; - } - LCUIMutex_Unlock(&self.mutex); - return timer ? 0 : -1; + return timer_list_add_interval(main_timer_list, n_ms, callback, arg); } -int LCUITimer_Reset(int timer_id, long int n_ms) -{ - Timer timer; - if (!self.active) { - return -2; - } - LCUIMutex_Lock(&self.mutex); - timer = FindTimer(timer_id); - if (timer) { - timer->pause_ms = 0; - timer->total_ms = n_ms; - timer->start_time = LCUI_GetTime(); - } - LCUIMutex_Unlock(&self.mutex); - return timer ? 0 : -1; -} - -int LCUI_SetTimeout(long int n_ms, void(*callback)(void *), void *arg) -{ - return LCUITimer_Set(n_ms, callback, arg, FALSE); -} - -int LCUI_SetInterval(long int n_ms, void(*callback)(void *), void *arg) -{ - return LCUITimer_Set(n_ms, callback, arg, TRUE); -} - -size_t LCUI_ProcessTimers(void) +size_t lcui_process_timers() { size_t count = 0; - long lost_ms; - - Timer timer = NULL; - LinkedListNode *node; - - LCUIMutex_Lock(&self.mutex); - while(self.active) { - for (LinkedList_Each(node, &self.timers)) { - timer = node->data; - if (timer && timer->state == STATE_RUN) { - break; - } - } - if (!node) { - break; - } - count += 1; - lost_ms = (long)LCUI_GetTimeDelta(timer->start_time); - /* 若流失的时间未达到总定时时长 */ - if (lost_ms - timer->pause_ms < timer->total_ms) { - break; - } - /* 若需要重复使用,则重置剩余等待时间 */ - LinkedList_Unlink(&self.timers, node); - timer->callback(timer->arg); - if (timer->reuse) { - timer->pause_ms = 0; - timer->start_time = LCUI_GetTime(); - TimerList_AddNode(node); - } else { - free(timer); - } - } - LCUIMutex_Unlock(&self.mutex); + LCUIMutex_Lock(&mutex); + count = timer_list_process(main_timer_list); + LCUIMutex_Unlock(&mutex); return count; } -void LCUI_InitTimer(void) +void lcui_init_timers(void) { - self.active = TRUE; - LCUITime_Init(); - LCUIMutex_Init(&self.mutex); - LinkedList_Init(&self.timers); + LCUIMutex_Init(&mutex); + main_timer_list = timer_list_create(); } -void LCUI_FreeTimer(void) +void lcui_destroy_timers() { - if (!self.active) { + if(!main_timer_list){ return; } - self.active = FALSE; - LCUIMutex_Lock(&self.mutex); - LCUIMutex_Unlock(&self.mutex); - LinkedList_ClearData(&self.timers, free); - LCUIMutex_Destroy(&self.mutex); + timer_list_destroy(main_timer_list); + LCUIMutex_Destroy(&mutex); + main_timer_list = NULL; } diff --git a/lib/ui-anchor/src/anchor.c b/lib/ui-anchor/src/anchor.c index 22435bb9..c8a849f1 100644 --- a/lib/ui-anchor/src/anchor.c +++ b/lib/ui-anchor/src/anchor.c @@ -122,7 +122,7 @@ static void XMLLoader_Load(LCUI_XMLLoader loader) if (loader->filepath[0] != '/') { path = malloc(strsize(loader->filepath) + sizeof(dirname)); if (!path) { - Logger_Error("[anchor] out of memory\n"); + logger_error("[anchor] out of memory\n"); return; } strcpy(path, dirname); @@ -142,7 +142,7 @@ static void XMLLoader_Load(LCUI_XMLLoader loader) LCUI_PostSimpleTask(XMLLoader_AppendToTarget, loader, NULL); return; } - Logger_Error("[anchor] href (%s): cannot load xml resource\n", + logger_error("[anchor] href (%s): cannot load xml resource\n", loader->filepath); XMLLoader_Destroy(loader); } @@ -153,7 +153,7 @@ static void XMLLoader_StartLoad(LCUI_XMLLoader loader) LCUI_TaskRec task = { 0 }; target = LCUIWidget_GetById(loader->target_id); if (!target) { - Logger_Error("[anchor] target (%s): not found\n", + logger_error("[anchor] target (%s): not found\n", loader->target_id); return; } @@ -169,7 +169,7 @@ void Anchor_Open(LCUI_Widget w) const char *attr_href = Widget_GetAttribute(w, "href"); if (!attr_href) { - Logger_Error("[anchor] href are required\n"); + logger_error("[anchor] href are required\n"); return; } if (strstr(attr_href, "file:") == attr_href) { @@ -183,7 +183,7 @@ void Anchor_Open(LCUI_Widget w) } loader = XMLLoader_New(w); if (!loader) { - Logger_Error("[anchor] out of memory\n"); + logger_error("[anchor] out of memory\n"); return; } LCUI_PostSimpleTask(XMLLoader_StartLoad, loader, NULL); diff --git a/lib/ui-anchor/src/uri.cpp b/lib/ui-anchor/src/uri.cpp index c0c514c1..b91c28ba 100644 --- a/lib/ui-anchor/src/uri.cpp +++ b/lib/ui-anchor/src/uri.cpp @@ -33,7 +33,7 @@ #include #include #include -#include +#include #if defined(LCUI_BUILD_IN_WIN32) && defined(WINAPI_PARTITION_APP) int OpenUri(const char *uristr) @@ -41,7 +41,7 @@ int OpenUri(const char *uristr) size_t len; wchar_t *wuri; - len = LCUI_DecodeString(NULL, uristr, 0, ENCODING_ANSI); + len = decode_string(NULL, uristr, 0, ENCODING_ANSI); if (len < 1) { return -1; } @@ -49,7 +49,7 @@ int OpenUri(const char *uristr) if (!wuri) { return -2; } - LCUI_DecodeString(wuri, uristr, len, ENCODING_ANSI); + decode_string(wuri, uristr, len, ENCODING_ANSI); wuri[len] = 0; auto str = ref new Platform::String(wuri); diff --git a/lib/ui-builder/src/builder.c b/lib/ui-builder/src/builder.c index e108fd71..07b7ff0c 100644 --- a/lib/ui-builder/src/builder.c +++ b/lib/ui-builder/src/builder.c @@ -77,7 +77,7 @@ struct XMLParserContextRec_ { static struct ModuleContext { LCUI_BOOL active; - RBTree parsers; + rbtree_t parsers; } self; #define EXIT(CODE) \ @@ -86,7 +86,7 @@ static struct ModuleContext { static void xmlPrintErrorMessage(xmlErrorPtr err) { - Logger_Error("[builder] %s (%d): error %d: %s\n", + logger_error("[builder] %s (%d): error %d: %s\n", err->file ? err->file : "(memory)", err->line, err->code, err->message); } @@ -258,12 +258,12 @@ static void LCUIBuilder_Init(void) int i, len; Parser *p; - RBTree_Init(&self.parsers); - RBTree_OnCompare(&self.parsers, CompareName); + rbtree_init(&self.parsers); + rbtree_set_compare_func(&self.parsers, CompareName); len = sizeof(parser_list) / sizeof(parser_list[0]); for (i = 0; i < len; ++i) { p = &parser_list[i]; - RBTree_CustomInsert(&self.parsers, p->name, p); + rbtree_insert_by_keydata(&self.parsers, p->name, p); } self.active = TRUE; } @@ -281,7 +281,7 @@ static void ParseNode(XMLParserContext ctx, xmlNodePtr node) continue; } if (node->type == XML_ELEMENT_NODE) { - p = RBTree_CustomGetData(&self.parsers, node->name); + p = rbtree_get_data_by_keydata(&self.parsers, node->name); if (!p) { proto = LCUIWidget_GetPrototype((char *)node->name); @@ -312,12 +312,12 @@ static void ParseNode(XMLParserContext ctx, xmlNodePtr node) case PB_NEXT: break; case PB_WARNING: - Logger_Warning("[builder] %s (%d): warning: %s node.\n", + logger_warning("[builder] %s (%d): warning: %s node.\n", node->doc->name, node->line, node->name); break; case PB_ERROR: default: - Logger_Error("[builder] %s (%d): error: %s node.\n", + logger_error("[builder] %s (%d): error: %s node.\n", node->doc->name, node->line, node->name); break; } @@ -331,7 +331,7 @@ static void ParseNode(XMLParserContext ctx, xmlNodePtr node) LCUI_Widget LCUIBuilder_LoadString(const char *str, int size) { #ifndef USE_LIBXML2 - Logger_Warning(WARN_TXT); + logger_warning(WARN_TXT); #else xmlDocPtr doc; xmlNodePtr cur; @@ -341,12 +341,12 @@ LCUI_Widget LCUIBuilder_LoadString(const char *str, int size) doc = xmlParseMemory(str, size); if (!doc) { xmlPrintErrorMessage(xmlGetLastError()); - Logger_Error("[builder] failed to parse xml form memory\n"); + logger_error("[builder] failed to parse xml form memory\n"); goto FAILED; } cur = xmlDocGetRootElement(doc); if (xmlStrcasecmp(cur->name, BAD_CAST "lcui-app")) { - Logger_Error("[builder] error root node name: %s\n", cur->name); + logger_error("[builder] error root node name: %s\n", cur->name); goto FAILED; } if (!self.active) { @@ -365,7 +365,7 @@ FAILED: LCUI_Widget LCUIBuilder_LoadFile(const char *filepath) { #ifndef USE_LIBXML2 - Logger_Warning(WARN_TXT); + logger_warning(WARN_TXT); #else xmlDocPtr doc; xmlNodePtr cur; @@ -376,12 +376,12 @@ LCUI_Widget LCUIBuilder_LoadFile(const char *filepath) doc = xmlParseFile(filepath); if (!doc) { xmlPrintErrorMessage(xmlGetLastError()); - Logger_Error("[builder] failed to parse xml form file\n"); + logger_error("[builder] failed to parse xml form file\n"); goto FAILED; } cur = xmlDocGetRootElement(doc); if (xmlStrcasecmp(cur->name, BAD_CAST "lcui-app")) { - Logger_Error("[builder] error root node name: %s\n", cur->name); + logger_error("[builder] error root node name: %s\n", cur->name); goto FAILED; } if (!self.active) { diff --git a/lib/ui-widgets/src/canvas.c b/lib/ui-widgets/src/canvas.c index f03cd0b6..9e20c7ab 100644 --- a/lib/ui-widgets/src/canvas.c +++ b/lib/ui-widgets/src/canvas.c @@ -37,7 +37,7 @@ typedef struct CanvasRec_ { LCUI_Graph buffer; - LinkedList contexts; + list_t contexts; } CanvasRec, *Canvas; static struct { @@ -65,20 +65,20 @@ static void Canvas_OnInit(LCUI_Widget w) Canvas canvas = Widget_AddData(w, self.proto, sizeof(CanvasRec)); Graph_Init(&canvas->buffer); - LinkedList_Init(&canvas->contexts); + list_create(&canvas->contexts); } static void Canvas_OnDestroy(LCUI_Widget w) { - LinkedListNode *node; + list_node_t *node; LCUI_CanvasContext ctx; Canvas canvas = Widget_AddData(w, self.proto, sizeof(CanvasRec)); - for (LinkedList_Each(node, &canvas->contexts)) { + for (list_each(node, &canvas->contexts)) { ctx = node->data; ctx->available = FALSE; } - LinkedList_ClearData(&canvas->contexts, NULL); + list_destroy_without_node(&canvas->contexts, NULL); Graph_Free(&canvas->buffer); } @@ -144,7 +144,7 @@ static void CanvasContext_Release(LCUI_CanvasContext ctx) if (ctx->available) { canvas = Widget_GetData(ctx->canvas, self.proto); - LinkedList_Unlink(&canvas->contexts, &ctx->node); + list_unlink(&canvas->contexts, &ctx->node); } free(ctx); } @@ -166,7 +166,7 @@ LCUI_CanvasContext Canvas_GetContext(LCUI_Widget w) ctx->release = CanvasContext_Release; ctx->node.data = ctx; ctx->node.next = ctx->node.prev = NULL; - LinkedList_AppendNode(&canvas->contexts, &ctx->node); + list_append_node(&canvas->contexts, &ctx->node); return ctx; } diff --git a/lib/ui-widgets/src/scrollbar.c b/lib/ui-widgets/src/scrollbar.c index a8bd4bbe..6a20e5e6 100644 --- a/lib/ui-widgets/src/scrollbar.c +++ b/lib/ui-widgets/src/scrollbar.c @@ -165,9 +165,9 @@ static void OnInertialScrolling(void *arg) scrollbar = Widget_GetData(w, scrollbar_prototype); effect = &scrollbar->effect; - time = (double)LCUI_GetTimeDelta(effect->timestamp) / 1000; + time = (double)get_time_delta(effect->timestamp) / 1000; distance = (effect->speed + 0.5 * effect->speed_delta * time) * time; - pos = effect->end_pos + iround(distance); + pos = effect->end_pos + y_iround(distance); DEBUG_MSG("distance: %g, pos: %d, speed_delta: %g, speed: %g\n", distance, pos, effect->speed_delta, effect->speed + effect->speed_delta * time); @@ -180,7 +180,7 @@ static void OnInertialScrolling(void *arg) ScrollBar_SetPosition(w, pos); return; } - LCUITimer_Free(effect->timer); + lcui_destroy_timer(effect->timer); effect->is_running = FALSE; effect->timer = -1; } @@ -202,7 +202,7 @@ static void UpdateInertialScrolling(InertialScrolling effect, int pos) effect->speed = 0; effect->is_running = FALSE; effect->start_pos = pos; - effect->timestamp = LCUI_GetTime(); + effect->timestamp = get_time_ms(); } static void StartInertialScrolling(LCUI_Widget w) @@ -217,7 +217,7 @@ static void StartInertialScrolling(LCUI_Widget w) effect = &scrollbar->effect; effect->end_pos = scrollbar->pos; distance = effect->end_pos - effect->start_pos; - time_delta = LCUI_GetTimeDelta(effect->timestamp); + time_delta = get_time_delta(effect->timestamp); /* 根据距离计算当前移动速度 */ if (time_delta > 0) { effect->speed = 1000.0 * distance / time_delta; @@ -226,16 +226,16 @@ static void StartInertialScrolling(LCUI_Widget w) return; } effect->speed_delta = -effect->speed; - effect->timestamp = LCUI_GetTime(); + effect->timestamp = get_time_ms(); if (effect->is_running) { return; } effect->is_running = TRUE; if (effect->timer > 0) { - LCUITimer_Free(effect->timer); + lcui_destroy_timer(effect->timer); } effect->timer = - LCUITimer_Set(effect->interval, OnInertialScrolling, w, TRUE); + lcui_set_interval(effect->interval, OnInertialScrolling, w); DEBUG_MSG("start_pos: %d, end_pos: %d\n", effect->start_pos, effect->end_pos); DEBUG_MSG("effect->speed: %g, distance: %d, time: %d\n", effect->speed, @@ -260,29 +260,29 @@ static void ScrollBarThumb_OnMouseMove(LCUI_Widget thumb, LCUI_WidgetEvent e, if (scrollbar->direction == LCUI_SCROLLBAR_HORIZONTAL) { size = thumb->parent->box.content.width - thumb->width; x = scrollbar->thumb_x + e->motion.x - scrollbar->mouse_x; - x = max(0, min(x, size)); + x = y_max(0, y_min(x, size)); y = 0; layer_pos = (scrollbar->target->box.outer.width - box->box.content.width) * - max(0, min(x / size, 1.0)); + y_max(0, y_min(x / size, 1.0)); Widget_SetStyle(target, key_left, -layer_pos, px); } else { size = thumb->parent->box.content.height - thumb->height; x = 0; y = scrollbar->thumb_y + e->motion.y - scrollbar->mouse_y; - y = max(0, min(y, size)); + y = y_max(0, y_min(y, size)); layer_pos = (scrollbar->target->box.outer.height - box->box.content.height) * - max(0, min(y / size, 1.0)); + y_max(0, y_min(y / size, 1.0)); Widget_SetStyle(target, key_top, -layer_pos, px); } - if (scrollbar->pos != iround(layer_pos)) { + if (scrollbar->pos != y_iround(layer_pos)) { LCUI_WidgetEventRec e; LCUI_InitWidgetEvent(&e, "scroll"); e.cancel_bubble = TRUE; Widget_TriggerEvent(target, &e, &layer_pos); } - scrollbar->pos = iround(layer_pos); + scrollbar->pos = y_iround(layer_pos); Widget_UpdateStyle(target, FALSE); Widget_Move(thumb, x, y); } @@ -498,7 +498,7 @@ static void ScrollBox_OnTouch(LCUI_Widget box, LCUI_WidgetEvent e, void *arg) break; case LCUI_WEVENT_TOUCHUP: Widget_ReleaseTouchCapture(box, -1); - time_delta = (uint_t)LCUI_GetTimeDelta(scrollbar->timestamp); + time_delta = (uint_t)get_time_delta(scrollbar->timestamp); if (scrollbar->is_dragging && time_delta < 50) { StartInertialScrolling(w); } @@ -527,7 +527,7 @@ static void ScrollBox_OnTouch(LCUI_Widget box, LCUI_WidgetEvent e, void *arg) scrollbar->pos); } scrollbar->distance = distance; - scrollbar->timestamp = LCUI_GetTime(); + scrollbar->timestamp = get_time_ms(); ScrollBar_SetPosition(w, pos); if (scrollbar->is_dragging) { break; @@ -667,7 +667,7 @@ int ScrollBar_SetPosition(LCUI_Widget w, int pos) Widget_SetStyle(thumb, key_top, thumb_pos, px); Widget_SetStyle(target, key_top, -new_pos, px); } - pos = iround(new_pos); + pos = y_iround(new_pos); if (scrollbar->pos != pos) { LCUI_WidgetEventRec e; LCUI_InitWidgetEvent(&e, "scroll"); diff --git a/lib/ui-widgets/src/sidebar.c b/lib/ui-widgets/src/sidebar.c index f0680b46..7188de82 100644 --- a/lib/ui-widgets/src/sidebar.c +++ b/lib/ui-widgets/src/sidebar.c @@ -44,7 +44,7 @@ typedef struct SideBarItemRec_ { } SideBarItemRec, *SideBarItem; typedef struct SideBarRec_ { - LinkedList items; + list_t items; LCUI_Style line_height; } SideBarRec, *SideBar; @@ -119,7 +119,7 @@ LCUI_Widget SideBar_AppendItem(LCUI_Widget sidebar, const wchar_t *id, Widget_Show(w); Widget_Show(sbi->icon); Widget_Show(sbi->text); - LinkedList_Append(&sb->items, sbi); + list_append(&sb->items, sbi); return w; } @@ -141,7 +141,7 @@ static void SideBar_OnInit(LCUI_Widget w) { const size_t data_size = sizeof(SideBarRec); SideBar sb = Widget_AddData(w, self.sidebar, data_size); - LinkedList_Init(&sb->items); + list_create(&sb->items); } static void OnToggle(LCUI_Widget w, LCUI_WidgetEvent e, void *arg) diff --git a/lib/ui-widgets/src/textcaret.c b/lib/ui-widgets/src/textcaret.c index 36d63d63..c69025a2 100644 --- a/lib/ui-widgets/src/textcaret.c +++ b/lib/ui-widgets/src/textcaret.c @@ -75,7 +75,7 @@ void TextCaret_Refresh(LCUI_Widget widget) if (!caret->visible) { return; } - LCUITimer_Reset(caret->timer_id, caret->blink_interval); + lcui_reset_timer(caret->timer_id, caret->blink_interval); Widget_GetOffset(widget, LCUIWidget_GetRoot(), &x, &y); LCUIIME_SetCaret((int)x, (int)y); Widget_Show(widget); @@ -107,7 +107,7 @@ void TextCaret_SetVisible(LCUI_Widget widget, LCUI_BOOL visible) if (visible) { TextCaret_Refresh(widget); } else { - LCUITimer_Reset(caret->timer_id, caret->blink_interval); + lcui_reset_timer(caret->timer_id, caret->blink_interval); Widget_Hide(widget); } } @@ -122,7 +122,7 @@ static void TextCaret_OnInit(LCUI_Widget widget) caret->task->widget = widget; caret->blink_interval = 500; caret->visible = FALSE; - caret->timer_id = LCUI_SetInterval(caret->blink_interval, + caret->timer_id = lcui_set_interval(caret->blink_interval, TextCaret_OnBlink, caret->task); } @@ -132,7 +132,7 @@ void TextCaret_SetBlinkTime(LCUI_Widget widget, unsigned int n_ms) caret = Widget_GetData(widget, prototype); caret->blink_interval = n_ms; - LCUITimer_Reset(caret->timer_id, caret->blink_interval); + lcui_reset_timer(caret->timer_id, caret->blink_interval); } static void TextCaret_OnDestroy(LCUI_Widget widget) @@ -141,7 +141,7 @@ static void TextCaret_OnDestroy(LCUI_Widget widget) caret = Widget_GetData(widget, prototype); caret->task->active = FALSE; - if (LCUITimer_Free(caret->timer_id) != -1) { + if (lcui_destroy_timer(caret->timer_id) != -1) { free(caret->task); caret->task = NULL; } diff --git a/lib/ui-widgets/src/textedit.c b/lib/ui-widgets/src/textedit.c index ce3560a8..6ad4080e 100644 --- a/lib/ui-widgets/src/textedit.c +++ b/lib/ui-widgets/src/textedit.c @@ -48,7 +48,7 @@ #define PLACEHOLDER_COLOR RGB(140, 140, 140) #define GetData(W) Widget_GetData(W, self.prototype) #define AddData(W) Widget_AddData(W, self.prototype, sizeof(LCUI_TextEditRec)) -#define TextBlocks_Clear(blocks) LinkedList_Clear(blocks, TextBlock_OnDestroy) +#define TextBlocks_Clear(blocks) list_destroy(blocks, TextBlock_OnDestroy) enum TaskType { TASK_SET_TEXT, TASK_UPDATE, TASK_TOTAL }; @@ -67,8 +67,8 @@ typedef struct LCUI_TextEditRec_ { wchar_t *allow_input_char; /**< 允许输入的字符 */ wchar_t password_char; /**< 屏蔽符的副本 */ size_t text_block_size; /**< 块大小 */ - LinkedList text_blocks; /**< 文本块缓冲区 */ - LinkedList text_tags; /**< 当前处理的标签列表 */ + list_t text_blocks; /**< 文本块缓冲区 */ + list_t text_tags; /**< 当前处理的标签列表 */ LCUI_BOOL tasks[TASK_TOTAL]; /**< 待处理的任务 */ LCUI_Mutex mutex; /**< 互斥锁 */ } LCUI_TextEditRec, *LCUI_TextEdit; @@ -152,8 +152,8 @@ static void TextEdit_UpdateCaret(LCUI_Widget widget) caret_x = pos.x / scale; caret_y = pos.y / scale; } - offset_x = iround(edit->layer->offset_x / scale); - offset_y = iround(edit->layer->offset_y / scale); + offset_x = y_iround(edit->layer->offset_x / scale); + offset_y = y_iround(edit->layer->offset_y / scale); x = caret_x + offset_x; y = caret_y + offset_y; width = edit->layer->width / scale; @@ -180,8 +180,8 @@ static void TextEdit_UpdateCaret(LCUI_Widget widget) x = caret_x + widget->box.content.width - (edit->layer->width / scale); } - offset_x = iround((x - caret_x) * scale); - offset_y = iround((y - caret_y) * scale); + offset_x = y_iround((x - caret_x) * scale); + offset_y = y_iround((y - caret_y) * scale); if (TextLayer_SetOffset(edit->layer, offset_x, offset_y)) { edit->tasks[TASK_UPDATE] = TRUE; Widget_AddTask(widget, LCUI_WTASK_USER); @@ -255,7 +255,7 @@ static int TextEdit_AddTextBlock(LCUI_Widget widget, const wchar_t *wtext, --i; block->text[j] = 0; block->length = j; - LinkedList_Append(&edit->text_blocks, block); + list_append(&edit->text_blocks, block); continue; } for (j = 0; i < len && j < size - 1; ++j, ++i) { @@ -287,7 +287,7 @@ static int TextEdit_AddTextBlock(LCUI_Widget widget, const wchar_t *wtext, block->text[j] = 0; block->length = j; /* 添加文本块至缓冲区 */ - LinkedList_Append(&edit->text_blocks, block); + list_append(&edit->text_blocks, block); } edit->tasks[TASK_SET_TEXT] = TRUE; Widget_AddTask(widget, LCUI_WTASK_USER); @@ -297,7 +297,7 @@ static int TextEdit_AddTextBlock(LCUI_Widget widget, const wchar_t *wtext, /** 更新文本框内的字体位图 */ static void TextEdit_ProcTextBlock(LCUI_Widget widget, LCUI_TextBlock txtblk) { - LinkedList *tags; + list_t *tags; LCUI_TextEdit edit; LCUI_TextLayer layer; @@ -343,13 +343,13 @@ static void TextEdit_ProcTextBlock(LCUI_Widget widget, LCUI_TextBlock txtblk) static void TextEdit_UpdateTextLayer(LCUI_Widget w) { float scale; - LinkedList rects; + list_t rects; LCUI_RectF rect; LCUI_TextEdit edit; LCUI_TextStyleRec style; - LinkedListNode *node; + list_node_t *node; - LinkedList_Init(&rects); + list_create(&rects); scale = LCUIMetrics_GetScale(); edit = Widget_GetData(w, self.prototype); TextStyle_Copy(&style, &edit->layer_source->text_default_style); @@ -361,7 +361,7 @@ static void TextEdit_UpdateTextLayer(LCUI_Widget w) TextLayer_SetTextStyle(edit->layer_placeholder, &style); TextStyle_Destroy(&style); TextLayer_Update(edit->layer, &rects); - for (LinkedList_Each(node, &rects)) { + for (list_each(node, &rects)) { LCUIRect_ToRectF(node->data, &rect, 1.0f / scale); Widget_InvalidateArea(w, &rect, SV_CONTENT_BOX); } @@ -374,15 +374,15 @@ static void TextEdit_OnTask(LCUI_Widget widget, int task) LCUI_TextEdit edit = Widget_GetData(widget, self.prototype); if (edit->tasks[TASK_SET_TEXT]) { - LinkedList blocks; - LinkedListNode *node; + list_t blocks; + list_node_t *node; LCUI_WidgetEventRec ev; - LinkedList_Init(&blocks); + list_create(&blocks); LCUIMutex_Lock(&edit->mutex); - LinkedList_Concat(&blocks, &edit->text_blocks); + list_concat(&blocks, &edit->text_blocks); LCUIMutex_Unlock(&edit->mutex); - for (LinkedList_Each(node, &blocks)) { + for (list_each(node, &blocks)) { TextEdit_ProcTextBlock(widget, node->data); } TextBlocks_Clear(&blocks); @@ -415,18 +415,18 @@ static void TextEdit_OnResize(LCUI_Widget w, float width, float height) { float scale = LCUIMetrics_GetScale(); - LinkedList rects; - LinkedListNode *node; + list_t rects; + list_node_t *node; LCUI_RectF rect; LCUI_TextEdit edit = GetData(w); - LinkedList_Init(&rects); + list_create(&rects); TextLayer_SetFixedSize(edit->layer, (int)(width * scale), (int)(width * scale)); TextLayer_SetMaxSize(edit->layer, (int)(height * scale), (int)(height * scale)); TextLayer_Update(edit->layer, &rects); TextLayer_ClearInvalidRect(edit->layer); - for (LinkedList_Each(node, &rects)) { + for (list_each(node, &rects)) { LCUIRect_ToRectF(node->data, &rect, 1.0f / scale); Widget_InvalidateArea(w, &rect, SV_CONTENT_BOX); } @@ -446,7 +446,7 @@ static void TextEdit_OnAutoSize(LCUI_Widget w, float *width, float *height, case LCUI_LAYOUT_RULE_FIXED_WIDTH: max_width = (int)(scale * w->box.content.width); if (edit->is_multiline_mode) { - n = max(TextLayer_GetRowTotal(edit->layer), 6); + n = y_max(TextLayer_GetRowTotal(edit->layer), 6); for (max_height = 0, i = 0; i < n; ++i) { max_height += TextLayer_GetRowHeight(edit->layer, i); @@ -466,7 +466,7 @@ static void TextEdit_OnAutoSize(LCUI_Widget w, float *width, float *height, default: max_width = (int)(scale * DEFAULT_WIDTH); if (edit->is_multiline_mode) { - n = max(TextLayer_GetRowTotal(edit->layer), 6); + n = y_max(TextLayer_GetRowTotal(edit->layer), 6); for (max_height = 0, i = 0; i < n; ++i) { max_height += TextLayer_GetRowHeight(edit->layer, i); @@ -504,16 +504,16 @@ void TextEdit_ClearText(LCUI_Widget widget) { LCUI_TextEdit edit; LCUI_TextBlock block; - LinkedListNode *node, *prev; + list_node_t *node, *prev; edit = Widget_GetData(widget, self.prototype); LCUIMutex_Lock(&edit->mutex); - for (LinkedList_Each(node, &edit->text_blocks)) { + for (list_each(node, &edit->text_blocks)) { block = node->data; prev = node->prev; if (block->owner == TEXT_BLOCK_OWNER_SOURCE) { TextBlock_OnDestroy(block); - LinkedList_DeleteNode(&edit->text_blocks, node); + list_delete_node(&edit->text_blocks, node); node = prev; } } @@ -570,7 +570,7 @@ int TextEdit_SetText(LCUI_Widget widget, const char *utf8_str) if (!wstr) { return -ENOMEM; } - len = LCUI_DecodeString(wstr, utf8_str, len, ENCODING_UTF8); + len = decode_utf8(wstr, utf8_str, len); wstr[len] = 0; ret = TextEdit_SetTextW(widget, wstr); free(wstr); @@ -634,7 +634,7 @@ int TextEdit_SetPlaceHolder(LCUI_Widget w, const char *str) if (!wstr) { return -ENOMEM; } - len = LCUI_DecodeString(wstr, str, len, ENCODING_UTF8); + len = decode_utf8(wstr, str, len); wstr[len] = 0; ret = TextEdit_SetPlaceHolderW(w, wstr); free(wstr); @@ -837,8 +837,8 @@ static void TextEdit_OnMouseMove(LCUI_Widget w, LCUI_WidgetEvent e, void *arg) } scale = LCUIMetrics_GetScale(); Widget_GetOffset(w, NULL, &offset_x, &offset_y); - x = iround((e->motion.x - offset_x - w->padding.left) * scale); - y = iround((e->motion.y - offset_y - w->padding.top) * scale); + x = y_iround((e->motion.x - offset_x - w->padding.left) * scale); + y = y_iround((e->motion.y - offset_y - w->padding.top) * scale); TextLayer_SetCaretPosByPixelPos(edit->layer, x, y); TextEdit_UpdateCaret(w); } @@ -857,8 +857,8 @@ static void TextEdit_OnMouseDown(LCUI_Widget w, LCUI_WidgetEvent e, void *arg) LCUI_TextEdit edit = GetData(w); Widget_GetOffset(w, NULL, &offset_x, &offset_y); - x = iround((e->motion.x - offset_x - w->padding.left) * scale); - y = iround((e->motion.y - offset_y - w->padding.top) * scale); + x = y_iround((e->motion.x - offset_x - w->padding.left) * scale); + y = y_iround((e->motion.y - offset_y - w->padding.top) * scale); TextLayer_SetCaretPosByPixelPos(edit->layer, x, y); TextEdit_UpdateCaret(w); Widget_SetMouseCapture(w); @@ -895,7 +895,7 @@ static void TextEdit_OnInit(LCUI_Widget w) edit->caret = LCUIWidget_New("textcaret"); w->computed_style.focusable = TRUE; memset(edit->tasks, 0, sizeof(edit->tasks)); - LinkedList_Init(&edit->text_blocks); + list_create(&edit->text_blocks); StyleTags_Init(&edit->text_tags); TextEdit_EnableMultiline(w, FALSE); TextLayer_SetAutoWrap(edit->layer, TRUE); diff --git a/lib/ui-widgets/src/textview.c b/lib/ui-widgets/src/textview.c index 52ade820..23243896 100644 --- a/lib/ui-widgets/src/textview.c +++ b/lib/ui-widgets/src/textview.c @@ -57,12 +57,12 @@ typedef struct LCUI_TextViewRec_ { LCUI_TextLayer layer; LCUI_CSSFontStyleRec style; LCUI_TextViewTaskRec task; - LinkedListNode node; + list_node_t node; } LCUI_TextViewRec, *LCUI_TextView; static struct LCUI_TextViewModule { int key_word_break; - LinkedList list; + list_t list; LCUI_WidgetPrototype prototype; } self; @@ -130,13 +130,13 @@ static void TextView_Update(LCUI_Widget w) LCUI_RectF rect; LCUI_TextView txt = GetData(w); - LinkedList rects; - LinkedListNode *node; + list_t rects; + list_node_t *node; - LinkedList_Init(&rects); + list_create(&rects); TextLayer_Update(txt->layer, &rects); TextLayer_ClearInvalidRect(txt->layer); - for (LinkedList_Each(node, &rects)) { + for (list_each(node, &rects)) { LCUIRect_ToRectF(node->data, &rect, 1.0f / scale); Widget_InvalidateArea(w, &rect, SV_CONTENT_BOX); } @@ -191,14 +191,14 @@ static void TextView_OnInit(LCUI_Widget w) CSSFontStyle_Init(&txt->style); txt->node.data = txt; txt->node.prev = txt->node.next = NULL; - LinkedList_AppendNode(&self.list, &txt->node); + list_append_node(&self.list, &txt->node); } static void TextView_OnDestroy(LCUI_Widget w) { LCUI_TextView txt = GetData(w); - LinkedList_Unlink(&self.list, &txt->node); + list_unlink(&self.list, &txt->node); CSSFontStyle_Destroy(&txt->style); TextLayer_Destroy(txt->layer); free(txt->content); @@ -216,7 +216,7 @@ static void TextView_OnAutoSize(LCUI_Widget w, float *width, float *height, LCUI_TextView txt = GetData(w); - LinkedList rects; + list_t rects; if (w->parent && w->parent->computed_style.width_sizing == LCUI_SIZING_RULE_FIXED) { @@ -243,7 +243,7 @@ static void TextView_OnAutoSize(LCUI_Widget w, float *width, float *height, max_height = 0; break; } - LinkedList_Init(&rects); + list_create(&rects); TextLayer_SetFixedSize(txt->layer, 0, 0); TextLayer_SetMaxSize(txt->layer, max_width, max_height); TextLayer_Update(txt->layer, &rects); @@ -262,15 +262,15 @@ static void TextView_OnResize(LCUI_Widget w, float width, float height) LCUI_RectF rect; LCUI_TextView txt = GetData(w); - LinkedList rects; - LinkedListNode *node; + list_t rects; + list_node_t *node; - LinkedList_Init(&rects); + list_create(&rects); TextLayer_SetFixedSize(txt->layer, fixed_width, fixed_height); TextLayer_SetMaxSize(txt->layer, fixed_width, fixed_height); TextLayer_Update(txt->layer, &rects); TextLayer_ClearInvalidRect(txt->layer); - for (LinkedList_Each(node, &rects)) { + for (list_each(node, &rects)) { LCUIRect_ToRectF(node->data, &rect, 1.0f / scale); Widget_InvalidateArea(w, &rect, SV_CONTENT_BOX); } @@ -348,7 +348,7 @@ int TextView_SetText(LCUI_Widget w, const char *utf8_text) size_t len = strlen(utf8_text) + 1; wstr = malloc(sizeof(wchar_t) * len); - LCUI_DecodeString(wstr, utf8_text, len, ENCODING_UTF8); + decode_utf8(wstr, utf8_text, len); ret = TextView_SetTextW(w, wstr); if (wstr) { free(wstr); @@ -392,9 +392,9 @@ size_t LCUIWidget_RefreshTextView(void) { size_t count = 0; LCUI_TextView txt; - LinkedListNode *node; + list_node_t *node; - for (LinkedList_Each(node, &self.list)) { + for (list_each(node, &self.list)) { txt = node->data; if (txt->widget->state != LCUI_WSTATE_DELETED) { Widget_UpdateStyle(txt->widget, TRUE); @@ -442,10 +442,10 @@ void LCUIWidget_AddTextView(void) self.prototype->setattr = TextView_OnParseAttr; self.prototype->runtask = TextVIew_OnTask; LCUI_AddCSSPropertyParser(&parser); - LinkedList_Init(&self.list); + list_create(&self.list); } void LCUIWidget_FreeTextView(void) { - LinkedList_ClearData(&self.list, NULL); + list_destroy_without_node(&self.list, NULL); } diff --git a/lib/ui/src/css_fontstyle.c b/lib/ui/src/css_fontstyle.c index fea6d72e..4cddbdc5 100644 --- a/lib/ui/src/css_fontstyle.c +++ b/lib/ui/src/css_fontstyle.c @@ -230,7 +230,7 @@ static void OnComputeFontSize(LCUI_CSSFontStyle fs, LCUI_Style s) { if (s->is_valid) { fs->font_size = - ComputeActual(max(MIN_FONT_SIZE, s->value), s->type); + ComputeActual(y_max(MIN_FONT_SIZE, s->value), s->type); return; } fs->font_size = ComputeActual(DEFAULT_FONT_SIZE, LCUI_STYPE_PX); @@ -295,14 +295,14 @@ static void OnComputeLineHeight(LCUI_CSSFontStyle fs, LCUI_Style s) int h; if (s->is_valid) { if (s->type == LCUI_STYPE_INT) { - h = iround(fs->font_size * s->val_int); + h = y_iround(fs->font_size * s->val_int); } else if (s->type == LCUI_STYPE_SCALE) { - h = iround(fs->font_size * s->val_scale); + h = y_iround(fs->font_size * s->val_scale); } else { h = ComputeActual(s->value, s->type); } } else { - h = iround(fs->font_size * LINE_HEIGHT_SCALE); + h = y_iround(fs->font_size * LINE_HEIGHT_SCALE); } fs->line_height = h; } @@ -321,9 +321,9 @@ static void OnComputeContent(LCUI_CSSFontStyle fs, LCUI_Style s) return; } - len = LCUI_DecodeUTF8String(NULL, s->val_string, 0); + len = decode_utf8(NULL, s->val_string, 0); content = malloc((len + 1) * sizeof(wchar_t)); - len = LCUI_DecodeUTF8String(content, s->val_string, len); + len = decode_utf8(content, s->val_string, len); content[len] = 0; if (content[0] == '"') { for (i = 0; content[i + 1]; ++i) { diff --git a/lib/ui/src/layout/block.c b/lib/ui/src/layout/block.c index 1e46e7b1..7bbbf92b 100644 --- a/lib/ui/src/layout/block.c +++ b/lib/ui/src/layout/block.c @@ -39,7 +39,7 @@ typedef struct LCUI_BlockLayoutRowRec_ { float width; float height; - LinkedList elements; + list_t elements; } LCUI_BlockLayoutRowRec, *LCUI_BlockLayoutRow; typedef struct LCUI_BlockLayoutContextRec_ { @@ -55,17 +55,17 @@ typedef struct LCUI_BlockLayoutContextRec_ { int prev_display; /* - * LinkedList rows + * list_t rows * Element rows in the static layout flow */ - LinkedList rows; + list_t rows; LCUI_BlockLayoutRow row; /* - * LinkedList free_elements + * list_t free_elements * A list of elements that do not exist in the static layout flow */ - LinkedList free_elements; + list_t free_elements; } LCUI_BlockLayoutContextRec, *LCUI_BlockLayoutContext; static void BlockLayout_UpdateElementPosition(LCUI_BlockLayoutContext ctx, @@ -102,7 +102,7 @@ static LCUI_BlockLayoutRow BlockLayoutRow_Create(void) row = malloc(sizeof(LCUI_BlockLayoutRowRec)); row->width = 0; row->height = 0; - LinkedList_Init(&row->elements); + list_create(&row->elements); return row; } @@ -110,21 +110,21 @@ static void BlockLayoutRow_Destroy(void *arg) { LCUI_BlockLayoutRow row = arg; - LinkedList_Clear(&row->elements, NULL); + list_destroy(&row->elements, NULL); free(row); } static void BlockLayout_NextRow(LCUI_BlockLayoutContext ctx) { if (ctx->row) { - ctx->content_width = max(ctx->content_width, ctx->row->width); + ctx->content_width = y_max(ctx->content_width, ctx->row->width); ctx->content_height += ctx->row->height; ctx->y += ctx->row->height; } ctx->prev_display = 0; ctx->x = ctx->widget->padding.left; ctx->row = BlockLayoutRow_Create(); - LinkedList_Append(&ctx->rows, ctx->row); + list_append(&ctx->rows, ctx->row); } static LCUI_BlockLayoutContext BlockLayout_Begin(LCUI_Widget w, @@ -181,8 +181,8 @@ static LCUI_BlockLayoutContext BlockLayout_Begin(LCUI_Widget w, ctx->content_height = 0; ctx->prev_display = 0; ctx->prev = NULL; - LinkedList_Init(&ctx->free_elements); - LinkedList_Init(&ctx->rows); + list_create(&ctx->free_elements); + list_create(&ctx->rows); BlockLayout_NextRow(ctx); return ctx; } @@ -214,7 +214,7 @@ static void BlockLayout_Load(LCUI_BlockLayoutContext ctx) LCUI_Widget child; LCUI_Widget w = ctx->widget; - LinkedListNode *node; + list_node_t *node; if (ctx->rule == LCUI_LAYOUT_RULE_FIXED_WIDTH || ctx->rule == LCUI_LAYOUT_RULE_FIXED) { @@ -227,11 +227,11 @@ static void BlockLayout_Load(LCUI_BlockLayoutContext ctx) } DEBUG_MSG("%s, start\n", ctx->widget->id); DEBUG_MSG("%s, max_row_width: %g\n", ctx->widget->id, max_row_width); - for (LinkedList_Each(node, &w->children)) { + for (list_each(node, &w->children)) { child = node->data; if (Widget_HasAbsolutePosition(child)) { - LinkedList_Append(&ctx->free_elements, child); + list_append(&ctx->free_elements, child); continue; } /* @@ -281,11 +281,11 @@ static void BlockLayout_Load(LCUI_BlockLayoutContext ctx) if (child->box.outer.height > ctx->row->height) { ctx->row->height = child->box.outer.height; } - LinkedList_Append(&ctx->row->elements, child); + list_append(&ctx->row->elements, child); ctx->prev_display = child->computed_style.display; ctx->prev = child; } - ctx->content_width = max(ctx->content_width, ctx->row->width); + ctx->content_width = y_max(ctx->content_width, ctx->row->width); ctx->content_height += ctx->row->height; DEBUG_MSG("content_size: %g, %g\n", ctx->content_width, ctx->content_height); @@ -315,9 +315,9 @@ static void BlockLayout_ReflowRow(LCUI_BlockLayoutContext ctx, float row_y) float x = ctx->widget->padding.left; LCUI_Widget w; - LinkedListNode *node; + list_node_t *node; - for (LinkedList_Each(node, &ctx->row->elements)) { + for (list_each(node, &ctx->row->elements)) { w = node->data; UpdateBlockItemSize(w, LCUI_LAYOUT_RULE_FIXED); BlockLayout_UpdateElementMargin(ctx, w); @@ -329,8 +329,8 @@ static void BlockLayout_ReflowRow(LCUI_BlockLayoutContext ctx, float row_y) static void BlockLayout_ReflowFreeElements(LCUI_BlockLayoutContext ctx) { - LinkedListNode *node; - for (LinkedList_Each(node, &ctx->free_elements)) { + list_node_t *node; + for (list_each(node, &ctx->free_elements)) { Widget_AutoReflow(node->data, LCUI_LAYOUT_RULE_FIXED); } } @@ -339,13 +339,13 @@ static void BlockLayout_Reflow(LCUI_BlockLayoutContext ctx) { float y; LCUI_Widget w = ctx->widget; - LinkedListNode *node; + list_node_t *node; y = w->padding.top; if (w->computed_style.display != SV_INLINE_BLOCK) { ctx->content_width = w->box.content.width; } - for (LinkedList_Each(node, &ctx->rows)) { + for (list_each(node, &ctx->rows)) { ctx->row = node->data; BlockLayout_ReflowRow(ctx, y); y += ctx->row->height; @@ -355,8 +355,8 @@ static void BlockLayout_Reflow(LCUI_BlockLayoutContext ctx) static void BlockLayout_End(LCUI_BlockLayoutContext ctx) { - LinkedList_Clear(&ctx->rows, BlockLayoutRow_Destroy); - LinkedList_Clear(&ctx->free_elements, NULL); + list_destroy(&ctx->rows, BlockLayoutRow_Destroy); + list_destroy(&ctx->free_elements, NULL); free(ctx); } @@ -371,18 +371,18 @@ static void BlockLayout_ApplySize(LCUI_BlockLayoutContext ctx) width = w->box.content.width; w->proto->autosize(w, &width, &height, ctx->rule); width = w->box.content.width; - height = max(height, ctx->content_height); + height = y_max(height, ctx->content_height); break; case LCUI_LAYOUT_RULE_FIXED_HEIGHT: height = w->box.content.height; w->proto->autosize(w, &width, &height, ctx->rule); - width = max(width, ctx->content_width); + width = y_max(width, ctx->content_width); height = w->box.content.height; break; case LCUI_LAYOUT_RULE_MAX_CONTENT: w->proto->autosize(w, &width, &height, ctx->rule); - width = max(width, ctx->content_width); - height = max(height, ctx->content_height); + width = y_max(width, ctx->content_width); + height = y_max(height, ctx->content_height); break; default: width = w->box.content.width; diff --git a/lib/ui/src/layout/flexbox.c b/lib/ui/src/layout/flexbox.c index 4b5af643..ba89a620 100644 --- a/lib/ui/src/layout/flexbox.c +++ b/lib/ui/src/layout/flexbox.c @@ -47,8 +47,8 @@ typedef struct LCUI_FlexBoxLineRec_ { float sum_of_shrink_value; size_t count_of_auto_margin_items; - /** LinkedList elements */ - LinkedList elements; + /** list_t elements */ + list_t elements; } LCUI_FlexBoxLineRec, *LCUI_FlexBoxLine; typedef struct LCUI_FlexBoxLayoutContextRec_ { @@ -61,11 +61,11 @@ typedef struct LCUI_FlexBoxLayoutContextRec_ { float main_size; float cross_size; - /** LinkedList lines */ - LinkedList lines; + /** list_t lines */ + list_t lines; LCUI_FlexBoxLine line; - LinkedList free_elements; + list_t free_elements; } LCUI_FlexBoxLayoutContextRec, *LCUI_FlexBoxLayoutContext; static LCUI_FlexBoxLine FlexBoxLine_Create(void) @@ -78,7 +78,7 @@ static LCUI_FlexBoxLine FlexBoxLine_Create(void) line->sum_of_grow_value = 0; line->sum_of_shrink_value = 0; line->count_of_auto_margin_items = 0; - LinkedList_Init(&line->elements); + list_create(&line->elements); return line; } @@ -86,7 +86,7 @@ static void FlexBoxLine_Destroy(void *arg) { LCUI_FlexBoxLine line = arg; - LinkedList_Clear(&line->elements, NULL); + list_destroy(&line->elements, NULL); free(line); } @@ -98,13 +98,13 @@ static void FlexBoxLine_LoadElement(LCUI_FlexBoxLine line, LCUI_Widget w) if (w->computed_style.flex.shrink > 0) { line->sum_of_shrink_value += w->computed_style.flex.shrink; } - LinkedList_Append(&line->elements, w); + list_append(&line->elements, w); } static void FlexBoxLayout_NextLine(LCUI_FlexBoxLayoutContext ctx) { if (ctx->line) { - ctx->main_size = max(ctx->main_size, ctx->line->main_size); + ctx->main_size = y_max(ctx->main_size, ctx->line->main_size); ctx->cross_axis += ctx->line->cross_size; ctx->cross_size = ctx->cross_axis; if (ctx->widget->computed_style.flex.direction == SV_COLUMN) { @@ -115,7 +115,7 @@ static void FlexBoxLayout_NextLine(LCUI_FlexBoxLayoutContext ctx) } ctx->main_axis = ctx->widget->padding.left; ctx->line = FlexBoxLine_Create(); - LinkedList_Append(&ctx->lines, ctx->line); + list_append(&ctx->lines, ctx->line); } static LCUI_FlexBoxLayoutContext FlexBoxLayout_Begin(LCUI_Widget w, @@ -174,16 +174,16 @@ static LCUI_FlexBoxLayoutContext FlexBoxLayout_Begin(LCUI_Widget w, } ctx->main_size = 0; ctx->cross_size = 0; - LinkedList_Init(&ctx->free_elements); - LinkedList_Init(&ctx->lines); + list_create(&ctx->free_elements); + list_create(&ctx->lines); FlexBoxLayout_NextLine(ctx); return ctx; } static void FlexBoxLayout_End(LCUI_FlexBoxLayoutContext ctx) { - LinkedList_Clear(&ctx->lines, FlexBoxLine_Destroy); - LinkedList_Clear(&ctx->free_elements, NULL); + list_destroy(&ctx->lines, FlexBoxLine_Destroy); + list_destroy(&ctx->free_elements, NULL); free(ctx); } @@ -191,7 +191,7 @@ static void FlexBoxLayout_LoadRows(LCUI_FlexBoxLayoutContext ctx) { LCUI_Widget child; LCUI_FlexBoxLayoutStyle *flex = &ctx->widget->computed_style.flex; - LinkedListNode *node; + list_node_t *node; float basis; float max_main_size = -1; @@ -201,13 +201,13 @@ static void FlexBoxLayout_LoadRows(LCUI_FlexBoxLayoutContext ctx) max_main_size = ctx->widget->box.content.width; } DEBUG_MSG("%s, max_main_size: %g\n", ctx->widget->id, max_main_size); - for (LinkedList_Each(node, &ctx->widget->children)) { + for (list_each(node, &ctx->widget->children)) { child = node->data; if (child->computed_style.display == SV_NONE) { continue; } if (Widget_HasAbsolutePosition(child)) { - LinkedList_Append(&ctx->free_elements, child); + list_append(&ctx->free_elements, child); continue; } /* Clears the auto margin calculated on the last layout */ @@ -246,7 +246,7 @@ static void FlexBoxLayout_LoadRows(LCUI_FlexBoxLayoutContext ctx) ctx->line->main_size += basis; FlexBoxLine_LoadElement(ctx->line, child); } - ctx->main_size = max(ctx->main_size, ctx->line->main_size); + ctx->main_size = y_max(ctx->main_size, ctx->line->main_size); ctx->cross_size += ctx->line->cross_size; DEBUG_MSG("%s,end load, size: (%g, %g)\n", ctx->widget->id, ctx->main_size, ctx->cross_size); @@ -256,7 +256,7 @@ static void FlexBoxLayout_LoadColumns(LCUI_FlexBoxLayoutContext ctx) { LCUI_Widget child; LCUI_FlexBoxLayoutStyle *flex = &ctx->widget->computed_style.flex; - LinkedListNode *node; + list_node_t *node; float basis; float max_main_size = -1; @@ -266,14 +266,14 @@ static void FlexBoxLayout_LoadColumns(LCUI_FlexBoxLayoutContext ctx) max_main_size = ctx->widget->box.content.height; } DEBUG_MSG("max_main_size: %g\n", max_main_size); - for (LinkedList_Each(node, &ctx->widget->children)) { + for (list_each(node, &ctx->widget->children)) { child = node->data; if (child->computed_style.display == SV_NONE) { continue; } if (Widget_HasAbsolutePosition(child)) { - LinkedList_Append(&ctx->free_elements, child); + list_append(&ctx->free_elements, child); continue; } Widget_ComputeFlexBasisStyle(child); @@ -300,7 +300,7 @@ static void FlexBoxLayout_LoadColumns(LCUI_FlexBoxLayoutContext ctx) ctx->line->main_size += basis; FlexBoxLine_LoadElement(ctx->line, child); } - ctx->main_size = max(ctx->main_size, ctx->line->main_size); + ctx->main_size = y_max(ctx->main_size, ctx->line->main_size); ctx->cross_size += ctx->line->cross_size; DEBUG_MSG("main_size: %g\n", ctx->main_size); } @@ -390,7 +390,7 @@ static void FlexBoxLayout_ReflowRow(LCUI_FlexBoxLayoutContext ctx) LCUI_Widget w; LCUI_FlexBoxLayoutStyle *flex; - LinkedListNode *node; + list_node_t *node; free_space = ctx->widget->box.content.width - ctx->line->main_size; if (free_space >= 0) { @@ -403,7 +403,7 @@ static void FlexBoxLayout_ReflowRow(LCUI_FlexBoxLayoutContext ctx) /* flex-grow and flex-shrink */ DEBUG_MSG("%s, free_space: %g\n", ctx->widget->id, free_space); - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { w = node->data; flex = &w->computed_style.flex; if (w->computed_style.height_sizing != LCUI_SIZING_RULE_FIXED) { @@ -436,7 +436,7 @@ static void FlexBoxLayout_ReflowRow(LCUI_FlexBoxLayoutContext ctx) if (free_space > 0 && ctx->line->count_of_auto_margin_items > 0) { main_axis = 0; k = free_space / ctx->line->count_of_auto_margin_items; - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { w = node->data; if (Widget_HasAutoStyle(w, key_margin_left)) { w->margin.left = k; @@ -456,7 +456,7 @@ static void FlexBoxLayout_ReflowRow(LCUI_FlexBoxLayoutContext ctx) main_axis = ctx->widget->padding.left; FlexBoxLayout_ComputeJustifyContent(ctx, &main_axis, &space); - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { w = node->data; main_axis += space; w->layout_x = main_axis; @@ -475,7 +475,7 @@ static void FlexBoxLayout_ReflowColumn(LCUI_FlexBoxLayoutContext ctx) LCUI_Widget w; LCUI_FlexBoxLayoutStyle *flex; - LinkedListNode *node; + list_node_t *node; free_space = ctx->widget->box.content.height - ctx->line->main_size; if (free_space >= 0) { @@ -486,7 +486,7 @@ static void FlexBoxLayout_ReflowColumn(LCUI_FlexBoxLayoutContext ctx) /* flex-grow and flex-shrink */ - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { w = node->data; flex = &w->computed_style.flex; if (w->computed_style.width_sizing != LCUI_SIZING_RULE_FIXED) { @@ -518,7 +518,7 @@ static void FlexBoxLayout_ReflowColumn(LCUI_FlexBoxLayoutContext ctx) if (free_space > 0 && ctx->line->count_of_auto_margin_items > 0) { main_axis = 0; k = free_space / ctx->line->count_of_auto_margin_items; - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { w = node->data; if (Widget_HasAutoStyle(w, key_margin_top)) { w->margin.top = k; @@ -537,7 +537,7 @@ static void FlexBoxLayout_ReflowColumn(LCUI_FlexBoxLayoutContext ctx) main_axis = ctx->widget->padding.top; FlexBoxLayout_ComputeJustifyContent(ctx, &main_axis, &space); - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { w = node->data; main_axis += space; w->layout_y = main_axis; @@ -550,11 +550,11 @@ static void FlexBoxLayout_ReflowColumn(LCUI_FlexBoxLayoutContext ctx) static void FlexBoxLayout_AlignItemsCenter(LCUI_FlexBoxLayoutContext ctx, float base_cross_axis) { - LinkedListNode *node; + list_node_t *node; LCUI_Widget child; if (ctx->widget->computed_style.flex.direction == SV_COLUMN) { - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { child = node->data; child->layout_x = base_cross_axis + @@ -564,7 +564,7 @@ static void FlexBoxLayout_AlignItemsCenter(LCUI_FlexBoxLayoutContext ctx, } return; } - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { child = node->data; child->layout_y = base_cross_axis + @@ -576,11 +576,11 @@ static void FlexBoxLayout_AlignItemsCenter(LCUI_FlexBoxLayoutContext ctx, static void FlexBoxLayout_AlignItemsStretch(LCUI_FlexBoxLayoutContext ctx, float base_cross_axis) { - LinkedListNode *node; + list_node_t *node; LCUI_Widget child; if (ctx->widget->computed_style.flex.direction == SV_COLUMN) { - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { child = node->data; child->layout_x = base_cross_axis; if (Widget_HasAutoStyle(child, key_width)) { @@ -593,7 +593,7 @@ static void FlexBoxLayout_AlignItemsStretch(LCUI_FlexBoxLayoutContext ctx, } return; } - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { child = node->data; child->layout_y = base_cross_axis; if (Widget_HasAutoStyle(child, key_height)) { @@ -607,18 +607,18 @@ static void FlexBoxLayout_AlignItemsStretch(LCUI_FlexBoxLayoutContext ctx, static void FlexBoxLayout_AlignItemsStart(LCUI_FlexBoxLayoutContext ctx, float base_cross_axis) { - LinkedListNode *node; + list_node_t *node; LCUI_Widget child; if (ctx->widget->computed_style.flex.direction == SV_COLUMN) { - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { child = node->data; child->layout_x = base_cross_axis; Widget_UpdateBoxPosition(child); } return; } - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { child = node->data; child->layout_y = base_cross_axis; Widget_UpdateBoxPosition(child); @@ -628,11 +628,11 @@ static void FlexBoxLayout_AlignItemsStart(LCUI_FlexBoxLayoutContext ctx, static void FlexBoxLayout_AlignItemsEnd(LCUI_FlexBoxLayoutContext ctx, float base_cross_axis) { - LinkedListNode *node; + list_node_t *node; LCUI_Widget child; if (ctx->widget->computed_style.flex.direction == SV_COLUMN) { - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { child = node->data; child->layout_x = base_cross_axis + ctx->line->cross_size - @@ -641,7 +641,7 @@ static void FlexBoxLayout_AlignItemsEnd(LCUI_FlexBoxLayoutContext ctx, } return; } - for (LinkedList_Each(node, &ctx->line->elements)) { + for (list_each(node, &ctx->line->elements)) { child = node->data; child->layout_y = base_cross_axis + ctx->line->cross_size - child->box.outer.height; @@ -655,7 +655,7 @@ static void FlexBoxLayout_AlignItems(LCUI_FlexBoxLayoutContext ctx) float free_space = 0; LCUI_Widget w = ctx->widget; - LinkedListNode *node; + list_node_t *node; if (w->computed_style.flex.direction == SV_COLUMN) { cross_axis = w->padding.left; @@ -667,7 +667,7 @@ static void FlexBoxLayout_AlignItems(LCUI_FlexBoxLayoutContext ctx) if (free_space < 0) { free_space = 0; } - for (LinkedList_Each(node, &ctx->lines)) { + for (list_each(node, &ctx->lines)) { ctx->line = node->data; ctx->line->cross_size += free_space / ctx->lines.length; switch (w->computed_style.flex.align_items) { @@ -698,10 +698,10 @@ static void FlexBoxLayout_AlignItems(LCUI_FlexBoxLayoutContext ctx) static void FlexBoxLayout_Reflow(LCUI_FlexBoxLayoutContext ctx) { LCUI_Widget w = ctx->widget; - LinkedListNode *node; + list_node_t *node; DEBUG_MSG("widget: %s, start\n", w->id); - for (LinkedList_Each(node, &ctx->lines)) { + for (list_each(node, &ctx->lines)) { ctx->line = node->data; if (w->computed_style.flex.direction == SV_COLUMN) { FlexBoxLayout_ReflowColumn(ctx); @@ -715,8 +715,8 @@ static void FlexBoxLayout_Reflow(LCUI_FlexBoxLayoutContext ctx) static void FlexBoxLayout_ReflowFreeElements(LCUI_FlexBoxLayoutContext ctx) { - LinkedListNode *node; - for (LinkedList_Each(node, &ctx->free_elements)) { + list_node_t *node; + for (list_each(node, &ctx->free_elements)) { Widget_AutoReflow(node->data, LCUI_LAYOUT_RULE_FIXED); } } @@ -739,18 +739,18 @@ static void FlexBoxLayout_ApplySize(LCUI_FlexBoxLayoutContext ctx) width = w->box.content.width; w->proto->autosize(w, &width, &height, ctx->rule); width = w->box.content.width; - height = max(height, ctx->main_size); + height = y_max(height, ctx->main_size); break; case LCUI_LAYOUT_RULE_FIXED_HEIGHT: height = w->box.content.height; w->proto->autosize(w, &width, &height, ctx->rule); height = w->box.content.height; - width = max(width, ctx->cross_size); + width = y_max(width, ctx->cross_size); break; default: w->proto->autosize(w, &width, &height, ctx->rule); - height = max(height, ctx->main_size); - width = max(width, ctx->cross_size); + height = y_max(height, ctx->main_size); + width = y_max(width, ctx->cross_size); break; } w->width = ToBorderBoxWidth(w, width); @@ -773,18 +773,18 @@ static void FlexBoxLayout_ApplySize(LCUI_FlexBoxLayoutContext ctx) width = w->box.content.width; w->proto->autosize(w, &width, &height, ctx->rule); width = w->box.content.width; - height = max(height, ctx->cross_size); + height = y_max(height, ctx->cross_size); break; case LCUI_LAYOUT_RULE_FIXED_HEIGHT: height = w->box.content.height; w->proto->autosize(w, &width, &height, ctx->rule); - width = max(width, ctx->main_size); + width = y_max(width, ctx->main_size); height = w->box.content.height; break; default: w->proto->autosize(w, &width, &height, ctx->rule); - width = max(width, ctx->main_size); - height = max(height, ctx->cross_size); + width = y_max(width, ctx->main_size); + height = y_max(height, ctx->cross_size); break; } w->width = ToBorderBoxWidth(w, width); diff --git a/lib/ui/src/metrics.c b/lib/ui/src/metrics.c index a49a1e14..de64c584 100644 --- a/lib/ui/src/metrics.c +++ b/lib/ui/src/metrics.c @@ -31,7 +31,7 @@ #include #include -#include +#include #include static LCUI_MetricsRec metrics; @@ -76,15 +76,15 @@ float LCUIMetrics_ComputeStyle(LCUI_Style style) int LCUIMetrics_ComputeActual(float value, LCUI_StyleType type) { - return iround(LCUIMetrics_Compute(value, type) * metrics.scale); + return y_iround(LCUIMetrics_Compute(value, type) * metrics.scale); } void LCUIMetrics_ComputeRectActual(LCUI_Rect *dst, const LCUI_RectF *src) { - dst->x = iround(src->x * metrics.scale); - dst->y = iround(src->y * metrics.scale); - dst->width = iround(src->width * metrics.scale); - dst->height = iround(src->height * metrics.scale); + dst->x = y_iround(src->x * metrics.scale); + dst->y = y_iround(src->y * metrics.scale); + dst->width = y_iround(src->width * metrics.scale); + dst->height = y_iround(src->height * metrics.scale); } float LCUIMetrics_GetScale(void) @@ -134,8 +134,8 @@ void LCUIMetrics_SetDpi(float dpi) void LCUIMetrics_SetScale(float scale) { - scale = max(0.5f, scale); - scale = min(5.0f, scale); + scale = y_max(0.5f, scale); + scale = y_min(5.0f, scale); metrics.scale = scale; } diff --git a/lib/ui/src/widget_attribute.c b/lib/ui/src/widget_attribute.c index c19c33df..5e52cbe3 100644 --- a/lib/ui/src/widget_attribute.c +++ b/lib/ui/src/widget_attribute.c @@ -39,7 +39,7 @@ #include static struct LCUI_WidgetAttribleModule { - DictType dt_attributes; + dict_type_t dt_attributes; LCUI_BOOL available; } self; @@ -61,14 +61,14 @@ int Widget_SetAttributeEx(LCUI_Widget w, const char *name, void *value, LCUI_WidgetAttribute attr; if (!self.available) { - Dict_InitStringKeyType(&self.dt_attributes); - self.dt_attributes.valDestructor = OnClearWidgetAttribute; + dict_init_string_key_type(&self.dt_attributes); + self.dt_attributes.val_destructor = OnClearWidgetAttribute; self.available = TRUE; } if (!w->attributes) { - w->attributes = Dict_Create(&self.dt_attributes, NULL); + w->attributes = dict_create(&self.dt_attributes, NULL); } - attr = Dict_FetchValue(w->attributes, name); + attr = dict_fetch_value(w->attributes, name); if (attr) { if (attr->value.destructor) { attr->value.destructor(attr->value.data); @@ -76,7 +76,7 @@ int Widget_SetAttributeEx(LCUI_Widget w, const char *name, void *value, } else { attr = NEW(LCUI_WidgetAttributeRec, 1); attr->name = strdup2(name); - Dict_Add(w->attributes, attr->name, attr); + dict_add(w->attributes, attr->name, attr); } attr->value.data = value; attr->value.type = value_type; @@ -119,7 +119,7 @@ const char *Widget_GetAttribute(LCUI_Widget w, const char *name) if (!w->attributes) { return NULL; } - attr = Dict_FetchValue(w->attributes, name); + attr = dict_fetch_value(w->attributes, name); if (attr) { return attr->value.string; } @@ -129,7 +129,7 @@ const char *Widget_GetAttribute(LCUI_Widget w, const char *name) void Widget_DestroyAttributes(LCUI_Widget w) { if (w->attributes) { - Dict_Release(w->attributes); + dict_destroy(w->attributes); } w->attributes = NULL; } diff --git a/lib/ui/src/widget_background.c b/lib/ui/src/widget_background.c index 9366a35d..9bae574d 100644 --- a/lib/ui/src/widget_background.c +++ b/lib/ui/src/widget_background.c @@ -33,9 +33,9 @@ #include #include #include -#include #include #include +#include #include "widget_background.h" #define ComputeActual LCUIMetrics_ComputeActual @@ -43,7 +43,7 @@ typedef struct ImageCacheRec_ { char *path; LCUI_Graph image; - LinkedList refs; + list_t refs; } ImageCacheRec, *ImageCache; typedef struct ImageRefRec_ { @@ -53,20 +53,20 @@ typedef struct ImageRefRec_ { static struct LCUI_WidgetBackgroundModule { LCUI_BOOL active; - DictType dtype; - Dict *images; - RBTree refs; + dict_type_t dtype; + dict_t *images; + rbtree_t refs; } self; static void DestroyImageCache(ImageCache cache) { - LinkedListNode *node; - while ((node = LinkedList_GetNode(&cache->refs, 0))) { + list_node_t *node; + while ((node = list_get_node(&cache->refs, 0))) { LCUI_Widget w = node->data; - RBTree_CustomErase(&self.refs, node->data); + rbtree_delete_by_keydata(&self.refs, node->data); Widget_UnsetStyle(w, key_background_image); Graph_Init(&w->computed_style.background.image); - LinkedList_DeleteNode(&cache->refs, node); + list_delete_node(&cache->refs, node); } Graph_Free(&cache->image); free(cache->path); @@ -84,39 +84,39 @@ static void AddImageRef(LCUI_Widget widget, ImageCache cache) ASSIGN(ref, ImageRef); ref->cache = cache; ref->widget = widget; - RBTree_CustomInsert(&self.refs, widget, ref); - LinkedList_Append(&cache->refs, widget); + rbtree_insert_by_keydata(&self.refs, widget, ref); + list_append(&cache->refs, widget); } static ImageRef GetImageRef(LCUI_Widget widget) { - return RBTree_CustomGetData(&self.refs, widget); + return rbtree_get_data_by_keydata(&self.refs, widget); } static void DeleteImageRef(LCUI_Widget widget) { ImageRef ref; ImageCache cache; - LinkedListNode *node; + list_node_t *node; ref = GetImageRef(widget); if (!ref) { return; } cache = ref->cache; - for (LinkedList_Each(node, &cache->refs)) { + for (list_each(node, &cache->refs)) { LCUI_Widget w = node->data; if (w != widget) { continue; } - RBTree_CustomErase(&self.refs, node->data); + rbtree_delete_by_keydata(&self.refs, node->data); Widget_UnsetStyle(w, key_background_image); Graph_Init(&w->computed_style.background.image); - LinkedList_DeleteNode(&cache->refs, node); + list_delete_node(&cache->refs, node); break; } - RBTree_CustomErase(&self.refs, widget); + rbtree_delete_by_keydata(&self.refs, widget); if (cache->refs.length < 1) { - Dict_Delete(self.images, cache->path); + dict_delete(self.images, cache->path); } } @@ -134,8 +134,8 @@ static void ExecLoadImage(void *arg1, void *arg2) cache = NEW(ImageCacheRec, 1); cache->image = image; cache->path = strdup2(path); - LinkedList_Init(&cache->refs); - if (Dict_Add(self.images, cache->path, cache) == 0) { + list_create(&cache->refs); + if (dict_add(self.images, cache->path, cache) == 0) { AddImageRef(w, cache); } else { DestroyImageCache(cache); @@ -175,7 +175,7 @@ static void AsyncLoadImage(LCUI_Widget widget, const char *path) DeleteImageRef(widget); } } - cache = Dict_FetchValue(self.images, path); + cache = dict_fetch_value(self.images, path); if (cache) { AddImageRef(widget, cache); Graph_Quote(&widget->computed_style.background.image, @@ -192,19 +192,19 @@ static void AsyncLoadImage(LCUI_Widget widget, const char *path) void LCUIWidget_InitImageLoader(void) { - RBTree_Init(&self.refs); - Dict_InitStringKeyType(&self.dtype); - self.dtype.valDestructor = ImageCacheDestructor; - self.images = Dict_Create(&self.dtype, NULL); - RBTree_OnCompare(&self.refs, OnCompareWidget); - RBTree_OnDestroy(&self.refs, free); + rbtree_init(&self.refs); + dict_init_string_key_type(&self.dtype); + self.dtype.val_destructor = ImageCacheDestructor; + self.images = dict_create(&self.dtype, NULL); + rbtree_set_compare_func(&self.refs, OnCompareWidget); + rbtree_set_destroy_func(&self.refs, free); self.active = TRUE; } void LCUIWidget_FreeImageLoader(void) { - Dict_Release(self.images); - RBTree_Destroy(&self.refs); + dict_destroy(self.images); + rbtree_destroy(&self.refs); self.images = NULL; self.active = FALSE; } diff --git a/lib/ui/src/widget_base.c b/lib/ui/src/widget_base.c index ea564d83..2c95feba 100644 --- a/lib/ui/src/widget_base.c +++ b/lib/ui/src/widget_base.c @@ -41,7 +41,7 @@ static struct LCUI_WidgetModule { LCUI_Widget root; /**< 根级部件 */ - LinkedList trash; /**< 待删除的部件列表 */ + list_t trash; /**< 待删除的部件列表 */ } LCUIWidget; LCUI_Widget LCUIWidget_GetRoot(void) @@ -52,13 +52,13 @@ LCUI_Widget LCUIWidget_GetRoot(void) size_t LCUIWidget_ClearTrash(void) { size_t count; - LinkedListNode *node; + list_node_t *node; node = LCUIWidget.trash.head.next; count = LCUIWidget.trash.length; while (node) { - LinkedListNode *next = node->next; - LinkedList_Unlink(&LCUIWidget.trash, node); + list_node_t *next = node->next; + list_unlink(&LCUIWidget.trash, node); Widget_ExecDestroy(node->data); node = next; } @@ -71,7 +71,7 @@ static void Widget_AddToTrash(LCUI_Widget w) if (Widget_Unlink(w) != 0) { return; } - LinkedList_AppendNode(&LCUIWidget.trash, &w->node); + list_append_node(&LCUIWidget.trash, &w->node); Widget_PostSurfaceEvent(w, LCUI_WEVENT_UNLINK, TRUE); } @@ -88,8 +88,8 @@ static void Widget_Init(LCUI_Widget widget) widget->computed_style.position = SV_STATIC; widget->computed_style.pointer_events = SV_INHERIT; widget->computed_style.box_sizing = SV_CONTENT_BOX; - LinkedList_Init(&widget->children); - LinkedList_Init(&widget->children_show); + list_create(&widget->children); + list_create(&widget->children_show); widget->node.data = widget; widget->node_show.data = widget; widget->node.next = widget->node.prev = NULL; @@ -164,7 +164,7 @@ void Widget_Destroy(LCUI_Widget w) } if (w->parent) { LCUI_Widget child; - LinkedListNode *node; + list_node_t *node; /* Update the index of the siblings behind it */ node = w->node.next; @@ -186,7 +186,7 @@ void Widget_Empty(LCUI_Widget w) { LCUI_Widget root = w; LCUI_Widget child; - LinkedListNode *node; + list_node_t *node; LCUI_WidgetEventRec ev; while (root->parent) { @@ -197,7 +197,7 @@ void Widget_Empty(LCUI_Widget w) return; } LCUI_InitWidgetEvent(&ev, "unlink"); - for (LinkedList_Each(node, &w->children)) { + for (list_each(node, &w->children)) { child = node->data; Widget_TriggerEvent(child, &ev, NULL); if (child->parent == root) { @@ -207,8 +207,8 @@ void Widget_Empty(LCUI_Widget w) child->state = LCUI_WSTATE_DELETED; child->parent = NULL; } - LinkedList_ClearData(&w->children_show, NULL); - LinkedList_Concat(&LCUIWidget.trash, &w->children); + list_destroy_without_node(&w->children_show, NULL); + list_concat(&LCUIWidget.trash, &w->children); Widget_InvalidateArea(w, NULL, SV_GRAPH_BOX); Widget_UpdateStyle(w, TRUE); } @@ -259,7 +259,7 @@ void Widget_SetTitleW(LCUI_Widget w, const wchar_t *title) LCUI_BOOL Widget_InVisibleArea(LCUI_Widget w) { - LinkedListNode *node; + list_node_t *node; LCUI_RectF rect; LCUI_Widget self, parent, child; LCUI_WidgetStyle *style; @@ -319,7 +319,7 @@ int Widget_SetRules(LCUI_Widget w, const LCUI_WidgetRulesRec *rules) data = (LCUI_WidgetRulesData)w->rules; if (data) { - Dict_Release(data->style_cache); + dict_destroy(data->style_cache); free(data); w->rules = NULL; } @@ -390,18 +390,18 @@ void Widget_SortChildrenShow(LCUI_Widget w) { LCUI_Widget child, target; LCUI_WidgetStyle *s, *ts; - LinkedListNode *node, *target_node; - LinkedList *list; + list_node_t *node, *target_node; + list_t *list; list = &w->children_show; - LinkedList_ClearData(list, NULL); - for (LinkedList_Each(node, &w->children)) { + list_destroy_without_node(list, NULL); + for (list_each(node, &w->children)) { child = node->data; s = &child->computed_style; if (child->state < LCUI_WSTATE_READY) { continue; } - for (LinkedList_Each(target_node, list)) { + for (list_each(target_node, list)) { target = target_node->data; ts = &target->computed_style; if (s->z_index == ts->z_index) { @@ -415,12 +415,12 @@ void Widget_SortChildrenShow(LCUI_Widget w) } else if (s->z_index < ts->z_index) { continue; } - LinkedList_Link(list, target_node->prev, + list_link(list, target_node->prev, &child->node_show); break; } if (!target_node) { - LinkedList_AppendNode(list, &child->node_show); + list_append_node(list, &child->node_show); } } } @@ -547,7 +547,7 @@ void Widget_UpdateBoxSize(LCUI_Widget w) void LCUIWidget_InitBase(void) { - LinkedList_Init(&LCUIWidget.trash); + list_create(&LCUIWidget.trash); LCUIWidget.root = LCUIWidget_New("root"); Widget_SetTitleW(LCUIWidget.root, L"LCUI Display"); } diff --git a/lib/ui/src/widget_border.c b/lib/ui/src/widget_border.c index 180dfe66..81d94f6c 100644 --- a/lib/ui/src/widget_border.c +++ b/lib/ui/src/widget_border.c @@ -134,7 +134,7 @@ static unsigned int ComputeActual(float width) void Widget_ComputeBorder(LCUI_Widget w, LCUI_Border *b) { LCUI_BorderStyle *s; - float r = min(w->width, w->height) / 2.0f; + float r = y_min(w->width, w->height) / 2.0f; s = &w->computed_style.border; b->top.color = s->top.color; @@ -149,10 +149,10 @@ void Widget_ComputeBorder(LCUI_Widget w, LCUI_Border *b) b->left.width = ComputeActual(s->left.width); b->right.width = ComputeActual(s->right.width); b->bottom.width = ComputeActual(s->bottom.width); - b->top_left_radius = ComputeActual(min(s->top_left_radius, r)); - b->top_right_radius = ComputeActual(min(s->top_right_radius, r)); - b->bottom_left_radius = ComputeActual(min(s->bottom_left_radius, r)); - b->bottom_right_radius = ComputeActual(min(s->bottom_right_radius, r)); + b->top_left_radius = ComputeActual(y_min(s->top_left_radius, r)); + b->top_right_radius = ComputeActual(y_min(s->top_right_radius, r)); + b->bottom_left_radius = ComputeActual(y_min(s->bottom_left_radius, r)); + b->bottom_right_radius = ComputeActual(y_min(s->bottom_right_radius, r)); } void Widget_PaintBorder(LCUI_Widget w, LCUI_PaintContext paint, diff --git a/lib/ui/src/widget_class.c b/lib/ui/src/widget_class.c index bd50d4a8..47abde54 100644 --- a/lib/ui/src/widget_class.c +++ b/lib/ui/src/widget_class.c @@ -37,13 +37,13 @@ static void Widget_MarkChildrenRefreshByClasses(LCUI_Widget w) { - LinkedListNode *node; + list_node_t *node; if (w->rules && w->rules->ignore_classes_change) { return; } Widget_AddTask(w, LCUI_WTASK_REFRESH_STYLE); - for (LinkedList_Each(node, &w->children)) { + for (list_each(node, &w->children)) { Widget_MarkChildrenRefreshByClasses(node->data); } } diff --git a/lib/ui/src/widget_diff.c b/lib/ui/src/widget_diff.c index 595b88a5..b7173562 100644 --- a/lib/ui/src/widget_diff.c +++ b/lib/ui/src/widget_diff.c @@ -100,7 +100,7 @@ INLINE void Widget_AddReflowTaskToParent(LCUI_Widget w) int Widget_EndStyleDiff(LCUI_Widget w, LCUI_WidgetStyleDiff diff) { - LinkedListNode *node; + list_node_t *node; const LCUI_WidgetStyle *style = &w->computed_style; if (style->visible != diff->visible) { @@ -118,7 +118,7 @@ int Widget_EndStyleDiff(LCUI_Widget w, LCUI_WidgetStyleDiff diff) Widget_UpdateBoxPosition(w); if (MEMCMP(&diff->box.padding, &w->box.padding)) { w->invalid_area_type = LCUI_INVALID_AREA_TYPE_CANVAS_BOX; - for (LinkedList_Each(node, &w->children)) { + for (list_each(node, &w->children)) { Widget_AddTask(node->data, LCUI_WTASK_POSITION); Widget_AddTask(node->data, LCUI_WTASK_RESIZE); } diff --git a/lib/ui/src/widget_event.c b/lib/ui/src/widget_event.c index e5f5c0d1..546760fc 100644 --- a/lib/ui/src/widget_event.c +++ b/lib/ui/src/widget_event.c @@ -46,9 +46,9 @@ #define DBLCLICK_INTERVAL 500 typedef struct TouchCapturerRec_ { - LinkedList points; + list_t points; LCUI_Widget widget; - LinkedListNode node; + list_node_t node; } TouchCapturerRec, *TouchCapturer; typedef struct WidgetEventHandlerRec_ { @@ -71,7 +71,7 @@ enum WidgetStatusType { /** 部件事件记录结点 */ typedef struct WidgetEventRecordRec_ { LCUI_Widget widget; /**< 所属部件 */ - LinkedList records; /**< 事件记录列表 */ + list_t records; /**< 事件记录列表 */ } WidgetEventRecordRec, *WidgetEventRecord; /** 事件标识号与名称的映射记录 */ @@ -91,14 +91,14 @@ typedef struct ClickRecord_ { /** 当前功能模块的相关数据 */ static struct LCUIWidgetEvnetModule { LCUI_Widget mouse_capturer; /**< 占用鼠标的部件 */ - LinkedList touch_capturers; /**< 触点占用记录 */ + list_t touch_capturers; /**< 触点占用记录 */ LCUI_Widget targets[WST_TOTAL]; /**< 相关的部件 */ - LinkedList events; /**< 已绑定的事件 */ - LinkedList event_mappings; /**< 事件标识号和名称映射记录列表 */ - RBTree event_records; /**< 当前正执行的事件的记录 */ - RBTree event_names; /**< 事件名称表,以标识号作为索引 */ - DictType event_ids_type; - Dict *event_ids; /**< 事件标识号表,以事件名称作为索引 */ + list_t events; /**< 已绑定的事件 */ + list_t event_mappings; /**< 事件标识号和名称映射记录列表 */ + rbtree_t event_records; /**< 当前正执行的事件的记录 */ + rbtree_t event_names; /**< 事件名称表,以标识号作为索引 */ + dict_type_t event_ids_type; + dict_t *event_ids; /**< 事件标识号表,以事件名称作为索引 */ int base_event_id; /**< 事件标识号计数器 */ ClickRecord click; /**< 上次鼠标点击记录 */ LCUI_Mutex mutex; /**< 互斥锁 */ @@ -147,7 +147,7 @@ static void DirectDestroyWidgetEventPack(void *data) static void DestoryWidgetEventRecord(void *data) { WidgetEventRecord record = data; - LinkedList_Clear(&record->records, DirectDestroyWidgetEventPack); + list_destroy(&record->records, DirectDestroyWidgetEventPack); free(record); } @@ -200,14 +200,14 @@ static void Widget_AddEventRecord(LCUI_Widget widget, LCUI_WidgetEventPack pack) WidgetEventRecord record; LCUIMutex_Lock(&self.mutex); - record = RBTree_CustomGetData(&self.event_records, widget); + record = rbtree_get_data_by_keydata(&self.event_records, widget); if (!record) { record = NEW(WidgetEventRecordRec, 1); - LinkedList_Init(&record->records); + list_create(&record->records); record->widget = widget; - RBTree_CustomInsert(&self.event_records, widget, record); + rbtree_insert_by_keydata(&self.event_records, widget, record); } - LinkedList_Append(&record->records, pack); + list_append(&record->records, pack); LCUIMutex_Unlock(&self.mutex); } @@ -217,18 +217,18 @@ static int Widget_DeleteEventRecord(LCUI_Widget widget, { int ret = 0; WidgetEventRecord record; - LinkedListNode *node, *prev; + list_node_t *node, *prev; LCUIMutex_Lock(&self.mutex); - record = RBTree_CustomGetData(&self.event_records, widget); + record = rbtree_get_data_by_keydata(&self.event_records, widget); if (!record) { LCUIMutex_Unlock(&self.mutex); return -1; } - for (LinkedList_Each(node, &record->records)) { + for (list_each(node, &record->records)) { prev = node->prev; if (node->data == pack) { - LinkedList_DeleteNode(&record->records, node); + list_delete_node(&record->records, node); node = prev; ret = 1; } @@ -307,33 +307,33 @@ static void DestroyWidgetEventPack(void *arg) static void DestroyTouchCapturer(void *arg) { TouchCapturer tc = arg; - LinkedList_Clear(&tc->points, free); + list_destroy(&tc->points, free); tc->widget = NULL; free(tc); } #define TouchCapturers_Clear(LIST) \ \ - LinkedList_ClearData(LIST, DestroyTouchCapturer) + list_destroy_without_node(LIST, DestroyTouchCapturer) -static int TouchCapturers_Add(LinkedList *list, LCUI_Widget w, int point_id) +static int TouchCapturers_Add(list_t *list, LCUI_Widget w, int point_id) { int *data; TouchCapturer tc = NULL; - LinkedListNode *node, *ptnode; + list_node_t *node, *ptnode; if (point_id < 0) { tc = NEW(TouchCapturerRec, 1); tc->widget = w; - LinkedList_Init(&tc->points); + list_create(&tc->points); TouchCapturers_Clear(list); - LinkedList_Append(list, tc); + list_append(list, tc); return 0; } /* 获取该部件的触点捕捉记录 */ - for (LinkedList_Each(node, list)) { + for (list_each(node, list)) { tc = node->data; /* 清除与该触点绑定的其它捕捉记录 */ - for (LinkedList_Each(ptnode, &tc->points)) { + for (list_each(ptnode, &tc->points)) { if (point_id == *(int *)ptnode->data) { if (tc->widget == w) { return 0; @@ -350,21 +350,21 @@ static int TouchCapturers_Add(LinkedList *list, LCUI_Widget w, int point_id) tc = NEW(TouchCapturerRec, 1); tc->widget = w; tc->node.data = tc; - LinkedList_Init(&tc->points); - LinkedList_AppendNode(list, &tc->node); + list_create(&tc->points); + list_append_node(list, &tc->node); } /* 追加触点捕捉记录 */ data = NEW(int, 1); *data = point_id; - LinkedList_Append(&tc->points, data); + list_append(&tc->points, data); return 0; } -static int TouchCapturers_Delete(LinkedList *list, LCUI_Widget w, int point_id) +static int TouchCapturers_Delete(list_t *list, LCUI_Widget w, int point_id) { TouchCapturer tc = NULL; - LinkedListNode *node, *ptnode; - for (LinkedList_Each(node, list)) { + list_node_t *node, *ptnode; + for (list_each(node, list)) { tc = node->data; if (tc->widget == w) { break; @@ -374,17 +374,17 @@ static int TouchCapturers_Delete(LinkedList *list, LCUI_Widget w, int point_id) return -1; } if (point_id < 0) { - LinkedList_Clear(&tc->points, free); + list_destroy(&tc->points, free); } else { - for (LinkedList_Each(ptnode, &tc->points)) { + for (list_each(ptnode, &tc->points)) { if (*(int *)ptnode->data == point_id) { free(node->data); - LinkedList_DeleteNode(&tc->points, ptnode); + list_delete_node(&tc->points, ptnode); } } } if (tc->points.length == 0) { - LinkedList_Unlink(&self.touch_capturers, &tc->node); + list_unlink(&self.touch_capturers, &tc->node); free(tc); } return 0; @@ -395,16 +395,16 @@ int LCUIWidget_SetEventName(int event_id, const char *event_name) int ret; EventMapping mapping; LCUIMutex_Lock(&self.mutex); - if (Dict_FetchValue(self.event_ids, event_name)) { + if (dict_fetch_value(self.event_ids, event_name)) { LCUIMutex_Unlock(&self.mutex); return -1; } mapping = malloc(sizeof(EventMappingRec)); mapping->name = strdup2(event_name); mapping->id = event_id; - LinkedList_Append(&self.event_mappings, mapping); - RBTree_Insert(&self.event_names, event_id, mapping); - ret = Dict_Add(self.event_ids, mapping->name, mapping); + list_append(&self.event_mappings, mapping); + rbtree_insert_by_key(&self.event_names, event_id, mapping); + ret = dict_add(self.event_ids, mapping->name, mapping); LCUIMutex_Unlock(&self.mutex); return ret; } @@ -418,7 +418,7 @@ const char *LCUIWidget_GetEventName(int event_id) { EventMapping mapping; LCUIMutex_Lock(&self.mutex); - mapping = RBTree_GetData(&self.event_names, event_id); + mapping = rbtree_get_data_by_key(&self.event_names, event_id); LCUIMutex_Unlock(&self.mutex); return mapping ? mapping->name : NULL; } @@ -427,7 +427,7 @@ int LCUIWidget_GetEventId(const char *event_name) { EventMapping mapping; LCUIMutex_Lock(&self.mutex); - mapping = Dict_FetchValue(self.event_ids, event_name); + mapping = dict_fetch_value(self.event_ids, event_name); LCUIMutex_Unlock(&self.mutex); return mapping ? mapping->id : -1; } @@ -493,7 +493,7 @@ int Widget_UnbindEvent(LCUI_Widget widget, const char *event_name, static LCUI_Widget Widget_GetNextAt(LCUI_Widget widget, int x, int y) { LCUI_Widget w; - LinkedListNode *node; + list_node_t *node; node = &widget->node; for (node = node->next; node; node = node->next) { @@ -574,7 +574,7 @@ static int Widget_TriggerEventEx(LCUI_Widget widget, LCUI_WidgetEventPack pack) x = pointer_x - x; y = pointer_y - y; /* 从当前部件后面找到当前坐标点命中的兄弟部件 */ - w = Widget_GetNextAt(widget, iround(x), iround(y)); + w = Widget_GetNextAt(widget, y_iround(x), y_iround(y)); if (!w) { break; } @@ -643,7 +643,7 @@ int Widget_TriggerEvent(LCUI_Widget widget, LCUI_WidgetEvent e, void *data) int Widget_StopEventPropagation(LCUI_Widget widget) { - LinkedListNode *node; + list_node_t *node; WidgetEventRecord record; LCUI_WidgetEventPack pack; @@ -651,12 +651,12 @@ int Widget_StopEventPropagation(LCUI_Widget widget) return 0; } LCUIMutex_Lock(&self.mutex); - record = RBTree_CustomGetData(&self.event_records, widget); + record = rbtree_get_data_by_keydata(&self.event_records, widget); if (!record) { LCUIMutex_Unlock(&self.mutex); return -1; } - for (LinkedList_Each(node, &record->records)) { + for (list_each(node, &record->records)) { pack = node->data; pack->event.cancel_bubble = TRUE; } @@ -701,9 +701,9 @@ static LCUI_Widget Widget_GetEventTarget(LCUI_Widget widget, float x, float y, LCUI_Widget child; LCUI_Widget target = NULL; - LinkedListNode *node; + list_node_t *node; - for (LinkedList_Each(node, &widget->children_show)) { + for (list_each(node, &widget->children_show)) { child = node->data; if (!child->computed_style.visible || child->state != LCUI_WSTATE_NORMAL || @@ -840,7 +840,7 @@ static void ClearFocusTarget(LCUI_Widget target) void LCUIWidget_ClearEventTarget(LCUI_Widget widget) { - LinkedListNode *node; + list_node_t *node; WidgetEventRecord record; LCUI_WidgetEventPack pack; @@ -848,9 +848,9 @@ void LCUIWidget_ClearEventTarget(LCUI_Widget widget) return; } LCUIMutex_Lock(&self.mutex); - record = RBTree_CustomGetData(&self.event_records, widget); + record = rbtree_get_data_by_keydata(&self.event_records, widget); if (record) { - for (LinkedList_Each(node, &record->records)) { + for (list_each(node, &record->records)) { pack = node->data; pack->widget = NULL; pack->event.cancel_bubble = TRUE; @@ -917,8 +917,8 @@ static void OnMouseEvent(LCUI_SysEvent sys_ev, void *arg) root = LCUIWidget_GetRoot(); LCUICursor_GetPos(&pos); scale = LCUIMetrics_GetScale(); - pos.x = iround(pos.x / scale); - pos.y = iround(pos.y / scale); + pos.x = y_iround(pos.x / scale); + pos.y = y_iround(pos.y / scale); if (self.mouse_capturer) { target = self.mouse_capturer; } else { @@ -946,14 +946,14 @@ static void OnMouseEvent(LCUI_SysEvent sys_ev, void *arg) if (ev.button.button == LCUI_KEY_LEFTBUTTON && self.click.widget == target) { int delta; - delta = (int)LCUI_GetTimeDelta(self.click.time); + delta = (int)get_time_delta(self.click.time); self.click.interval = delta; } else if (ev.button.button == LCUI_KEY_LEFTBUTTON && self.click.widget != target) { self.click.x = pos.x; self.click.y = pos.y; } - self.click.time = LCUI_GetTime(); + self.click.time = get_time_ms(); self.click.widget = target; Widget_OnMouseDownEvent(target); LCUIWidget_SetFocus(target); @@ -1081,19 +1081,19 @@ static void ConvertTouchPoint(LCUI_TouchPoint point) break; } scale = LCUIMetrics_GetScale(); - point->x = iround(point->x / scale); - point->y = iround(point->y / scale); + point->x = y_iround(point->x / scale); + point->y = y_iround(point->y / scale); } /** 分发触控事件给对应的部件 */ -static int DispatchTouchEvent(LinkedList *capturers, LCUI_TouchPoint points, +static int DispatchTouchEvent(list_t *capturers, LCUI_TouchPoint points, int n_points) { int i, count; float scale; LCUI_WidgetEventRec ev = { 0 }; LCUI_Widget target, root, w; - LinkedListNode *node, *ptnode; + list_node_t *node, *ptnode; root = LCUIWidget_GetRoot(); scale = LCUIMetrics_GetScale(); @@ -1102,8 +1102,8 @@ static int DispatchTouchEvent(LinkedList *capturers, LCUI_TouchPoint points, ev.touch.points = NEW(LCUI_TouchPointRec, n_points); /* 先将各个触点按命中的部件进行分组 */ for (i = 0; i < n_points; ++i) { - target = Widget_At(root, iround(points[i].x / scale), - iround(points[i].y / scale)); + target = Widget_At(root, y_iround(points[i].x / scale), + y_iround(points[i].y / scale)); if (!target) { continue; } @@ -1120,10 +1120,10 @@ static int DispatchTouchEvent(LinkedList *capturers, LCUI_TouchPoint points, count = 0; ev.touch.n_points = 0; /* 然后向命中的部件发送触控事件 */ - for (LinkedList_Each(node, capturers)) { + for (list_each(node, capturers)) { TouchCapturer tc = node->data; for (i = 0; i < n_points; ++i) { - for (LinkedList_Each(ptnode, &tc->points)) { + for (list_each(ptnode, &tc->points)) { LCUI_TouchPoint point; if (points[i].id != *(int *)ptnode->data) { continue; @@ -1149,16 +1149,16 @@ static int DispatchTouchEvent(LinkedList *capturers, LCUI_TouchPoint points, static void OnTouch(LCUI_SysEvent sys_ev, void *arg) { int i, n; - LinkedList capturers; + list_t capturers; LCUI_TouchPoint points; - LinkedListNode *node, *ptnode; + list_node_t *node, *ptnode; n = sys_ev->touch.n_points; points = sys_ev->touch.points; - LinkedList_Init(&capturers); + list_create(&capturers); LCUIMutex_Lock(&self.mutex); /* 合并现有的触点捕捉记录 */ - for (LinkedList_Each(node, &self.touch_capturers)) { + for (list_each(node, &self.touch_capturers)) { TouchCapturer tc = node->data; for (i = 0; i < n; ++i) { /* 如果没有触点记录,则说明是捕获全部触点 */ @@ -1167,7 +1167,7 @@ static void OnTouch(LCUI_SysEvent sys_ev, void *arg) points[i].id); continue; } - for (LinkedList_Each(ptnode, &tc->points)) { + for (list_each(ptnode, &tc->points)) { if (points[i].id != *(int *)ptnode->data) { continue; } @@ -1253,7 +1253,7 @@ static void BindSysEvent(int e, LCUI_SysEventFunc func) { int *id = malloc(sizeof(int)); *id = LCUI_BindEvent(e, func, NULL, NULL); - LinkedList_Append(&self.events, id); + list_append(&self.events, id); } void LCUIWidget_InitEvent(void) @@ -1292,10 +1292,10 @@ void LCUIWidget_InitEvent(void) { LCUI_WEVENT_TITLE, "title" } }; LCUIMutex_Init(&self.mutex); - RBTree_Init(&self.event_names); - RBTree_Init(&self.event_records); - LinkedList_Init(&self.events); - LinkedList_Init(&self.event_mappings); + rbtree_init(&self.event_names); + rbtree_init(&self.event_records); + list_create(&self.events); + list_create(&self.event_mappings); self.targets[WST_ACTIVE] = NULL; self.targets[WST_HOVER] = NULL; self.targets[WST_FOCUS] = NULL; @@ -1306,8 +1306,8 @@ void LCUIWidget_InitEvent(void) self.click.widget = NULL; self.click.interval = DBLCLICK_INTERVAL; self.base_event_id = LCUI_WEVENT_USER + 1000; - Dict_InitStringKeyType(&self.event_ids_type); - self.event_ids = Dict_Create(&self.event_ids_type, NULL); + dict_init_string_key_type(&self.event_ids_type); + self.event_ids = dict_create(&self.event_ids_type, NULL); n = sizeof(mappings) / sizeof(mappings[0]); for (i = 0; i < n; ++i) { LCUIWidget_SetEventName(mappings[i].id, mappings[i].name); @@ -1321,25 +1321,25 @@ void LCUIWidget_InitEvent(void) BindSysEvent(LCUI_KEYUP, OnKeyboardEvent); BindSysEvent(LCUI_TOUCH, OnTouch); BindSysEvent(LCUI_TEXTINPUT, OnTextInput); - RBTree_OnCompare(&self.event_records, CompareWidgetEventRecord); - RBTree_OnDestroy(&self.event_records, DestoryWidgetEventRecord); - LinkedList_Init(&self.touch_capturers); + rbtree_set_compare_func(&self.event_records, CompareWidgetEventRecord); + rbtree_set_destroy_func(&self.event_records, DestoryWidgetEventRecord); + list_create(&self.touch_capturers); } void LCUIWidget_FreeEvent(void) { - LinkedListNode *node; + list_node_t *node; LCUIMutex_Lock(&self.mutex); - for (LinkedList_Each(node, &self.events)) { + for (list_each(node, &self.events)) { int *id = node->data; LCUI_UnbindEvent(*id); } - RBTree_Destroy(&self.event_names); - RBTree_Destroy(&self.event_records); - Dict_Release(self.event_ids); + rbtree_destroy(&self.event_names); + rbtree_destroy(&self.event_records); + dict_destroy(self.event_ids); TouchCapturers_Clear(&self.touch_capturers); - LinkedList_Clear(&self.events, free); - LinkedList_Clear(&self.event_mappings, DestroyEventMapping); + list_destroy(&self.events, free); + list_destroy(&self.event_mappings, DestroyEventMapping); LCUIMutex_Unlock(&self.mutex); LCUIMutex_Destroy(&self.mutex); self.event_ids = NULL; diff --git a/lib/ui/src/widget_hash.c b/lib/ui/src/widget_hash.c index c2f2c9a2..afc43ada 100644 --- a/lib/ui/src/widget_hash.c +++ b/lib/ui/src/widget_hash.c @@ -73,10 +73,10 @@ void Widget_GenerateSelfHash(LCUI_Widget widget) void Widget_GenerateHash(LCUI_Widget w) { - LinkedListNode *node; + list_node_t *node; Widget_GenerateSelfHash(w); - for (LinkedList_Each(node, &w->children)) { + for (list_each(node, &w->children)) { Widget_GenerateHash(node->data); } } diff --git a/lib/ui/src/widget_helper.c b/lib/ui/src/widget_helper.c index f6c34bb7..7883a0ac 100644 --- a/lib/ui/src/widget_helper.c +++ b/lib/ui/src/widget_helper.c @@ -244,17 +244,17 @@ static void Widget_CollectReference(LCUI_Widget w, void *arg) const char *ref = Widget_GetAttribute(w, "ref"); if (ref) { - Dict_Add(arg, (void*)ref, w); + dict_add(arg, (void*)ref, w); } } -Dict *Widget_CollectReferences(LCUI_Widget w) +dict_t *Widget_CollectReferences(LCUI_Widget w) { - Dict *dict; - static DictType t; + dict_t *dict; + static dict_type_t t; - Dict_InitStringKeyType(&t); - dict = Dict_Create(&t, NULL); + dict_init_string_key_type(&t); + dict = dict_create(&t, NULL); Widget_Each(w, Widget_CollectReference, dict); return dict; } diff --git a/lib/ui/src/widget_id.c b/lib/ui/src/widget_id.c index 61e5e74e..f3501c17 100644 --- a/lib/ui/src/widget_id.c +++ b/lib/ui/src/widget_id.c @@ -36,29 +36,29 @@ #include static struct LCUI_WidgetIdLibraryModule { - Dict *ids; - DictType dt_ids; + dict_t *ids; + dict_type_t dt_ids; LCUI_Mutex mutex; } self; static int Widget_FreeId(LCUI_Widget w) { - LinkedList *list; - LinkedListNode *node; + list_t *list; + list_node_t *node; if (!w->id) { return -1; } - list = Dict_FetchValue(self.ids, w->id); + list = dict_fetch_value(self.ids, w->id); if (!list) { return -2; } - for (LinkedList_Each(node, list)) { + for (list_each(node, list)) { if (node->data == w) { free(w->id); w->id = NULL; - LinkedList_Unlink(list, node); - LinkedListNode_Delete(node); + list_unlink(list, node); + list_node_free(node); return 0; } } @@ -76,7 +76,7 @@ int Widget_DestroyId(LCUI_Widget w) int Widget_SetId(LCUI_Widget w, const char *idstr) { - LinkedList *list; + list_t *list; Widget_DestroyId(w); if (!idstr) { @@ -87,19 +87,19 @@ int Widget_SetId(LCUI_Widget w, const char *idstr) if (!w->id) { goto error_exit; } - list = Dict_FetchValue(self.ids, w->id); + list = dict_fetch_value(self.ids, w->id); if (!list) { - list = malloc(sizeof(LinkedList)); + list = malloc(sizeof(list_t)); if (!list) { goto error_exit; } - LinkedList_Init(list); - if (Dict_Add(self.ids, w->id, list) != 0) { + list_create(list); + if (dict_add(self.ids, w->id, list) != 0) { free(list); goto error_exit; } } - if (!LinkedList_Append(list, w)) { + if (!list_append(list, w)) { goto error_exit; } LCUIMutex_Unlock(&self.mutex); @@ -116,16 +116,16 @@ error_exit: LCUI_Widget LCUIWidget_GetById(const char *id) { - LinkedList *list; + list_t *list; LCUI_Widget w = NULL; if (!id) { return NULL; } LCUIMutex_Lock(&self.mutex); - list = Dict_FetchValue(self.ids, id); + list = dict_fetch_value(self.ids, id); if (list) { - w = LinkedList_Get(list, 0); + w = list_get(list, 0); } LCUIMutex_Unlock(&self.mutex); return w; @@ -133,22 +133,22 @@ LCUI_Widget LCUIWidget_GetById(const char *id) static void OnClearWidgetList(void *privdata, void *data) { - LinkedList *list = data; - LinkedList_Clear(list, NULL); + list_t *list = data; + list_destroy(list, NULL); free(list); } void LCUIWidget_InitIdLibrary(void) { LCUIMutex_Init(&self.mutex); - Dict_InitStringCopyKeyType(&self.dt_ids); - self.dt_ids.valDestructor = OnClearWidgetList; - self.ids = Dict_Create(&self.dt_ids, NULL); + dict_init_string_copy_key_type(&self.dt_ids); + self.dt_ids.val_destructor = OnClearWidgetList; + self.ids = dict_create(&self.dt_ids, NULL); } void LCUIWidget_FreeIdLibrary(void) { - Dict_Release(self.ids); + dict_destroy(self.ids); LCUIMutex_Destroy(&self.mutex); self.ids = NULL; } diff --git a/lib/ui/src/widget_paint.c b/lib/ui/src/widget_paint.c index b7669c47..2ab19394 100644 --- a/lib/ui/src/widget_paint.c +++ b/lib/ui/src/widget_paint.c @@ -51,7 +51,7 @@ typedef struct LCUI_RectGroupRec_ { LCUI_Widget widget; - LinkedList rects; + list_t rects; } LCUI_RectGroupRec, *LCUI_RectGroup; typedef struct LCUI_WidgetRendererRec_ { @@ -108,8 +108,8 @@ typedef struct LCUI_WidgetRendererRec_ { static struct LCUI_WidgetRenderModule { LCUI_BOOL active; LCUI_WidgetPrototype default_proto; - RBTree groups; - LinkedList rects; + rbtree_t groups; + list_t rects; } self = { 0 }; /** 判断部件是否有可绘制内容 */ @@ -238,16 +238,16 @@ LCUI_BOOL Widget_InvalidateArea(LCUI_Widget w, LCUI_RectF *in_rect, if (rect.width > 0 && rect.height > 0) { \ actual_rect = malloc(sizeof(LCUI_Rect)); \ RectFToInvalidArea(&rect, actual_rect); \ - LinkedList_Append(rects, actual_rect); \ + list_append(rects, actual_rect); \ } \ } while (0) -static void Widget_CollectInvalidArea(LCUI_Widget w, LinkedList *rects, float x, +static void Widget_CollectInvalidArea(LCUI_Widget w, list_t *rects, float x, float y, LCUI_RectF visible_area) { LCUI_RectF rect; LCUI_Rect *actual_rect; - LinkedListNode *node; + list_node_t *node; if (w->parent && w->parent->invalid_area_type >= LCUI_INVALID_AREA_TYPE_PADDING_BOX) { @@ -283,7 +283,7 @@ static void Widget_CollectInvalidArea(LCUI_Widget w, LinkedList *rects, float x, &visible_area); visible_area.x += x; visible_area.y += y; - for (LinkedList_Each(node, &w->children_show)) { + for (list_each(node, &w->children_show)) { Widget_CollectInvalidArea( node->data, rects, x + w->box.padding.x, y + w->box.padding.y, visible_area); @@ -293,17 +293,17 @@ static void Widget_CollectInvalidArea(LCUI_Widget w, LinkedList *rects, float x, w->has_child_invalid_area = FALSE; } -size_t Widget_GetInvalidArea(LCUI_Widget w, LinkedList *rects) +size_t Widget_GetInvalidArea(LCUI_Widget w, list_t *rects) { LCUI_Rect *rect; - LinkedListNode *node; + list_node_t *node; float scale = LCUIMetrics_GetScale(); - int x = iround(w->box.padding.x * scale); - int y = iround(w->box.padding.y * scale); + int x = y_iround(w->box.padding.x * scale); + int y = y_iround(w->box.padding.y * scale); Widget_CollectInvalidArea(w, rects, 0, 0, w->box.padding); - for (LinkedList_Each(node, rects)) { + for (list_each(node, rects)) { rect = node->data; rect->x -= x; rect->y -= y; @@ -326,10 +326,10 @@ static void OnDestroyGroup(void *data) void LCUIWidget_InitRenderer(void) { - RBTree_Init(&self.groups); - RBTree_OnCompare(&self.groups, OnCompareGroup); - RBTree_OnDestroy(&self.groups, OnDestroyGroup); - LinkedList_Init(&self.rects); + rbtree_init(&self.groups); + rbtree_set_compare_func(&self.groups, OnCompareGroup); + rbtree_set_destroy_func(&self.groups, OnDestroyGroup); + list_create(&self.rects); self.default_proto = LCUIWidget_GetPrototype(NULL); self.active = TRUE; } @@ -338,7 +338,7 @@ void LCUIWidget_FreeRenderer(void) { self.active = FALSE; RectList_Clear(&self.rects); - RBTree_Destroy(&self.groups); + rbtree_destroy(&self.groups); } /** 当前部件的绘制函数 */ @@ -552,13 +552,13 @@ static size_t WidgetRenderer_RenderChildren(LCUI_WidgetRenderer that) LCUI_Widget child; LCUI_Rect paint_rect; LCUI_RectF child_rect; - LinkedListNode *node; + list_node_t *node; LCUI_PaintContextRec child_paint; LCUI_WidgetRenderer renderer; LCUI_WidgetActualStyleRec style; /* Render the child widgets from bottom to top in stack order */ - for (LinkedList_EachReverse(node, &that->target->children_show)) { + for (list_each_reverse(node, &that->target->children_show)) { child = node->data; if (!child->computed_style.visible || child->state != LCUI_WSTATE_NORMAL) { diff --git a/lib/ui/src/widget_prototype.c b/lib/ui/src/widget_prototype.c index 4558a185..934fe827 100644 --- a/lib/ui/src/widget_prototype.c +++ b/lib/ui/src/widget_prototype.c @@ -35,8 +35,8 @@ #include static struct LCUI_WidgetPrototypeModule { - Dict *prototypes; - DictType dicttype; + dict_t *prototypes; + dict_type_t dicttype; LCUI_WidgetPrototypeRec default_prototype; } self = { 0 }; @@ -86,9 +86,9 @@ static void DeletePrototype(void *privdata, void *data) void LCUIWidget_InitPrototype(void) { - Dict_InitStringKeyType(&self.dicttype); - self.dicttype.valDestructor = DeletePrototype; - self.prototypes = Dict_Create(&self.dicttype, NULL); + dict_init_string_key_type(&self.dicttype); + self.dicttype.val_destructor = DeletePrototype; + self.prototypes = dict_create(&self.dicttype, NULL); self.default_prototype.name = NULL; self.default_prototype.init = Widget_DefaultMethod; self.default_prototype.refresh = Widget_DefaultMethod; @@ -105,7 +105,7 @@ void LCUIWidget_InitPrototype(void) void LCUIWidget_FreePrototype(void) { - Dict_Release(self.prototypes); + dict_destroy(self.prototypes); } LCUI_WidgetPrototype LCUIWidget_GetPrototype(const char *name) @@ -115,7 +115,7 @@ LCUI_WidgetPrototype LCUIWidget_GetPrototype(const char *name) if (!name) { return &self.default_prototype; } - proto = Dict_FetchValue(self.prototypes, name); + proto = dict_fetch_value(self.prototypes, name); if (!proto) { return &self.default_prototype; } @@ -127,13 +127,13 @@ LCUI_WidgetPrototype LCUIWidget_NewPrototype(const char *name, { LCUI_WidgetPrototype proto; - if (Dict_FetchValue(self.prototypes, name)) { + if (dict_fetch_value(self.prototypes, name)) { return NULL; } proto = NEW(LCUI_WidgetPrototypeRec, 1); if (parent_name) { LCUI_WidgetPrototype parent; - parent = Dict_FetchValue(self.prototypes, parent_name); + parent = dict_fetch_value(self.prototypes, parent_name); if (parent) { *proto = *parent; proto->proto = parent; @@ -144,7 +144,7 @@ LCUI_WidgetPrototype LCUIWidget_NewPrototype(const char *name, *proto = self.default_prototype; } proto->name = strdup2(name); - if (Dict_Add(self.prototypes, proto->name, proto) == 0) { + if (dict_add(self.prototypes, proto->name, proto) == 0) { return proto; } free(proto->name); diff --git a/lib/ui/src/widget_status.c b/lib/ui/src/widget_status.c index 06471d08..01bb373c 100644 --- a/lib/ui/src/widget_status.c +++ b/lib/ui/src/widget_status.c @@ -38,13 +38,13 @@ static void Widget_MarkChildrenRefreshByStatus(LCUI_Widget w) { - LinkedListNode *node; + list_node_t *node; if (w->rules && w->rules->ignore_status_change) { return; } Widget_AddTask(w, LCUI_WTASK_REFRESH_STYLE); - for (LinkedList_Each(node, &w->children)) { + for (list_each(node, &w->children)) { Widget_MarkChildrenRefreshByStatus(node->data); } } diff --git a/lib/ui/src/widget_style.c b/lib/ui/src/widget_style.c index 5026576a..f477a940 100644 --- a/lib/ui/src/widget_style.c +++ b/lib/ui/src/widget_style.c @@ -482,10 +482,10 @@ LCUI_SelectorNode Widget_GetSelectorNode(LCUI_Widget w) sn->type = strdup2(w->type); } for (i = 0; w->classes && w->classes[i]; ++i) { - sortedstrlist_add(&sn->classes, w->classes[i]); + strlist_sorted_add(&sn->classes, w->classes[i]); } for (i = 0; w->status && w->status[i]; ++i) { - sortedstrlist_add(&sn->status, w->status[i]); + strlist_sorted_add(&sn->status, w->status[i]); } SelectorNode_Update(sn); return sn; @@ -494,31 +494,31 @@ LCUI_SelectorNode Widget_GetSelectorNode(LCUI_Widget w) LCUI_Selector Widget_GetSelector(LCUI_Widget w) { int i = 0; - LinkedList list; + list_t list; LCUI_Selector s; LCUI_Widget parent; - LinkedListNode *node; + list_node_t *node; s = Selector(NULL); - LinkedList_Init(&list); + list_create(&list); for (parent = w; parent; parent = parent->parent) { if (parent->id || parent->type || parent->classes || parent->status) { - LinkedList_Append(&list, parent); + list_append(&list, parent); } } if (list.length >= MAX_SELECTOR_DEPTH) { - LinkedList_Clear(&list, NULL); + list_destroy(&list, NULL); Selector_Delete(s); return NULL; } - for (LinkedList_EachReverse(node, &list)) { + for (list_each_reverse(node, &list)) { parent = node->data; s->nodes[i] = Widget_GetSelectorNode(parent); s->rank += s->nodes[i]->rank; i += 1; } - LinkedList_Clear(&list, NULL); + list_destroy(&list, NULL); s->nodes[i] = NULL; s->length = i; Selector_Update(s); @@ -528,8 +528,8 @@ LCUI_Selector Widget_GetSelector(LCUI_Widget w) size_t Widget_GetChildrenStyleChanges(LCUI_Widget w, int type, const char *name) { LCUI_Selector s; - LinkedList snames; - LinkedListNode *node; + list_t snames; + list_node_t *node; size_t i, n, len; size_t count = 0; @@ -545,7 +545,7 @@ size_t Widget_GetChildrenStyleChanges(LCUI_Widget w, int type, const char *name) default: return 0; } - LinkedList_Init(&snames); + list_create(&snames); s = Widget_GetSelector(w); n = strsplit(name, " ", &names); /* 为分割出来的字符串加上前缀 */ @@ -558,7 +558,7 @@ size_t Widget_GetChildrenStyleChanges(LCUI_Widget w, int type, const char *name) names[i] = str; } SelectorNode_GetNames(s->nodes[s->length - 1], &snames); - for (LinkedList_Each(node, &snames)) { + for (list_each(node, &snames)) { char *sname = node->data; /* 过滤掉不包含 name 中存在的名称 */ for (i = 0; i < n; ++i) { @@ -582,7 +582,7 @@ size_t Widget_GetChildrenStyleChanges(LCUI_Widget w, int type, const char *name) } } Selector_Delete(s); - LinkedList_Clear(&snames, free); + list_destroy(&snames, free); for (i = 0; names[i]; ++i) { free(names[i]); } @@ -608,9 +608,9 @@ void Widget_UpdateStyle(LCUI_Widget w, LCUI_BOOL is_refresh_all) void Widget_UpdateChildrenStyle(LCUI_Widget w, LCUI_BOOL is_refresh_all) { - LinkedListNode *node; + list_node_t *node; w->task.for_children = TRUE; - for (LinkedList_Each(node, &w->children)) { + for (list_each(node, &w->children)) { Widget_UpdateStyle(node->data, is_refresh_all); Widget_UpdateChildrenStyle(node->data, is_refresh_all); } diff --git a/lib/ui/src/widget_task.c b/lib/ui/src/widget_task.c index 214523e6..7b9874b4 100644 --- a/lib/ui/src/widget_task.c +++ b/lib/ui/src/widget_task.c @@ -45,7 +45,7 @@ typedef struct LCUI_WidgetTaskContextRec_ *LCUI_WidgetTaskContext; typedef struct LCUI_WidgetTaskContextRec_ { unsigned style_hash; - Dict *style_cache; + dict_t *style_cache; LCUI_WidgetStyleDiffRec style_diff; LCUI_WidgetLayoutDiffRec layout_diff; LCUI_WidgetTaskContext parent; @@ -53,7 +53,7 @@ typedef struct LCUI_WidgetTaskContextRec_ { } LCUI_WidgetTaskContextRec; static struct WidgetTaskModule { - DictType style_cache_dict; + dict_type_t style_cache_dict; LCUI_MetricsRec metrics; LCUI_BOOL refresh_all; LCUI_WidgetFunction handlers[LCUI_WTASK_TOTAL_NUM]; @@ -64,7 +64,7 @@ static size_t Widget_UpdateWithContext(LCUI_Widget w, static unsigned int IntKeyDict_HashFunction(const void *key) { - return Dict_IdentityHashFunction(*(unsigned int *)key); + return (*(unsigned int *)key); } static int IntKeyDict_KeyCompare(void *privdata, const void *key1, @@ -92,15 +92,15 @@ static void StyleSheetCacheDestructor(void *privdata, void *val) static void InitStylesheetCacheDict(void) { - DictType *dt = &self.style_cache_dict; + dict_type_t *dt = &self.style_cache_dict; - dt->valDup = NULL; - dt->keyDup = IntKeyDict_KeyDup; - dt->keyCompare = IntKeyDict_KeyCompare; - dt->hashFunction = IntKeyDict_HashFunction; - dt->keyDestructor = IntKeyDict_KeyDestructor; - dt->valDestructor = StyleSheetCacheDestructor; - dt->keyDestructor = IntKeyDict_KeyDestructor; + dt->val_dup = NULL; + dt->key_dup = IntKeyDict_KeyDup; + dt->key_compare = IntKeyDict_KeyCompare; + dt->hash_function = IntKeyDict_HashFunction; + dt->key_destructor = IntKeyDict_KeyDestructor; + dt->val_destructor = StyleSheetCacheDestructor; + dt->key_destructor = IntKeyDict_KeyDestructor; } static void Widget_OnRefreshStyle(LCUI_Widget w) @@ -146,10 +146,10 @@ void Widget_UpdateTaskStatus(LCUI_Widget widget) void Widget_AddTaskForChildren(LCUI_Widget widget, int task) { LCUI_Widget child; - LinkedListNode *node; + list_node_t *node; widget->task.for_children = TRUE; - for (LinkedList_Each(node, &widget->children)) { + for (list_each(node, &widget->children)) { child = node->data; Widget_AddTask(child, task); Widget_AddTaskForChildren(child, task); @@ -238,7 +238,7 @@ LCUI_WidgetTaskContext Widget_BeginUpdate(LCUI_Widget w, data = (LCUI_WidgetRulesData)w->rules; if (!data->style_cache) { data->style_cache = - Dict_Create(&self.style_cache_dict, NULL); + dict_create(&self.style_cache_dict, NULL); } Widget_GenerateSelfHash(w); self_ctx->style_hash = w->hash; @@ -248,12 +248,12 @@ LCUI_WidgetTaskContext Widget_BeginUpdate(LCUI_Widget w, if (self_ctx->style_cache && w->hash) { hash = self_ctx->style_hash; hash = ((hash << 5) + hash) + w->hash; - style = Dict_FetchValue(self_ctx->style_cache, &hash); + style = dict_fetch_value(self_ctx->style_cache, &hash); if (!style) { style = StyleSheet(); selector = Widget_GetSelector(w); LCUI_GetStyleSheet(selector, style); - Dict_Add(self_ctx->style_cache, &hash, style); + dict_add(self_ctx->style_cache, &hash, style); Selector_Delete(selector); } w->inherited_style = style; @@ -282,7 +282,7 @@ static size_t Widget_UpdateVisibleChildren(LCUI_Widget w, LCUI_BOOL found = FALSE; LCUI_RectF rect, visible_rect; LCUI_Widget child, parent; - LinkedListNode *node, *next; + list_node_t *node, *next; rect = w->box.padding; if (rect.width < 1 && Widget_HasAutoStyle(w, key_width)) { @@ -335,7 +335,7 @@ static size_t Widget_UpdateChildren(LCUI_Widget w, LCUI_WidgetTaskContext ctx) clock_t msec = 0; LCUI_Widget child; LCUI_WidgetRulesData data; - LinkedListNode *node, *next; + list_node_t *node, *next; size_t total = 0, update_count = 0, count; if (!w->task.for_children) { @@ -377,7 +377,7 @@ static size_t Widget_UpdateChildren(LCUI_Widget w, LCUI_WidgetTaskContext ctx) continue; } if (count > 0) { - data->progress = max(child->index, data->progress); + data->progress = y_max(child->index, data->progress); if (data->progress > w->children_show.length) { data->progress = child->index; } diff --git a/lib/ui/src/widget_tree.c b/lib/ui/src/widget_tree.c index c3bcf641..9079ca69 100644 --- a/lib/ui/src/widget_tree.c +++ b/lib/ui/src/widget_tree.c @@ -50,7 +50,7 @@ int Widget_Append(LCUI_Widget parent, LCUI_Widget widget) widget->parent = parent; widget->state = LCUI_WSTATE_CREATED; widget->index = parent->children.length; - LinkedList_AppendNode(&parent->children, &widget->node); + list_append_node(&parent->children, &widget->node); ev.cancel_bubble = TRUE; ev.type = LCUI_WEVENT_LINK; Widget_UpdateStyle(widget, TRUE); @@ -67,7 +67,7 @@ int Widget_Prepend(LCUI_Widget parent, LCUI_Widget widget) { LCUI_Widget child; LCUI_WidgetEventRec ev = { 0 }; - LinkedListNode *node; + list_node_t *node; if (!parent || !widget) { return -1; @@ -81,7 +81,7 @@ int Widget_Prepend(LCUI_Widget parent, LCUI_Widget widget) widget->parent = parent; widget->state = LCUI_WSTATE_CREATED; node = &widget->node; - LinkedList_InsertNode(&parent->children, 0, node); + list_insert_node(&parent->children, 0, node); /** 修改它后面的部件的 index 值 */ node = node->next; while (node) { @@ -105,8 +105,8 @@ int Widget_Unwrap(LCUI_Widget widget) size_t len; LCUI_Widget child; LCUI_WidgetEventRec ev = { 0 }; - LinkedList *children; - LinkedListNode *target, *node, *prev; + list_t *children; + list_node_t *target, *node, *prev; if (!widget->parent) { return -1; @@ -114,9 +114,9 @@ int Widget_Unwrap(LCUI_Widget widget) children = &widget->parent->children; len = widget->children.length; if (len > 0) { - node = LinkedList_GetNode(&widget->children, 0); + node = list_get_node(&widget->children, 0); Widget_RemoveStatus(node->data, "first-child"); - node = LinkedList_GetNodeAtTail(&widget->children, 0); + node = list_get_last_node(&widget->children); Widget_RemoveStatus(node->data, "last-child"); } node = &widget->node; @@ -130,8 +130,8 @@ int Widget_Unwrap(LCUI_Widget widget) child = node->data; ev.type = LCUI_WEVENT_UNLINK; Widget_TriggerEvent(child, &ev, NULL); - LinkedList_Unlink(&widget->children, node); - LinkedList_Link(children, target, node); + list_unlink(&widget->children, node); + list_link(children, target, node); child->parent = widget->parent; ev.type = LCUI_WEVENT_LINK; Widget_TriggerEvent(child, &ev, NULL); @@ -144,7 +144,7 @@ int Widget_Unwrap(LCUI_Widget widget) Widget_AddStatus(target->next->data, "first-child"); } if (widget->index == children->length - 1) { - node = LinkedList_GetNodeAtTail(children, 0); + node = list_get_last_node(children); Widget_AddStatus(node->data, "last-child"); } Widget_Destroy(widget); @@ -155,7 +155,7 @@ int Widget_Unlink(LCUI_Widget w) { LCUI_Widget child; LCUI_WidgetEventRec ev = { 0 }; - LinkedListNode *node; + list_node_t *node; if (!w->parent) { return -1; @@ -186,8 +186,8 @@ int Widget_Unlink(LCUI_Widget w) ev.cancel_bubble = TRUE; ev.type = LCUI_WEVENT_UNLINK; Widget_TriggerEvent(w, &ev, NULL); - LinkedList_Unlink(&w->parent->children, node); - LinkedList_Unlink(&w->parent->children_show, &w->node_show); + list_unlink(&w->parent->children, node); + list_unlink(&w->parent->children_show, &w->node_show); Widget_PostSurfaceEvent(w, LCUI_WEVENT_UNLINK, TRUE); Widget_AddTask(w->parent, LCUI_WTASK_REFLOW); w->parent = NULL; @@ -196,7 +196,7 @@ int Widget_Unlink(LCUI_Widget w) LCUI_Widget Widget_GetPrev(LCUI_Widget w) { - LinkedListNode *node = &w->node; + list_node_t *node = &w->node; if (node->prev && node != w->parent->children.head.next) { return node->prev->data; } @@ -205,7 +205,7 @@ LCUI_Widget Widget_GetPrev(LCUI_Widget w) LCUI_Widget Widget_GetNext(LCUI_Widget w) { - LinkedListNode *node = &w->node; + list_node_t *node = &w->node; if (node->next) { return node->next->data; } @@ -214,7 +214,7 @@ LCUI_Widget Widget_GetNext(LCUI_Widget w) LCUI_Widget Widget_GetChild(LCUI_Widget w, size_t index) { - LinkedListNode *node = LinkedList_GetNode(&w->children, index); + list_node_t *node = list_get_node(&w->children, index); if (node) { return node->data; } @@ -230,21 +230,21 @@ void Widget_DestroyChildren(LCUI_Widget w) { /* 先释放显示列表,后销毁部件列表,因为部件在这两个链表中的节点是和它共用 * 一块内存空间的,销毁部件列表会把部件释放掉,所以把这个操作放在后面 */ - LinkedList_ClearData(&w->children_show, NULL); - LinkedList_ClearData(&w->children, Widget_OnDestroy); + list_destroy_without_node(&w->children_show, NULL); + list_destroy_without_node(&w->children, Widget_OnDestroy); } static void _LCUIWidget_PrintTree(LCUI_Widget w, int depth, const char *prefix) { size_t len; LCUI_Widget child; - LinkedListNode *node; + list_node_t *node; LCUI_SelectorNode snode; char str[16], child_prefix[512]; len = strlen(prefix); strcpy(child_prefix, prefix); - for (LinkedList_Each(node, &w->children)) { + for (list_each(node, &w->children)) { if (node == w->children.tail.prev) { strcpy(str, "└"); strcpy(&child_prefix[len], " "); @@ -260,7 +260,7 @@ static void _LCUIWidget_PrintTree(LCUI_Widget w, int depth, const char *prefix) strcat(str, "┬"); } snode = Widget_GetSelectorNode(child); - Logger_Error( + logger_error( "%s%s %s, xy:(%g,%g), size:(%g,%g), " "visible: %s, display: %d, padding: (%g,%g,%g,%g), margin: " "(%g,%g,%g,%g)\n", @@ -281,7 +281,7 @@ void Widget_PrintTree(LCUI_Widget w) LCUI_SelectorNode node; w = w ? w : LCUIWidget_GetRoot(); node = Widget_GetSelectorNode(w); - Logger_Error("%s, xy:(%g,%g), size:(%g,%g), visible: %s\n", + logger_error("%s, xy:(%g,%g), size:(%g,%g), visible: %s\n", node->fullname, w->x, w->y, w->width, w->height, w->computed_style.visible ? "true" : "false"); SelectorNode_Delete(node); @@ -294,12 +294,12 @@ size_t Widget_Each(LCUI_Widget w, void (*callback)(LCUI_Widget, void *), size_t count = 0; LCUI_Widget next; - LCUI_Widget child = LinkedList_Get(&w->children, 0); + LCUI_Widget child = list_get(&w->children, 0); while (child && child != w) { callback(child, arg); ++count; - next = LinkedList_Get(&child->children, 0); + next = list_get(&child->children, 0); while (!next && child != w) { next = Widget_GetNext(child); child = child->parent; @@ -313,7 +313,7 @@ LCUI_Widget Widget_At(LCUI_Widget widget, int ix, int iy) { float x, y; LCUI_BOOL is_hit; - LinkedListNode *node; + list_node_t *node; LCUI_Widget target = widget, c = NULL; if (!widget) { @@ -323,7 +323,7 @@ LCUI_Widget Widget_At(LCUI_Widget widget, int ix, int iy) y = 1.0f * iy; do { is_hit = FALSE; - for (LinkedList_Each(node, &target->children_show)) { + for (list_each(node, &target->children_show)) { c = node->data; if (!c->computed_style.visible) { continue; diff --git a/lib/util/src/charset.c b/lib/util/src/charset.c deleted file mode 100644 index 2c14ad65..00000000 --- a/lib/util/src/charset.c +++ /dev/null @@ -1,284 +0,0 @@ -/* - * charset.c -- The charset opreation set. - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include -#include - -#include -#include - -/* clang-format off */ - -#define MAX_SAVE_NUM 20 - -#define UNI_SUR_HIGH_START 0xD800 -#define UNI_SUR_HIGH_END 0xDBFF -#define UNI_SUR_LOW_START 0xDC00 -#define UNI_SUR_LOW_END 0xDFFF - -/* The maximum possible value which will fit into four bytes of - UTF-8. This is larger than UNICODE_MAXIMUM. */ -#define UNICODE_UTF8_4 0x1fffff - -/* clang-format on */ - -#ifdef LCUI_BUILD_IN_WIN32 -#include - -static size_t encode(char *str, const wchar_t *wcs, size_t maxlen, int codepage) -{ - size_t bytes; - - bytes = WideCharToMultiByte(codepage, 0, wcs, -1, str, (int)maxlen, - NULL, NULL); - if (bytes > 0 && bytes < maxlen) { - // Excluding the terminating NULL - bytes -= 1; - } - return bytes; -} - -static size_t decode(wchar_t *wcs, const char *str, size_t maxlen, int codepage) -{ - size_t len; - - len = MultiByteToWideChar(codepage, 0, str, -1, wcs, (int)maxlen); - if (len > 0 && len < maxlen) { - // Excluding the terminating NULL - len -= 1; - } - return len; -} -#endif - -static size_t utf8_to_ucs2(const char *utf8, wchar_t *ucs2) -{ - size_t i, count; - wchar_t unicode; - const unsigned char *byte; - unsigned char buf[MAX_SAVE_NUM]; - - byte = (unsigned char *)utf8; - if ((*byte >> 7) == 0) { // 0xxxxxxx - *ucs2 = *byte; - return 1; - } - if ((*byte >> 5) == 6) { // 110xxxxx - count = 2; - } else if ((*byte >> 4) == 14) { // 1110xxxx - count = 3; - } else if ((*byte >> 3) == 30) { // 11110xxx - count = 4; - } else if ((*byte >> 2) == 62) { // 111110xx - count = 5; - } else if ((*byte >> 1) == 126) { // 1111110x - count = 6; - } else { - return 0; - } - for (i = 0; i < count; ++i) { - buf[i] = *byte++; - } - unicode = buf[0]; - if (unicode >= 0xF0) { - unicode = (wchar_t)(buf[0] & 0x07) << 18; - unicode |= (wchar_t)(buf[1] & 0x3F) << 12; - unicode |= (wchar_t)(buf[2] & 0x3F) << 6; - unicode |= (wchar_t)(buf[3] & 0x3F); - } else if (unicode >= 0xE0) { - unicode = (wchar_t)(buf[0] & 0x0F) << 12; - unicode |= (wchar_t)(buf[1] & 0x3F) << 6; - unicode |= (wchar_t)(buf[2] & 0x3F); - } else if (unicode >= 0xC0) { - unicode = (wchar_t)(buf[0] & 0x1F) << 6; - unicode |= (wchar_t)(buf[1] & 0x3F); - } - *ucs2 = unicode; - return count; -} - -/* https://github.com/benkasminbullock/unicode-c/blob/master/unicode.c#L310 */ - -size_t ucs2_to_utf8(int32_t ucs2, unsigned char *utf8) -{ - if (ucs2 < 0x80) { - utf8[0] = ucs2; - utf8[1] = '\0'; - return 1; - } - if (ucs2 < 0x800) { - utf8[0] = (ucs2 >> 6) | 0xC0; - utf8[1] = (ucs2 & 0x3F) | 0x80; - utf8[2] = '\0'; - return 2; - } - if (ucs2 < 0xFFFF) { - utf8[0] = ((ucs2 >> 12)) | 0xE0; - utf8[1] = ((ucs2 >> 6) & 0x3F) | 0x80; - utf8[2] = ((ucs2)&0x3F) | 0x80; - utf8[3] = '\0'; - if (ucs2 >= UNI_SUR_HIGH_START && ucs2 <= UNI_SUR_LOW_END) { - /* Ill-formed. */ - return 0; - } - return 3; - } - if (ucs2 <= UNICODE_UTF8_4) { - /* http://tidy.sourceforge.net/cgi-bin/lxr/source/src/utf8.c#L380 - */ - utf8[0] = 0xF0 | (ucs2 >> 18); - utf8[1] = 0x80 | ((ucs2 >> 12) & 0x3F); - utf8[2] = 0x80 | ((ucs2 >> 6) & 0x3F); - utf8[3] = 0x80 | ((ucs2 & 0x3F)); - utf8[4] = '\0'; - return 4; - } - return 0; -} - -static size_t DecodeUTF8(wchar_t *wcs, const char *str, size_t max_len) -{ - size_t n; - size_t count = 0; - - wchar_t buf; - wchar_t *wp = wcs; - - const char *p = str; - - if (wcs) { - while (*p) { - count += 1; - if (count > max_len) { - count -= 1; - break; - } - n = utf8_to_ucs2(p, wp); - if (n > 0) { - p += n; - ++wp; - } else { - ++p; - } - } - if (count < max_len) { - wcs[count] = 0; - } - } else { - while (*p) { - n = utf8_to_ucs2(p, &buf); - if (n > 0) { - p += n; - } else { - ++p; - } - count += 1; - } - } - return count; -} - -size_t EncodeToUTF8(char *str, const wchar_t *wcs, size_t max_len) -{ - size_t n; - size_t count = 0; - - char *p = str; - unsigned char buf[MAX_SAVE_NUM]; - - const wchar_t *wp = wcs; - - if (str) { - while (*wp) { - n = ucs2_to_utf8(*wp, buf); - count += n; - if (count > max_len) { - count -= n; - break; - } - strncpy(p, (char *)buf, n); - p += n; - ++wp; - } - if (count < max_len) { - str[count] = 0; - } - } else { - while (*wp) { - count += ucs2_to_utf8(*wp, buf); - ++wp; - } - } - return count; -} - -size_t LCUI_DecodeString(wchar_t *wstr, const char *str, size_t max_len, - int encoding) -{ -#ifdef LCUI_BUILD_IN_WIN32 - // 暂时不处理其它编码方式 - switch (encoding) { - case ENCODING_ANSI: - return decode(wstr, str, max_len, CP_ACP); - case ENCODING_UTF8: - return DecodeUTF8(wstr, str, max_len); - default: - break; - } - return 0; -#else - return DecodeUTF8(wstr, str, max_len); -#endif -} - -size_t LCUI_EncodeString(char *str, const wchar_t *wstr, size_t max_len, - int encoding) -{ -#ifdef LCUI_BUILD_IN_WIN32 - int cp; - // 暂时不处理其它编码方式 - switch (encoding) { - case ENCODING_ANSI: - cp = CP_ACP; - break; - case ENCODING_UTF8: - return EncodeToUTF8(str, wstr, max_len); - default: - return 0; - } - return encode(str, wstr, max_len, cp); -#else - return EncodeToUTF8(str, wstr, max_len); -#endif -} diff --git a/lib/util/src/dict.c b/lib/util/src/dict.c deleted file mode 100644 index 9306ba09..00000000 --- a/lib/util/src/dict.c +++ /dev/null @@ -1,731 +0,0 @@ -/* Hash Tables Implementation. - * - * This file implements in memory hash tables with insert/del/replace/find/ - * get-random-element operations. Hash tables will auto resize if needed - * tables of power of two in size are used, collisions are handled by - * chaining. See the source code for more information... :) - * - * Copyright (c) 2006-2012, Salvatore Sanfilippo - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -/* Using Dict_EnableResize() / Dict_DisableResize() we make possible to - * enable/disable resizing of the hash table as needed. This is very important - * for Redis, as we use copy-on-write and don't want to move too much memory - * around when there is a child performing saving operations. - * - * Note that even when dict_can_resize is set to 0, not all resizes are - * prevented: an hash table is still allowed to grow if the ratio between - * the number of elements and the buckets > dict_force_resize_ratio. */ -static int dict_can_resize = 1; -static unsigned int dict_force_resize_ratio = 5; - -/* -------------------------- private prototypes ---------------------------- */ - -static int Dict_ExpandIfNeeded(Dict *ht); -static unsigned long Dict_NextPower(unsigned long size); -static int Dict_KeyIndex(Dict *ht, const void *key); -static int Dict_Init(Dict *ht, DictType *type, void *privdata); - -/* -------------------------- hash functions -------------------------------- */ - -unsigned int Dict_IntHashFunction(unsigned int key) -{ - key += ~(key << 15); - key ^= (key >> 10); - key += (key << 3); - key ^= (key >> 6); - key += ~(key << 11); - key ^= (key >> 16); - return key; -} - -/* Identity hash function for integer keys */ -unsigned int Dict_IdentityHashFunction(unsigned int key) -{ - return key; -} - -static int dict_hash_function_seed = 5381; - -void Dict_SetHashFunctionSeed(unsigned int seed) -{ - dict_hash_function_seed = seed; -} - -unsigned int Dict_GetHashFunctionSeed(void) -{ - return dict_hash_function_seed; -} - -/* Generic hash function (a popular one from Bernstein). - * I tested a few and this was the best. */ -unsigned int Dict_GenHashFunction(const unsigned char *buf, int len) -{ - unsigned int hash = dict_hash_function_seed; - while (len--) { - hash = ((hash << 5) + hash) + (*buf++); /* hash * 33 + c */ - } - return hash; -} - -/* And a case insensitive version */ -unsigned int Dict_GenCaseHashFunction(const unsigned char *buf, int len) -{ - unsigned int hash = dict_hash_function_seed; - while (len--) { - hash = ((hash << 5) + hash) + - (tolower(*buf++)); /* hash * 33 + c */ - } - return hash; -} - -/* ----------------------------- API implementation ------------------------- */ - -/** 重置哈希表 */ -static void Dict_Reset(DictHashTable *ht) -{ - ht->table = NULL; - ht->size = 0; - ht->sizemask = 0; - ht->used = 0; -} - -Dict *Dict_Create(DictType *type, void *privdata) -{ - static int inited = 0; - Dict *d = malloc(sizeof(Dict)); - Dict_Init(d, type, privdata); - if (!inited) { - srand((unsigned int)time(NULL)); - inited = 1; - } - return d; -} - -/** 初始化字典 */ -static int Dict_Init(Dict *d, DictType *type, void *privdata) -{ - d->type = type; - d->iterators = 0; - d->rehashidx = -1; - d->privdata = privdata; - Dict_Reset(&d->ht[0]); - Dict_Reset(&d->ht[1]); - return 0; -} - -int Dict_Resize(Dict *d) -{ - int minimal; - if (!dict_can_resize || Dict_IsRehashing(d)) { - return -1; - } - minimal = d->ht[0].used; - if (minimal < DICT_HT_INITIAL_SIZE) { - minimal = DICT_HT_INITIAL_SIZE; - } - return Dict_Expand(d, minimal); -} - -int Dict_Expand(Dict *d, unsigned long size) -{ - DictHashTable n; - unsigned long realsize; - if (Dict_IsRehashing(d) || d->ht[0].used > size) { - return -1; - } - /* 计算哈希表的(真正)大小 */ - realsize = Dict_NextPower(size); - n.used = 0; - n.size = realsize; - n.sizemask = realsize - 1; - n.table = calloc(realsize, sizeof(DictEntry *)); - /* 如果字典的 0 号哈希表未初始化,则将新建的哈希表作为字典的 0 号哈 - * 希表,否则,将新建哈希表作为字典的 1 号哈希表,并将它用于 rehash - */ - if (d->ht[0].table == NULL) { - d->ht[0] = n; - } else { - d->ht[1] = n; - d->rehashidx = 0; - } - return 0; -} - -int Dict_Rehash(Dict *d, int n) -{ - if (!Dict_IsRehashing(d)) { - return 0; - } - while (n--) { - DictEntry *de, *nextde; - if (d->ht[0].used == 0) { - free(d->ht[0].table); - d->ht[0] = d->ht[1]; - Dict_Reset(&d->ht[1]); - d->rehashidx = -1; - return 0; - } - assert(d->ht[0].size > (unsigned)d->rehashidx); - while (d->ht[0].table[d->rehashidx] == NULL) { - d->rehashidx++; - } - de = d->ht[0].table[d->rehashidx]; - while (de) { - unsigned int h; - nextde = de->next; - h = Dict_HashKey(d, de->key) & d->ht[1].sizemask; - de->next = d->ht[1].table[h]; - d->ht[1].table[h] = de; - d->ht[0].used--; - d->ht[1].used++; - de = nextde; - } - d->ht[0].table[d->rehashidx] = NULL; - d->rehashidx++; - } - return 1; -} - -#define timeInMilliseconds LCUI_GetTime - -int Dict_RehashMilliseconds(Dict *d, int ms) -{ - long long start = timeInMilliseconds(); - int rehashes = 0; - - while (Dict_Rehash(d, 100)) { - rehashes += 100; - if (timeInMilliseconds() - start > ms) { - break; - } - } - return rehashes; -} - -/** 在字典没有迭代器的情况下,rehash 一个元素 */ -static void Dict_RehashStep(Dict *d) -{ - if (d->iterators == 0) { - Dict_Rehash(d, 1); - } -} - -int Dict_Add(Dict *d, void *key, void *val) -{ - DictEntry *entry = Dict_AddRaw(d, key); - if (!entry) { - return -1; - } - Dict_SetVal(d, entry, val); - return 0; -} - -int Dict_AddCopy(Dict *d, void *key, const void *val) -{ - DictEntry *entry; - if (!d->type->valDup) { - return -2; - } - entry = Dict_AddRaw(d, key); - if (!entry) { - return -1; - } - entry->v.val = d->type->valDup(d->privdata, val); - return 0; -} - -DictEntry *Dict_AddRaw(Dict *d, void *key) -{ - int index; - DictEntry *entry; - DictHashTable *ht; - - /* 如果可以执行 rehash 操作,则执行平摊 rehash 操作 */ - if (Dict_IsRehashing(d)) { - Dict_RehashStep(d); - } - /* 计算 key 的 index 值,如果 key 已经存在,Dict_KeyIndex 返回 -1 */ - if ((index = Dict_KeyIndex(d, key)) == -1) { - return NULL; - } - /* 判断是否正在进行 rehash ,选择相应的表 */ - ht = Dict_IsRehashing(d) ? &d->ht[1] : &d->ht[0]; - entry = malloc(sizeof(*entry)); - entry->next = ht->table[index]; - ht->table[index] = entry; - ht->used++; - Dict_SetKey(d, entry, key); - return entry; -} - -int Dict_Replace(Dict *d, void *key, void *val) -{ - DictEntry *entry, auxentry; - if (Dict_Add(d, key, val) == 0) { - return 1; - } - entry = Dict_Find(d, key); - auxentry = *entry; - Dict_SetVal(d, entry, val); - Dict_FreeVal(d, &auxentry); - return 0; -} - -DictEntry *Dict_ReplaceRaw(Dict *d, void *key) -{ - DictEntry *entry = Dict_Find(d, key); - return entry ? entry : Dict_AddRaw(d, key); -} - -/* 删除字典中的指定元素 */ -static int Dict_GenericDelete(Dict *d, const void *key, int nofree) -{ - int table; - unsigned int h, idx; - DictEntry *he, *prev_he; - if (d->ht[0].size == 0) { - return -1; - } - if (Dict_IsRehashing(d)) { - Dict_RehashStep(d); - } - h = Dict_HashKey(d, key); - for (table = 0; table <= 1; table++) { - idx = h & d->ht[table].sizemask; - he = d->ht[table].table[idx]; - prev_he = NULL; - while (he) { - if (Dict_CompareKeys(d, key, he->key)) { - if (prev_he) { - prev_he->next = he->next; - } else { - d->ht[table].table[idx] = he->next; - } - if (!nofree) { - Dict_FreeKey(d, he); - Dict_FreeVal(d, he); - } - free(he); - d->ht[table].used--; - return 0; - } - prev_he = he; - he = he->next; - } - if (!Dict_IsRehashing(d)) { - break; - } - } - return -1; -} - -int Dict_Delete(Dict *ht, const void *key) -{ - return Dict_GenericDelete(ht, key, 0); -} - -int Dict_DeleteNoFree(Dict *ht, const void *key) -{ - return Dict_GenericDelete(ht, key, 1); -} - -/** 清除字典中指定的哈希表 */ -static void Dict_Clear(Dict *d, DictHashTable *ht) -{ - unsigned long i; - DictEntry *he, *next_he; - for (i = 0; i < ht->size && ht->used > 0; i++) { - he = ht->table[i]; - while (he) { - next_he = he->next; - Dict_FreeKey(d, he); - Dict_FreeVal(d, he); - free(he); - ht->used--; - he = next_he; - } - } - free(ht->table); - Dict_Reset(ht); -} - -void Dict_Release(Dict *d) -{ - Dict_Clear(d, &d->ht[0]); - Dict_Clear(d, &d->ht[1]); - free(d); -} - -DictEntry *Dict_Find(Dict *d, const void *key) -{ - DictEntry *he; - unsigned int h, idx, table; - if (d->ht[0].size == 0) { - return NULL; - } - if (Dict_IsRehashing(d)) { - Dict_RehashStep(d); - } - h = Dict_HashKey(d, key); - for (table = 0; table <= 1; table++) { - idx = h & d->ht[table].sizemask; - he = d->ht[table].table[idx]; - while (he) { - if (Dict_CompareKeys(d, key, he->key)) { - return he; - } - he = he->next; - } - if (!Dict_IsRehashing(d)) { - return NULL; - } - } - return NULL; -} - -void *Dict_FetchValue(Dict *d, const void *key) -{ - DictEntry *he = Dict_Find(d, key); - return he ? DictEntry_GetVal(he) : NULL; -} - -DictIterator *Dict_GetIterator(Dict *d) -{ - DictIterator *iter = malloc(sizeof(*iter)); - iter->d = d; - iter->table = 0; - iter->index = -1; - iter->safe = 0; - iter->entry = NULL; - iter->next_entry = NULL; - return iter; -} - -DictIterator *Dict_GetSafeIterator(Dict *d) -{ - DictIterator *i = Dict_GetIterator(d); - i->safe = 1; - return i; -} - -DictEntry *Dict_Next(DictIterator *iter) -{ - DictHashTable *ht; - while (1) { - if (iter->entry) { - iter->entry = iter->next_entry; - if (iter->entry) { - iter->next_entry = iter->entry->next; - return iter->entry; - } - continue; - } - /* 如果迭代器是新的(未使用过),那么初始化新迭代器 */ - ht = &iter->d->ht[iter->table]; - if (iter->safe && iter->index == -1 && iter->table == 0) { - iter->d->iterators++; - } - iter->index++; - if (iter->index >= (signed)ht->size) { - if (Dict_IsRehashing(iter->d) && iter->table == 0) { - iter->table++; - iter->index = 0; - ht = &iter->d->ht[1]; - } else { - break; - } - } - iter->entry = ht->table[iter->index]; - if (iter->entry) { - iter->next_entry = iter->entry->next; - return iter->entry; - } - } - return NULL; -} - -void Dict_ReleaseIterator(DictIterator *iter) -{ - if (iter->safe && !(iter->index == -1 && iter->table == 0)) { - iter->d->iterators--; - } - free(iter); -} - -DictEntry *Dict_GetRandomKey(Dict *d) -{ - DictEntry *he, *orighe; - unsigned int h; - int listlen, listele; - - if (Dict_Size(d) == 0) { - return NULL; - } - if (Dict_IsRehashing(d)) { - Dict_RehashStep(d); - } - if (Dict_IsRehashing(d)) { - do { - h = rand() % (d->ht[0].size + d->ht[1].size); - if (h >= d->ht[0].size) { - he = d->ht[1].table[h - d->ht[0].size]; - } else { - he = d->ht[0].table[h]; - } - } while (he == NULL); - } else { - do { - h = rand() & d->ht[0].sizemask; - he = d->ht[0].table[h]; - } while (he == NULL); - } - listlen = 0; - orighe = he; - while (he) { - he = he->next; - listlen++; - } - /* 从链表里随机取一项 */ - listele = rand() % listlen; - he = orighe; - while (listele--) he = he->next; - return he; -} - -/* ------------------------- private functions ------------------------------ */ - -/* Expand the hash table if needed */ -static int Dict_ExpandIfNeeded(Dict *d) -{ - /* Incremental rehashing already in progress. Return. */ - if (Dict_IsRehashing(d)) { - return 0; - } - /* If the hash table is empty expand it to the intial size. */ - if (d->ht[0].size == 0) { - return Dict_Expand(d, DICT_HT_INITIAL_SIZE); - } - /* If we reached the 1:1 ratio, and we are allowed to resize the hash - * table (global setting) or we should avoid it but the ratio between - * elements/buckets is over the "safe" threshold, we resize doubling - * the number of buckets. */ - if (d->ht[0].used >= d->ht[0].size && - (dict_can_resize || - d->ht[0].used / d->ht[0].size > dict_force_resize_ratio)) { - return Dict_Expand( - d, ((d->ht[0].size > d->ht[0].used) ? d->ht[0].size - : d->ht[0].used) * - 2); - } - return 0; -} - -static unsigned long Dict_NextPower(unsigned long size) -{ - unsigned long i = DICT_HT_INITIAL_SIZE; - - if (size >= LONG_MAX) - return LONG_MAX; - while (1) { - if (i >= size) - return i; - i *= 2; - } -} - -/** - * 获取字典中与 key 对应的空槽的索引 - * @returns 如果 key 已经存在,则返回 -1 - */ -static int Dict_KeyIndex(Dict *d, const void *key) -{ - DictEntry *he; - unsigned int h, idx, table; - if (Dict_ExpandIfNeeded(d) == -1) { - return -1; - } - h = Dict_HashKey(d, key); - for (table = 0; table <= 1; table++) { - idx = h & d->ht[table].sizemask; - he = d->ht[table].table[idx]; - while (he) { - if (Dict_CompareKeys(d, key, he->key)) { - return -1; - } - he = he->next; - } - if (!Dict_IsRehashing(d)) { - break; - } - } - return idx; -} - -void Dict_Empty(Dict *d) -{ - Dict_Clear(d, &d->ht[0]); - Dict_Clear(d, &d->ht[1]); - d->rehashidx = -1; - d->iterators = 0; -} - -#define DICT_STATS_VECTLEN 50 -static void Dict_PrintStatsHt(DictHashTable *ht) -{ - unsigned long totchainlen = 0; - unsigned long clvector[DICT_STATS_VECTLEN]; - unsigned long i, slots = 0, chainlen, maxchainlen = 0; - if (ht->used == 0) { - Logger_Info("No stats available for empty dictionaries\n"); - return; - } - for (i = 0; i < DICT_STATS_VECTLEN; i++) clvector[i] = 0; - for (i = 0; i < ht->size; i++) { - DictEntry *he; - if (ht->table[i] == NULL) { - clvector[0]++; - continue; - } - slots++; - chainlen = 0; - he = ht->table[i]; - while (he) { - chainlen++; - he = he->next; - } - if (chainlen < DICT_STATS_VECTLEN) { - clvector[chainlen]++; - } else { - clvector[DICT_STATS_VECTLEN - 1]++; - } - if (chainlen > maxchainlen) { - maxchainlen = chainlen; - } - totchainlen += chainlen; - } - printf("Hash table stats:\n"); - printf(" table size: %ld\n", ht->size); - printf(" number of elements: %ld\n", ht->used); - printf(" different slots: %ld\n", slots); - printf(" max chain length: %ld\n", maxchainlen); - printf(" avg chain length (counted): %.02f\n", - (float)totchainlen / slots); - printf(" avg chain length (computed): %.02f\n", - (float)ht->used / slots); - printf(" Chain length distribution:\n"); - for (i = 0; i < DICT_STATS_VECTLEN - 1; i++) { - if (clvector[i] == 0) { - continue; - } - printf(" %s%ld: %ld (%.02f%%)\n", - (i == DICT_STATS_VECTLEN - 1) ? ">= " : "", i, - clvector[i], ((float)clvector[i] / ht->size) * 100); - } -} - -void Dict_PrintStats(Dict *d) -{ - Dict_PrintStatsHt(&d->ht[0]); - if (Dict_IsRehashing(d)) { - printf("-- Rehashing into ht[1]:\n"); - Dict_PrintStatsHt(&d->ht[1]); - } -} - -void Dict_EnableResize(void) -{ - dict_can_resize = 1; -} - -void Dict_DisableResize(void) -{ - dict_can_resize = 0; -} - -unsigned int StringKeyDict_KeyHash(const void *key) -{ - const char *buf = key; - unsigned int hash = dict_hash_function_seed; - while (*buf) { - hash = ((hash << 5) + hash) + (*buf++); - } - return hash; -} - -int StringKeyDict_KeyCompare(void *privdata, const void *key1, - const void *key2) -{ - if (strcmp(key1, key2) == 0) { - return 1; - } - return 0; -} - -void *StringKeyDict_KeyDup(void *privdata, const void *key) -{ - char *newkey = malloc((strlen(key) + 1) * sizeof(char)); - strcpy(newkey, key); - return newkey; -} - -void StringKeyDict_KeyDestructor(void *privdata, void *key) -{ - free(key); -} - -void Dict_InitStringKeyType(DictType *t) -{ - t->hashFunction = StringKeyDict_KeyHash; - t->keyDup = NULL; - t->valDup = NULL; - t->keyCompare = StringKeyDict_KeyCompare; - t->keyDestructor = NULL; - t->valDestructor = NULL; -} - -void Dict_InitStringCopyKeyType(DictType *t) -{ - t->hashFunction = StringKeyDict_KeyHash; - t->keyDup = StringKeyDict_KeyDup; - t->valDup = NULL; - t->keyCompare = StringKeyDict_KeyCompare; - t->keyDestructor = StringKeyDict_KeyDestructor; - t->valDestructor = NULL; -} diff --git a/lib/util/src/dirent.c b/lib/util/src/dirent.c deleted file mode 100644 index fd844eef..00000000 --- a/lib/util/src/dirent.c +++ /dev/null @@ -1,211 +0,0 @@ -/* dirent.c -- Directory entry operation set. - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include -#include -#include - -int LCUI_OpenDirA(const char *path, LCUI_Dir *dir) -{ -#if defined(LCUI_BUILD_IN_WIN32) || (_WIN32) - size_t len; - char *newpath; - char name[] = "\\*"; - - len = strlen(path) + 1; - newpath = malloc(len * sizeof(char) + sizeof(name)); - if (newpath == NULL) { - return -ENOMEM; - } - strcpy(newpath, path); - strcpy(newpath + len - 1, name); - dir->handle = FindFirstFileA(newpath, &dir->entry.dataA); - free(newpath); - if (dir->handle == INVALID_HANDLE_VALUE) { - switch (GetLastError()) { - case ERROR_FILE_NOT_FOUND: - return -ENOENT; - case ERROR_ACCESS_DENIED: - return -EACCES; - default: - break; - } - return -1; - } - dir->cached = 1; -#endif - return 0; -} - -int LCUI_OpenDirW(const wchar_t *path, LCUI_Dir *dir) -{ -#if defined(LCUI_BUILD_IN_WIN32) || (_WIN32) - size_t len; - wchar_t *newpath; - wchar_t name[] = L"\\*"; - - - len = wcslen(path) + 1; - newpath = malloc(len * sizeof(wchar_t) + sizeof(name)); - if (!newpath) { - return -ENOMEM; - } - wcscpy(newpath, path); - wcscpy(newpath + len - 1, name); - dir->handle = FindFirstFileW(newpath, &dir->entry.dataW); - free(newpath); - if (dir->handle == INVALID_HANDLE_VALUE) { - switch (GetLastError()) { - case ERROR_FILE_NOT_FOUND: - return -ENOENT; - case ERROR_ACCESS_DENIED: - return -EACCES; - default: - break; - } - return -1; - } - dir->cached = 1; -#else - - int len; - char *newpath; - len = LCUI_EncodeString(NULL, path, 0, ENCODING_UTF8) + 1; - newpath = malloc(len * sizeof(wchar_t)); - LCUI_EncodeString(newpath, path, len, ENCODING_UTF8); - dir->handle = opendir(newpath); - free(newpath); - if (!dir->handle) { - return -1; - } -#endif - return 0; -} - -LCUI_DirEntry *LCUI_ReadDirA(LCUI_Dir *dir) -{ -#if defined(LCUI_BUILD_IN_WIN32) || (_WIN32) - if (dir->handle == INVALID_HANDLE_VALUE) { - return NULL; - } - if (dir->cached) { - dir->cached = 0; - return &dir->entry; - } - if (FindNextFileA(dir->handle, &dir->entry.dataA)) { - return &dir->entry; - } - FindClose(dir->handle); - dir->handle = INVALID_HANDLE_VALUE; -#endif - return NULL; -} - -LCUI_DirEntry *LCUI_ReadDirW(LCUI_Dir *dir) -{ -#if defined(LCUI_BUILD_IN_WIN32) || (_WIN32) - if (dir->handle == INVALID_HANDLE_VALUE) { - return NULL; - } - if (dir->cached) { - dir->cached = 0; - return &dir->entry; - } - if (FindNextFileW(dir->handle, &dir->entry.dataW)) { - return &dir->entry; - } - FindClose(dir->handle); - dir->handle = INVALID_HANDLE_VALUE; - return NULL; -#else - int len; - struct dirent *d; - d = readdir(dir->handle); - if (!d) { - return NULL; - } - dir->entry.dirent = *d; - len = LCUI_DecodeString(dir->entry.name, d->d_name, - LCUI_DIRENT_NAME_LEN, ENCODING_UTF8); - dir->entry.name[len] = 0; - return &dir->entry; -#endif -} - -int LCUI_CloseDir(LCUI_Dir *dir) -{ -#if defined(LCUI_BUILD_IN_WIN32) || (_WIN32) - if (!FindClose(dir->handle)) { - return -1; - } -#else - closedir(dir->handle); -#endif - return 0; -} - -char *LCUI_GetFileNameA(LCUI_DirEntry *entry) -{ -#if defined(LCUI_BUILD_IN_WIN32) || (_WIN32) - return entry->dataA.cFileName; -#endif - return NULL; -} - -wchar_t *LCUI_GetFileNameW(LCUI_DirEntry *entry) -{ -#if defined(LCUI_BUILD_IN_WIN32) || (_WIN32) - return entry->dataW.cFileName; -#else - return entry->name; -#endif - return NULL; -} - -int LCUI_FileIsDirectory(LCUI_DirEntry *entry) -{ -#if defined(LCUI_BUILD_IN_WIN32) || (_WIN32) - return entry->dataW.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; -#else - return entry->dirent.d_type == DT_DIR; -#endif -} - -int LCUI_FileIsRegular(LCUI_DirEntry *entry) -{ -#if defined(LCUI_BUILD_IN_WIN32) || (_WIN32) - return !(entry->dataW.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); -#else - return entry->dirent.d_type == DT_REG; -#endif -} diff --git a/lib/util/src/event.c b/lib/util/src/event.c index eaa7d067..caad7ddf 100644 --- a/lib/util/src/event.c +++ b/lib/util/src/event.c @@ -37,8 +37,8 @@ typedef struct LCUI_EventRecordRec_ { int id; /**< 事件标识号 */ LCUI_BOOL blocked; /**< 是否已经锁定 */ - LinkedList handlers; /**< 事件处理器列表 */ - LinkedList trash; /**< 待移除的处理器列表 */ + list_t handlers; /**< 事件处理器列表 */ + list_t trash; /**< 待移除的处理器列表 */ } LCUI_EventRecordRec, *LCUI_EventRecord; /** 事件处理器 */ @@ -47,14 +47,14 @@ typedef struct LCUI_EventHandlerRec_ { void *data; /**< 相关数据 */ void(*destroy_data)(void*); /**< 用于销毁数据的回调函数 */ LCUI_EventFunc func; /**< 事件处理函数 */ - LinkedListNode node; /**< 处理器列表中的节点 */ + list_node_t node; /**< 处理器列表中的节点 */ LCUI_EventRecord record; /**< 所属事件绑定记录 */ } LCUI_EventHandlerRec, *LCUI_EventHandler; static void DestroyEventHandler(void *data) { LCUI_EventHandler handler = data; - LinkedList_Unlink(&handler->record->handlers, &handler->node); + list_unlink(&handler->record->handlers, &handler->node); if (handler->destroy_data && handler->data) { handler->destroy_data(handler->data); } @@ -64,36 +64,36 @@ static void DestroyEventHandler(void *data) static void DestroyEventRecord(void *data) { - LinkedListNode *node; + list_node_t *node; LCUI_EventRecord record = data; while (record->handlers.length > 0) { - node = LinkedList_GetNode(&record->handlers, 0); + node = list_get_node(&record->handlers, 0); if (node) { DestroyEventHandler(node->data); } } - LinkedList_Clear(&record->trash, NULL); + list_destroy(&record->trash, NULL); free(record); } static void EventTrigger_RemoveHandler(LCUI_EventTrigger trigger, LCUI_EventHandler handler) { - LinkedListNode *node; + list_node_t *node; LCUI_EventRecord record = handler->record; if (record->blocked) { - for (LinkedList_Each(node, &record->trash)) { + for (list_each(node, &record->trash)) { if (node->data == handler) { return; } } - LinkedList_Append(&record->trash, handler); + list_append(&record->trash, handler); return; } - RBTree_Erase(&trigger->handlers, handler->id); + rbtree_delete_by_key(&trigger->handlers, handler->id); DestroyEventHandler(handler); if (record->handlers.length < 1) { - RBTree_Erase(&trigger->events, record->id); + rbtree_delete_by_key(&trigger->events, record->id); } } @@ -101,16 +101,16 @@ LCUI_EventTrigger EventTrigger(void) { LCUI_EventTrigger trigger = NEW(LCUI_EventTriggerRec, 1); trigger->handler_base_id = 1; - RBTree_Init(&trigger->handlers); - RBTree_Init(&trigger->events); - RBTree_OnDestroy(&trigger->events, DestroyEventRecord); + rbtree_init(&trigger->handlers); + rbtree_init(&trigger->events); + rbtree_set_destroy_func(&trigger->events, DestroyEventRecord); return trigger; } void EventTrigger_Destroy(LCUI_EventTrigger trigger) { - RBTree_Destroy(&trigger->events); - RBTree_Destroy(&trigger->handlers); + rbtree_destroy(&trigger->events); + rbtree_destroy(&trigger->handlers); free(trigger); } @@ -120,14 +120,14 @@ int EventTrigger_Bind(LCUI_EventTrigger trigger, int event_id, { LCUI_EventRecord record; LCUI_EventHandler handler; - record = RBTree_GetData(&trigger->events, event_id); + record = rbtree_get_data_by_key(&trigger->events, event_id); if (!record) { record = NEW(LCUI_EventRecordRec, 1); record->id = event_id; record->blocked = FALSE; - LinkedList_Init(&record->trash); - LinkedList_Init(&record->handlers); - RBTree_Insert(&trigger->events, event_id, record); + list_create(&record->trash); + list_create(&record->handlers); + rbtree_insert_by_key(&trigger->events, event_id, record); } handler = NEW(LCUI_EventHandlerRec, 1); handler->id = trigger->handler_base_id++; @@ -136,8 +136,8 @@ int EventTrigger_Bind(LCUI_EventTrigger trigger, int event_id, handler->func = func; handler->record = record; handler->node.data = handler; - LinkedList_AppendNode(&record->handlers, &handler->node); - RBTree_Insert(&trigger->handlers, handler->id, handler); + list_append_node(&record->handlers, &handler->node); + rbtree_insert_by_key(&trigger->handlers, handler->id, handler); return handler->id; } @@ -146,12 +146,12 @@ int EventTrigger_Unbind(LCUI_EventTrigger trigger, int event_id, { LCUI_EventRecord record; LCUI_EventHandler handler; - LinkedListNode *node = NULL; - record = RBTree_GetData(&trigger->events, event_id); + list_node_t *node = NULL; + record = rbtree_get_data_by_key(&trigger->events, event_id); if (!record) { return -1; } - for (LinkedList_Each(node, &record->handlers)) { + for (list_each(node, &record->handlers)) { handler = node->data; if (handler->func != func) { continue; @@ -165,7 +165,7 @@ int EventTrigger_Unbind(LCUI_EventTrigger trigger, int event_id, int EventTrigger_Unbind2(LCUI_EventTrigger trigger, int handler_id) { LCUI_EventHandler handler; - handler = RBTree_GetData(&trigger->handlers, handler_id); + handler = rbtree_get_data_by_key(&trigger->handlers, handler_id); if (!handler) { return -1; } @@ -178,12 +178,12 @@ int EventTrigger_Unbind3(LCUI_EventTrigger trigger, int event_id, { LCUI_EventRecord record; LCUI_EventHandler handler; - LinkedListNode *node = NULL; - record = RBTree_GetData(&trigger->events, event_id); + list_node_t *node = NULL; + record = rbtree_get_data_by_key(&trigger->events, event_id); if (!record) { return -1; } - for (LinkedList_Each(node, &record->handlers)) { + for (list_each(node, &record->handlers)) { handler = node->data; if (!compare_func(key, handler->data)) { continue; @@ -200,14 +200,14 @@ int EventTrigger_Trigger(LCUI_EventTrigger trigger, int event_id, void *arg) LCUI_EventRec e; LCUI_EventRecord record; LCUI_EventHandler handler; - LinkedListNode *node; - record = RBTree_GetData(&trigger->events, event_id); + list_node_t *node; + record = rbtree_get_data_by_key(&trigger->events, event_id); if (!record) { return count; } e.type = event_id; record->blocked = TRUE; - for (LinkedList_Each(node, &record->handlers)) { + for (list_each(node, &record->handlers)) { handler = node->data; e.data = handler->data; handler->func(&e, arg); @@ -217,9 +217,9 @@ int EventTrigger_Trigger(LCUI_EventTrigger trigger, int event_id, void *arg) while (record->trash.length > 0) { node = record->trash.head.next; handler = node->data; - RBTree_Erase(&trigger->handlers, handler->id); - LinkedList_Unlink(&record->handlers, &handler->node); - LinkedList_DeleteNode(&record->trash, node); + rbtree_delete_by_key(&trigger->handlers, handler->id); + list_unlink(&record->handlers, &handler->node); + list_delete_node(&record->trash, node); if (handler->destroy_data && handler->data) { handler->destroy_data(handler->data); } @@ -227,7 +227,7 @@ int EventTrigger_Trigger(LCUI_EventTrigger trigger, int event_id, void *arg) free(handler); } if (record->handlers.length < 1) { - RBTree_Erase(&trigger->events, record->id); + rbtree_delete_by_key(&trigger->events, record->id); } return count; } diff --git a/lib/util/src/linkedlist.c b/lib/util/src/linkedlist.c deleted file mode 100644 index 2c9c4045..00000000 --- a/lib/util/src/linkedlist.c +++ /dev/null @@ -1,217 +0,0 @@ -/* linkedlist.c -- Linked LinkedList - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -//#define DEBUG -#include -#include -#include - -void LinkedList_Init(LinkedList *list) -{ - list->length = 0; - list->head.next = list->tail.next = NULL; - list->head.data = list->tail.data = NULL; - list->head.prev = list->tail.prev = NULL; -} - -void LinkedList_Unlink(LinkedList *list, LinkedListNode *node) -{ - if (list->length > 0) { - list->length -= 1; - } - if (node->next) { - node->next->prev = node->prev; - } - if (node == list->tail.prev) { - list->tail.prev = node->prev; - } - if (node->prev) { - node->prev->next = node->next; - } - node->prev = NULL; - node->next = NULL; -} - -void LinkedList_ClearEx(LinkedList *list, void (*on_destroy)(void *), - int free_node) -{ - LinkedListNode *prev, *node; - node = list->tail.prev; - list->head.next = NULL; - list->tail.prev = NULL; - list->length = 0; - while (node && node != &list->head) { - prev = node->prev; - node->prev = NULL; - node->next = NULL; - if (node->data && on_destroy) { - on_destroy(node->data); - } - if (free_node) { - free(node); - } - node = prev; - } -} - -LinkedListNode *LinkedList_GetNodeAtTail(const LinkedList *list, size_t pos) -{ - LinkedListNode *node; - if (pos >= list->length) { - return NULL; - } - pos += 1; - node = list->tail.prev; - while (--pos >= 1 && node) { - node = node->prev; - } - return node; -} - -LinkedListNode *LinkedList_GetNode(const LinkedList *list, size_t pos) -{ - LinkedListNode *node; - if (pos >= list->length) { - return NULL; - } - if (pos > list->length / 2) { - pos = list->length - pos; - node = list->tail.prev; - while (--pos >= 1 && node) { - node = node->prev; - } - } else { - pos += 1; - node = list->head.next; - while (--pos >= 1 && node) { - node = node->next; - } - } - return node; -} - -void LinkedList_Link(LinkedList *list, LinkedListNode *cur, - LinkedListNode *node) -{ - node->prev = cur; - node->next = cur->next; - if (cur->next) { - cur->next->prev = node; - } - cur->next = node; - list->length += 1; -} - -void LinkedList_InsertNode(LinkedList *list, size_t pos, LinkedListNode *node) -{ - LinkedListNode *target; - target = LinkedList_GetNode(list, pos); - if (target) { - LinkedList_Link(list, target->prev, node); - } else { - LinkedList_AppendNode(list, node); - } -} - -LinkedListNode *LinkedList_Insert(LinkedList *list, size_t pos, void *data) -{ - LinkedListNode *node; - node = malloc(sizeof(LinkedListNode)); - node->data = data; - LinkedList_InsertNode(list, pos, node); - return node; -} - -void LinkedList_DeleteNode(LinkedList *list, LinkedListNode *node) -{ - LinkedList_Unlink(list, node); - node->data = NULL; - free(node); - node = NULL; -} - -void LinkedList_AppendNode(LinkedList *list, LinkedListNode *node) -{ - if (list->head.next) { - node->prev = list->tail.prev; - list->tail.prev->next = node; - list->tail.prev = node; - } else { - list->head.next = node; - list->tail.prev = node; - node->prev = &list->head; - } - node->next = NULL; - list->length += 1; -} - -void LinkedList_Delete(LinkedList *list, size_t pos) -{ - LinkedListNode *node = LinkedList_GetNode(list, pos); - LinkedList_DeleteNode(list, node); -} - -void *LinkedList_Get(const LinkedList *list, size_t pos) -{ - LinkedListNode *node = LinkedList_GetNode(list, pos); - return node ? node->data : NULL; -} - -LinkedListNode *LinkedList_Append(LinkedList *list, void *data) -{ - LinkedListNode *node; - node = malloc(sizeof(LinkedListNode)); - node->data = data; - node->next = NULL; - LinkedList_AppendNode(list, node); - return node; -} - -void LinkedListNode_Delete(LinkedListNode *node) -{ - free(node); -} - -void LinkedList_Concat(LinkedList *list1, LinkedList *list2) -{ - if (!list2->head.next) { - return; - } - if (list1->head.next) { - list1->tail.prev->next = list2->head.next; - list2->head.next->prev = list1->tail.prev; - } else { - list1->head.next = list2->head.next; - list1->head.next->prev = &list1->head; - } - list1->tail.prev = list2->tail.prev; - list2->head.next = list2->tail.prev = NULL; - list1->length += list2->length; - list2->length = 0; -} diff --git a/lib/util/src/logger.c b/lib/util/src/logger.c deleted file mode 100644 index 66f1acec..00000000 --- a/lib/util/src/logger.c +++ /dev/null @@ -1,106 +0,0 @@ -/* logger.c -- Logger module - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include - -#define BUFFER_SIZE 2048 - -static struct Logger { - char inited; - char buffer[BUFFER_SIZE]; - wchar_t bufferw[BUFFER_SIZE]; - void(*handler)(const char*); - void(*handlerw)(const wchar_t*); - LoggerLevel level; -} logger = { 0 }; - -void Logger_SetLevel(LoggerLevel level) -{ - logger.level = level; -} - -int Logger_Log(LoggerLevel level, const char* fmt, ...) -{ - int len; - va_list args; - - if (level < logger.level) { - return 0; - } - if (!logger.inited) { - logger.inited = 1; - } - va_start(args, fmt); - if (logger.handler) { - len = vsnprintf(logger.buffer, BUFFER_SIZE, fmt, args); - logger.buffer[BUFFER_SIZE - 1] = 0; - logger.handler(logger.buffer); - } else { - len = vprintf(fmt, args); - } - va_end(args); - return len; -} - -int Logger_LogW(LoggerLevel level, const wchar_t* fmt, ...) -{ - int len; - va_list args; - - if (level < logger.level) { - return 0; - } - if (!logger.inited) { - logger.inited = 1; - } - va_start(args, fmt); - if (logger.handlerw) { - len = vswprintf(logger.bufferw, BUFFER_SIZE, fmt, args); - logger.bufferw[BUFFER_SIZE - 1] = 0; - logger.handlerw(logger.bufferw); - } else { - len = vwprintf(fmt, args); - } - va_end(args); - return len; -} - -void Logger_SetHandler(void(*handler)(const char*)) -{ - logger.handler = handler; -} - -void Logger_SetHandlerW(void(*handler)(const wchar_t*)) -{ - logger.handlerw = handler; -} diff --git a/lib/util/src/math.c b/lib/util/src/math.c deleted file mode 100644 index eae57e00..00000000 --- a/lib/util/src/math.c +++ /dev/null @@ -1,28 +0,0 @@ -/* math.c -- Some extension functions for math - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ diff --git a/lib/util/src/object.c b/lib/util/src/object.c index 079523a2..e96ed492 100644 --- a/lib/util/src/object.c +++ b/lib/util/src/object.c @@ -34,14 +34,13 @@ #include #include #include -#include -#include +#include typedef struct LCUI_ObjectWatcherRec_ { void *data; LCUI_ObjectWatcherFunc func; LCUI_Object target; - LinkedListNode node; + list_node_t node; } LCUI_ObjectWatcherRec; LCUI_ObjectType ObjectType_New(const char *name) @@ -82,7 +81,7 @@ void Object_Destroy(LCUI_Object object) object->type->destroy(object); } if (object->watchers) { - LinkedList_ClearData(object->watchers, free); + list_destroy_without_node(object->watchers, free); free(object->watchers); } } @@ -154,11 +153,11 @@ LCUI_ObjectWatcher Object_Watch(LCUI_Object object, LCUI_ObjectWatcherFunc func, LCUI_ObjectWatcher watcher; if (!object->watchers) { - object->watchers = malloc(sizeof(LinkedList)); + object->watchers = malloc(sizeof(list_t)); if (!object->watchers) { return NULL; } - LinkedList_Init(object->watchers); + list_create(object->watchers); } watcher = malloc(sizeof(LCUI_ObjectWatcherRec)); if (!watcher) { @@ -168,20 +167,20 @@ LCUI_ObjectWatcher Object_Watch(LCUI_Object object, LCUI_ObjectWatcherFunc func, watcher->func = func; watcher->data = data; watcher->node.data = watcher; - LinkedList_AppendNode(object->watchers, &watcher->node); + list_append_node(object->watchers, &watcher->node); return watcher; } size_t Object_Notify(LCUI_Object object) { size_t count = 0; - LinkedListNode *node; + list_node_t *node; LCUI_ObjectWatcher watcher; if (!object->watchers) { return 0; } - for (LinkedList_Each(node, object->watchers)) { + for (list_each(node, object->watchers)) { watcher = node->data; watcher->func(object, watcher->data); ++count; @@ -191,7 +190,7 @@ size_t Object_Notify(LCUI_Object object) void ObjectWatcher_Delete(LCUI_ObjectWatcher watcher) { - LinkedList_Unlink(watcher->target->watchers, &watcher->node); + list_unlink(watcher->target->watchers, &watcher->node); free(watcher); } @@ -394,10 +393,10 @@ LCUI_Object WString_New(const wchar_t *value) static void WString_ToString(LCUI_Object str, LCUI_Object newstr) { - const size_t len = LCUI_EncodeUTF8String(NULL, str->value.wstring, 0) + 1; + const size_t len = encode_utf8(NULL, str->value.wstring, 0) + 1; String_Realloc(newstr, len); - LCUI_EncodeUTF8String(newstr->value.string, str->value.wstring, len); + encode_utf8(newstr->value.string, str->value.wstring, len); } void Number_Init(LCUI_Object object, double value) diff --git a/lib/util/src/parse.c b/lib/util/src/parse.c index 507487f7..0b6b4674 100644 --- a/lib/util/src/parse.c +++ b/lib/util/src/parse.c @@ -361,7 +361,7 @@ LCUI_BOOL ParseFontWeight(const char *str, int *weight) *weight = FONT_WEIGHT_THIN; return TRUE; } - *weight = iround(value / 100.0) * 100; + *weight = y_iround(value / 100.0) * 100; return TRUE; } diff --git a/lib/util/src/rbtree.c b/lib/util/src/rbtree.c deleted file mode 100644 index 1dea4979..00000000 --- a/lib/util/src/rbtree.c +++ /dev/null @@ -1,544 +0,0 @@ -/* rbtree.c -- Red Black Trees - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include - -#include -#include - -#define RED 0 -#define BLACK 1 - -/** 初始化红黑树 */ -void RBTree_Init(RBTree *rbt) -{ - rbt->root = NULL; - rbt->compare = NULL; - rbt->destroy = NULL; - rbt->total_node = 0; -} - -static void DestroyRBTreeNode(RBTree *rbt, RBTreeNode *node) -{ - if (!node) { - return; - } - DestroyRBTreeNode(rbt, node->left); - DestroyRBTreeNode(rbt, node->right); - if (node->parent) { - if (node->parent->left == node) { - node->parent->left = NULL; - } else { - node->parent->right = NULL; - } - } - if (rbt->destroy && node->data) { - rbt->destroy(node->data); - } - node->data = NULL; - free(node); -} - -/** 销毁红黑树 */ -void RBTree_Destroy(RBTree *rbt) -{ - rbt->total_node = 0; - DestroyRBTreeNode(rbt, rbt->root); - rbt->root = NULL; -} - -/** 获取第一个结点 */ -RBTreeNode *RBTree_First(const RBTree *rbt) -{ - RBTreeNode *node; - - node = rbt->root; - if (!node) { - return NULL; - } - while (node->left) { - node = node->left; - } - return node; -} - -/** 获取下一个结点 */ -RBTreeNode *RBTree_Next(const RBTreeNode *node) -{ - RBTreeNode *parent; - - if (node->parent == node) { - return NULL; - } - if (node->right) { - node = node->right; - while (node->left) { - node = node->left; - } - return (RBTreeNode*)node; - } - while ((parent = node->parent) && node == parent->right) { - node = parent; - } - return parent; -} - -/** - * 树的左旋 - * - * node right - * / \ ==> / \ - * a right node y - * / \ / \ - * b y a b - */ -static RBTreeNode* -rb_rotate_left(RBTreeNode* node, RBTreeNode* root) -{ - RBTreeNode* right = node->right; - - if ((node->right = right->left)) { - right->left->parent = node; - } - right->left = node; - - if ((right->parent = node->parent)) { - if (node == node->parent->right) { - node->parent->right = right; - } else { - node->parent->left = right; - } - } else { - root = right; - } - node->parent = right; - - return root; -} - -/** - * 树的右旋 - * - * node left - * / \ / \ - * left y ==> a node - * / \ / \ - * a b b y - */ -static RBTreeNode* -rb_rotate_right(RBTreeNode* node, RBTreeNode* root) -{ - RBTreeNode* left = node->left; - - if ((node->left = left->right)) { - left->right->parent = node; - } - left->right = node; - - if ((left->parent = node->parent)) { - if (node == node->parent->right) { - node->parent->right = left; - } else { - node->parent->left = left; - } - } else { - root = left; - } - node->parent = left; - - return root; -} - -static RBTreeNode* -rb_insert_rebalance(RBTreeNode *root, RBTreeNode *node) -{ - RBTreeNode *parent, *gparent, *uncle, *tmp; - - while ((parent = node->parent) && parent->color == RED) { - gparent = parent->parent; - - if (parent == gparent->left) { - uncle = gparent->right; - if (uncle && uncle->color == RED) { - uncle->color = BLACK; - parent->color = BLACK; - gparent->color = RED; - node = gparent; - } else { - if (parent->right == node) { - root = rb_rotate_left(parent, root); - tmp = parent; - parent = node; - node = tmp; - } - parent->color = BLACK; - gparent->color = RED; - root = rb_rotate_right(gparent, root); - } - } else { - uncle = gparent->left; - if (uncle && uncle->color == RED) { - uncle->color = BLACK; - parent->color = BLACK; - gparent->color = RED; - node = gparent; - } else { - if (parent->left == node) { - root = rb_rotate_right(parent, root); - tmp = parent; - parent = node; - node = tmp; - } - parent->color = BLACK; - gparent->color = RED; - root = rb_rotate_left(gparent, root); - } - } - } - - root->color = BLACK; - return root; -} - -/** 红黑树查找结点 */ -static RBTreeNode* -rb_search_auxiliary(RBTreeNode *root, int key, const void *keydata, - int(*cmp)(void*, const void*), RBTreeNode **save) -{ - int ret; - RBTreeNode *node = root, *parent = NULL; - - while (node) { - parent = node; - if (cmp && keydata) { - ret = cmp(node->data, keydata); - if (ret > 0) { - node = node->left; - } else if (ret < 0) { - node = node->right; - } else { - return node; - } - continue; - } - if (node->key > key) { - node = node->left; - } else if (node->key < key) { - node = node->right; - } else { - return node; - } - } - if (save) { - *save = parent; - } - return NULL; -} - -RBTreeNode* RBTree_CustomSearch(RBTree* rbt, const void *keydata) -{ - return rb_search_auxiliary(rbt->root, 0, keydata, rbt->compare, NULL); -} - -RBTreeNode* RBTree_Search(RBTree* rbt, int key) -{ - return rb_search_auxiliary(rbt->root, key, NULL, rbt->compare, NULL); -} - -void* RBTree_CustomGetData(RBTree* rbt, const void *keydata) -{ - RBTreeNode *node; - node = rb_search_auxiliary(rbt->root, 0, keydata, rbt->compare, NULL); - if (node) { - return node->data; - } - return NULL; -} - -void* RBTree_GetData(RBTree* rbt, int key) -{ - RBTreeNode *node; - node = rb_search_auxiliary(rbt->root, key, NULL, rbt->compare, NULL); - if (node) { - return node->data; - } - return NULL; -} - -static RBTreeNode* -rb_insert(RBTree *rbt, int key, const void *keydata, void *data) -{ - RBTreeNode *root, *node, *parent_node; - - parent_node = NULL; - root = rbt->root; - node = rb_search_auxiliary(root, key, keydata, - rbt->compare, &parent_node); - if (node) { - return NULL; - } - - node = (RBTreeNode*)malloc(sizeof(RBTreeNode)); - node->left = NULL; - node->parent = parent_node; - node->right = NULL; - node->data = data; - node->key = key; - node->color = RED; - - if (parent_node) { - if (rbt->compare && keydata) { - if (rbt->compare(parent_node->data, keydata) > 0) { - parent_node->left = node; - } else { - parent_node->right = node; - } - } else { - if (parent_node->key > key) { - parent_node->left = node; - } else { - parent_node->right = node; - } - } - } else { - root = node; - } - rbt->total_node += 1; - /* 调整红黑树的平衡 */ - rbt->root = rb_insert_rebalance(root, node); - return node; -} - -RBTreeNode* RBTree_Insert(RBTree *rbt, int key, void *data) -{ - return rb_insert(rbt, key, NULL, data); -} - -RBTreeNode* RBTree_CustomInsert(RBTree *rbt, const void *keydata, void *data) -{ - return rb_insert(rbt, 0, keydata, data); -} - -/** 在树中的结点被删除后调整平衡 */ -static RBTreeNode* -rb_erase_rebalance(RBTreeNode *node, RBTreeNode *parent, - RBTreeNode *root) -{ - RBTreeNode *other, *o_left, *o_right; - - while ((!node || node->color == BLACK) && node != root) { - if (parent->left == node) { - other = parent->right; - if (other->color == RED) { - other->color = BLACK; - parent->color = RED; - root = rb_rotate_left(parent, root); - other = parent->right; - } - if ((!other->left || other->left->color == BLACK) - && (!other->right || other->right->color == BLACK)) { - other->color = RED; - node = parent; - parent = node->parent; - continue; - } - if (!other->right || other->right->color == BLACK) { - if ((o_left = other->left)) { - o_left->color = BLACK; - } - other->color = RED; - root = rb_rotate_right(other, root); - other = parent->right; - } - other->color = parent->color; - parent->color = BLACK; - if (other->right) { - other->right->color = BLACK; - } - root = rb_rotate_left(parent, root); - node = root; - break; - } - - other = parent->left; - if (other->color == RED) { - other->color = BLACK; - parent->color = RED; - root = rb_rotate_right(parent, root); - other = parent->left; - } - if ((!other->left || other->left->color == BLACK) - && (!other->right || other->right->color == BLACK)) { - other->color = RED; - node = parent; - parent = node->parent; - continue; - } - - if (!other->left || other->left->color == BLACK) { - if ((o_right = other->right)) { - o_right->color = BLACK; - } - other->color = RED; - root = rb_rotate_left(other, root); - other = parent->left; - } - other->color = parent->color; - parent->color = BLACK; - if (other->left) { - other->left->color = BLACK; - } - root = rb_rotate_right(parent, root); - node = root; - break; - } - - if (node) { - node->color = BLACK; - } - return root; -} - -static void rb_erase_by_node(RBTree *rbt, RBTreeNode *node) -{ - unsigned char color; - RBTreeNode *parent; - RBTreeNode *old = node; - RBTreeNode *child = NULL; - RBTreeNode *root = rbt->root; - if (node->left && node->right) { - RBTreeNode *left; - node = node->right; - while ((left = node->left) != NULL) { - node = left; - } - child = node->right; - parent = node->parent; - color = node->color; - - if (child) { - child->parent = parent; - } - if (parent) { - if (parent->left == node) { - parent->left = child; - } else { - parent->right = child; - } - } else { - root = child; - } - - if (node->parent == old) { - parent = node; - } - - node->parent = old->parent; - node->color = old->color; - node->right = old->right; - node->left = old->left; - - if (old->parent) { - if (old->parent->left == old) { - old->parent->left = node; - } else { - old->parent->right = node; - } - } else { - root = node; - } - - old->left->parent = node; - if (old->right) { - old->right->parent = node; - } - } else { - if (!node->left) { - child = node->right; - } else if (!node->right) { - child = node->left; - } - parent = node->parent; - color = node->color; - - if (child) { - child->parent = parent; - } - if (parent) { - if (parent->left == node) { - parent->left = child; - } else { - parent->right = child; - } - } else { - root = child; - } - } - - if (rbt->destroy && old->data) { - rbt->destroy(old->data); - } - free(old); - if (color == BLACK) { - /* 恢复红黑树性质 */ - root = rb_erase_rebalance(child, parent, root); - } - rbt->root = root; - rbt->total_node -= 1; -} - -/** 删除红黑树中的结点 */ -static int rb_erase(RBTree *rbt, int key, const void *keydata) -{ - RBTreeNode *node; - /* 查找要删除的结点 */ - node = rb_search_auxiliary(rbt->root, key, keydata, - rbt->compare, NULL); - if (!node) { - return -1; - } - rb_erase_by_node(rbt, node); - return 0; -} - -int RBTree_Erase(RBTree *rbt, int key) -{ - return rb_erase(rbt, key, NULL); -} - -void RBTree_EraseNode(RBTree *rbt, RBTreeNode *node) -{ - rb_erase_by_node(rbt, node); -} - -int RBTree_CustomErase(RBTree *rbt, const void *keydata) -{ - return rb_erase(rbt, 0, keydata); -} diff --git a/lib/util/src/rect.c b/lib/util/src/rect.c index 8778034a..3cc836cf 100644 --- a/lib/util/src/rect.c +++ b/lib/util/src/rect.c @@ -51,18 +51,18 @@ void LCUIRect_ToRectF(const LCUI_Rect *rect, LCUI_RectF *rectf, float scale) void LCUIRect_Scale(const LCUI_Rect *src, LCUI_Rect *dst, float scale) { - dst->x = iround(src->x * scale); - dst->y = iround(src->y * scale); - dst->width = iround(src->width * scale); - dst->height = iround(src->height * scale); + dst->x = y_iround(src->x * scale); + dst->y = y_iround(src->y * scale); + dst->width = y_iround(src->width * scale); + dst->height = y_iround(src->height * scale); } void LCUIRectF_ToRect(const LCUI_RectF *rectf, LCUI_Rect *rect, float scale) { - rect->x = iround(rectf->x * scale); - rect->y = iround(rectf->y * scale); - rect->width = iround(rectf->width * scale); - rect->height = iround(rectf->height * scale); + rect->x = y_iround(rectf->x * scale); + rect->y = y_iround(rectf->y * scale); + rect->width = y_iround(rectf->width * scale); + rect->height = y_iround(rectf->height * scale); } /* FIXME: need new shorter name */ @@ -296,8 +296,8 @@ void LCUIRect_MergeRect(LCUI_Rect *big, const LCUI_Rect *a, const LCUI_Rect *b) } else { big->height = a->y + a->height; } - big->x = min(a->x, b->x); - big->y = min(a->y, b->y); + big->x = y_min(a->x, b->x); + big->y = y_min(a->y, b->y); big->width -= big->x; big->height -= big->y; } @@ -314,8 +314,8 @@ void LCUIRectF_MergeRect(LCUI_RectF *big, const LCUI_RectF *a, const LCUI_RectF } else { big->height = a->y + a->height; } - big->x = min(a->x, b->x); - big->y = min(a->y, b->y); + big->x = y_min(a->x, b->x); + big->y = y_min(a->y, b->y); big->width -= big->x; big->height -= big->y; } @@ -411,17 +411,17 @@ void LCUIRect_Split(LCUI_Rect *base, LCUI_Rect *target, LCUI_Rect rects[4]) rects[3].height = 0; } -int RectList_AddEx(LinkedList *list, LCUI_Rect *rect, LCUI_BOOL auto_merge) +int RectList_AddEx(list_t *list, LCUI_Rect *rect, LCUI_BOOL auto_merge) { int x_distance, y_distance; LCUI_Rect *p, union_rect; - LinkedListNode *node, *prev; + list_node_t *node, *prev; if (rect->width <= 0 || rect->height <= 0) { return -1; } - for (LinkedList_Each(node, list)) { + for (list_each(node, list)) { p = node->data; /* 如果被现有的矩形包含 */ if (LCUIRect_IsIncludeRect(p, rect)) { @@ -431,7 +431,7 @@ int RectList_AddEx(LinkedList *list, LCUI_Rect *rect, LCUI_BOOL auto_merge) if (LCUIRect_IsIncludeRect(rect, p)) { prev = node->prev; free(node->data); - LinkedList_DeleteNode(list, node); + list_delete_node(list, node); node = prev; continue; } @@ -444,42 +444,42 @@ int RectList_AddEx(LinkedList *list, LCUI_Rect *rect, LCUI_BOOL auto_merge) (y_distance <= 10 && y_distance >= -10)) { LCUIRect_MergeRect(&union_rect, p, rect); free(node->data); - LinkedList_DeleteNode(list, node); + list_delete_node(list, node); return RectList_Add(list, &union_rect); } } p = NEW(LCUI_Rect, 1); *p = *rect; - LinkedList_Append(list, p); + list_append(list, p); return 0; } -int RectList_Add(LinkedList *list, LCUI_Rect *rect) +int RectList_Add(list_t *list, LCUI_Rect *rect) { return RectList_AddEx(list, rect, TRUE); } -int RectList_Delete(LinkedList *list, LCUI_Rect *rect) +int RectList_Delete(list_t *list, LCUI_Rect *rect) { int i; LCUI_BOOL deletable; LCUI_Rect *p, child_rects[4]; - LinkedList extra_list; - LinkedListNode *prev, *node; + list_t extra_list; + list_node_t *prev, *node; if (rect->width <= 0 || rect->height <= 0) { return -1; } - LinkedList_Init(&extra_list); - for (LinkedList_Each(node, list)) { + list_create(&extra_list); + for (list_each(node, list)) { p = node->data; /* 如果包含现有的矩形 */ if (LCUIRect_IsIncludeRect(rect, p)) { prev = node->prev; free(node->data); - LinkedList_DeleteNode(list, node); + list_delete_node(list, node); node = prev; continue; } @@ -496,13 +496,13 @@ int RectList_Delete(LinkedList *list, LCUI_Rect *rect) if (deletable) { prev = node->prev; free(node->data); - LinkedList_DeleteNode(list, node); + list_delete_node(list, node); node = prev; deletable = FALSE; } RectList_AddEx(&extra_list, &child_rects[i], FALSE); } } - LinkedList_Concat(list, &extra_list); + list_concat(list, &extra_list); return 1; } diff --git a/lib/util/src/string.c b/lib/util/src/string.c deleted file mode 100644 index 3b3729ae..00000000 --- a/lib/util/src/string.c +++ /dev/null @@ -1,332 +0,0 @@ -/* string.c -- The string operation set. - * - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include -#include - -#define STRTRIM_CODE(TYPE, OUTSTR, INSTR, CHARLIST, DCHARLIST) \ - LCUI_BOOL clear, clear_left = TRUE; \ - TYPE *op = OUTSTR, *last_blank = NULL; \ - const TYPE *default_charlist = DCHARLIST, *ip = INSTR, *c; \ - \ - if (!CHARLIST) { \ - CHARLIST = default_charlist; \ - } \ - for (; *ip; ip++) { \ - for (clear = FALSE, c = CHARLIST; *c; ++c) { \ - if (*ip == *c) { \ - clear = TRUE; \ - break; \ - } \ - } \ - if (clear) { \ - if (!clear_left) { \ - *op = *ip; \ - if (!last_blank) { \ - last_blank = op; \ - } \ - ++op; \ - } \ - continue; \ - } \ - if (clear_left) { \ - clear_left = FALSE; \ - } \ - last_blank = NULL; \ - *op = *ip; \ - ++op; \ - } \ - if (last_blank) { \ - *last_blank = 0; \ - } \ - *op = 0; \ - return op - outstr; - -size_t strsize(const char *str) -{ - if (!str) { - return sizeof(char); - } - return (strlen(str) + 1) * sizeof(char); -} - -size_t wcssize(const wchar_t *str) -{ - if (!str) { - return sizeof(wchar_t); - } - return (wcslen(str) + 1) * sizeof(wchar_t); -} - -size_t strtolower(char *outstr, const char *instr) -{ - char *op = outstr; - const char *ip = instr; - for (; *ip; ++ip, ++op) { - *op = tolower(*ip); - } - *op = 0; - return ip - instr; -} - -size_t strntolower(char *outstr, size_t max_len, const char *instr) -{ - char *op = outstr; - const char *ip = instr; - for (; *ip && max_len > 1; ++ip, ++op, --max_len) { - *op = tolower(*ip); - } - *op = 0; - return ip - instr; -} - -char *strdup2(const char *str) -{ - size_t len = strlen(str) + 1; - char *out = malloc(sizeof(char) * len); - if (!out) { - return NULL; - } - strcpy(out, str); - return out; -} - -wchar_t *wcsdup2(const wchar_t *str) -{ - size_t len = wcslen(str) + 1; - wchar_t *out = malloc(sizeof(wchar_t) * len); - if (!out) { - return NULL; - } - wcscpy(out, str); - return out; -} - -size_t strtrim(char *outstr, const char *instr, const char *charlist) -{ - STRTRIM_CODE(char, outstr, instr, charlist, "\t\n\r "); -} - -size_t wcstrim(wchar_t *outstr, const wchar_t *instr, const wchar_t *charlist) -{ - STRTRIM_CODE(wchar_t, outstr, instr, charlist, L"\t\n\r "); -} - -unsigned strhash(unsigned hash, const char *str) -{ - const unsigned char *p = (unsigned char *)str; - - while (*p) { - hash = ((hash << 5) + hash) + (*p++); - } - return hash; -} - -size_t strreplace(char *str, size_t max_len, const char *substr, - const char *newstr) -{ - size_t len, buf_len; - char *buf, *pout, *pin; - - pin = strstr(str, substr); - if (!pin) { - return 0; - } - len = strlen(newstr); - buf_len = strlen(str) + len + 1; - buf = malloc(buf_len * sizeof(wchar_t)); - strcpy(buf, str); - pout = buf + (pin - str); - strcpy(pout, newstr); - pin += strlen(substr); - pout += len; - strcpy(pout, pin); - buf[buf_len - 1] = 0; - strncpy(str, buf, max_len); - free(buf); - return min(buf_len, max_len); -} - -size_t wcsreplace(wchar_t *str, size_t max_len, const wchar_t *substr, - const wchar_t *newstr) -{ - size_t len, buf_len; - wchar_t *buf, *pout, *pin; - - pin = wcsstr(str, substr); - if (!pin) { - return 0; - } - len = wcslen(newstr); - buf_len = wcslen(str) + len + 1; - buf = malloc(buf_len * sizeof(wchar_t)); - wcscpy(buf, str); - pout = buf + (pin - str); - wcscpy(pout, newstr); - pin += wcslen(substr); - pout += len; - wcscpy(pout, pin); - buf[buf_len - 1] = 0; - wcsncpy(str, buf, max_len); - free(buf); - return min(buf_len, max_len); -} - -int cmdsplit(const char *cmd, char ***outargv) -{ - size_t size; - char **argv = NULL, **tmp; - const char *cur = cmd, *p = NULL; - int argc = 0, spaces = 0, qoutes = 0, len = 0; - - if (outargv) { - argv = malloc(sizeof(char *)); - if (!argv) { - return -ENOMEM; - } - argv[0] = NULL; - } - while (1) { - switch (*cur) { - case 0: - case '\n': - case '\r': - case '\t': - case ' ': - if (*cur != 0) { - if (spaces != 0) { - break; - } - ++spaces; - if (qoutes > 0 && qoutes % 2 != 0) { - ++len; - break; - } - } - if (argv && len > 0) { - size = sizeof(char *) * (argc + 2); - tmp = realloc(argv, size); - if (!tmp) { - goto faild; - } - len += 1; - argv = tmp; - argv[argc + 1] = NULL; - size = sizeof(char) * len; - argv[argc] = malloc(size); - if (!argv[argc]) { - goto faild; - } - len -= 1; - strncpy(argv[argc], p, len); - argv[argc][len] = 0; - } - p = NULL; - if (len > 0) { - ++argc; - } - qoutes = 0; - len = 0; - if (*cur == 0) { - goto done; - } - break; - case '"': - ++qoutes; - default: - if (!p) { - p = cur; - } - spaces = 0; - ++len; - break; - } - ++cur; - } - -done: - if (argv) { - *outargv = argv; - } - return argc; - -faild: - argc += 1; - while (argc-- > 0) { - if (argv[argc]) { - free(argv[argc]); - argv[argc] = NULL; - } - } - free(argv); - return -ENOMEM; -} - -int strsplit(const char *instr, const char *sep, char ***outstrs) -{ - int i = 0; - const char *prev = instr; - size_t len, sep_len = strlen(sep); - char *next = strstr(prev, sep); - char **newstrs = NULL; - - while (1) { - char **tmp, *str; - if (next) { - len = next - prev + 1; - } else { - len = strlen(prev) + 1; - } - str = malloc(sizeof(char) * len); - tmp = realloc(newstrs, sizeof(char *) * (i + 2)); - if (!tmp) { - strlist_free(newstrs); - return 0; - } - newstrs = tmp; - strncpy(str, prev, len - 1); - str[len - 1] = 0; - newstrs[i] = str; - newstrs[i + 1] = NULL; - if (next) { - prev = next + sep_len; - } else { - break; - } - next = strstr(prev, sep); - i += 1; - } - *outstrs = newstrs; - return i + 1; -} diff --git a/lib/util/src/strlist.c b/lib/util/src/strlist.c deleted file mode 100644 index cf348be9..00000000 --- a/lib/util/src/strlist.c +++ /dev/null @@ -1,226 +0,0 @@ -/* - * strlist.c -- string list - * - * Copyright (c) 2019, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include -#include -#include - -static strpool_t *pool = NULL; - -int sortedstrlist_add(strlist_t *strlist, const char *str) -{ - int i, pos, n; - strlist_t newlist; - - if (*strlist) { - for (i = 0; (*strlist)[i]; ++i) - ; - n = i + 2; - } else { - n = 2; - } - newlist = realloc(*strlist, sizeof(char *) * n); - if (!newlist) { - return -ENOMEM; - } - newlist[n - 2] = NULL; - for (i = 0, pos = -1; newlist[i]; ++i) { - int tmp = strcmp(newlist[i], str); - if (tmp < 0) { - continue; - } else if (tmp == 0) { - return 1; - } else { - pos = i; - break; - } - } - if (!pool) { - pool = strpool_create(); - } - if (pos >= 0) { - for (i = n - 2; i > pos; --i) { - newlist[i] = newlist[i - 1]; - } - } else { - pos = n - 2; - } - newlist[pos] = strpool_alloc_str(pool, str); - newlist[n - 1] = NULL; - *strlist = newlist; - return 0; -} - -int strlist_add_one(strlist_t *strlist, const char *str) -{ - int i = 0; - char **newlist; - - if (!*strlist) { - newlist = (char **)malloc(sizeof(char *) * 2); - goto check_done; - } - for (i = 0; (*strlist)[i]; ++i) { - if (strcmp((*strlist)[i], str) == 0) { - return 1; - } - } - newlist = (char **)realloc(*strlist, (i + 2) * sizeof(char *)); - -check_done: - if (!newlist) { - return -ENOMEM; - } - if (!pool) { - pool = strpool_create(); - } - newlist[i] = strpool_alloc_str(pool, str); - newlist[i + 1] = NULL; - *strlist = newlist; - return 0; -} - -int strlist_add(strlist_t *strlist, const char *str) -{ - char buff[256]; - int count = 0, i, head; - - for (head = 0, i = 0; str[i]; ++i) { - if (str[i] != ' ') { - continue; - } - if (i > head) { - strncpy(buff, &str[head], i - head); - buff[i - head] = 0; - if (strlist_add_one(strlist, buff) == 0) { - count += 1; - } - } - head = i + 1; - } - if (i > head) { - strncpy(buff, &str[head], i - head); - buff[i - head] = 0; - if (strlist_add_one(strlist, buff) == 0) { - count += 1; - } - } - return count; -} - -int strlist_has(strlist_t strlist, const char *str) -{ - int i; - if (!strlist) { - return 0; - } - for (i = 0; strlist[i]; ++i) { - if (strcmp(strlist[i], str) == 0) { - return 1; - } - } - return 0; -} - -int strlist_remove_one(strlist_t *strlist, const char *str) -{ - int i, pos, len; - strlist_t newlist; - - if (!*strlist) { - return 0; - } - for (len = 0; (*strlist)[len]; ++len) - ; - for (pos = -1, i = 0; i < len; ++i) { - if (strcmp((*strlist)[i], str) == 0) { - pos = i; - break; - } - } - if (pos == -1) { - return 0; - } - strpool_free_str((*strlist)[pos]); - if (pos == 0 && len < 2) { - free(*strlist); - *strlist = NULL; - return 1; - } - newlist = (char **)malloc(len * sizeof(char *)); - for (i = 0; i < pos; ++i) { - newlist[i] = (*strlist)[i]; - } - for (i = pos; i < len; ++i) { - newlist[i] = (*strlist)[i + 1]; - } - newlist[len - 1] = NULL; - free(*strlist); - *strlist = newlist; - return 1; -} - -int strlist_remove(strlist_t *strlist, const char *str) -{ - char buff[256]; - int count = 0, i, head; - - for (head = 0, i = 0; str[i]; ++i) { - if (str[i] != ' ') { - continue; - } - if (i - 1 > head) { - strncpy(buff, &str[head], i - head); - buff[i - head] = 0; - count += strlist_remove_one(strlist, buff); - } - head = i + 1; - } - if (i - 1 > head) { - strncpy(buff, &str[head], i - head); - buff[i - head] = 0; - count += strlist_remove_one(strlist, buff); - } - return count; -} - -void strlist_free(strlist_t strlist) -{ - int i = 0; - while (strlist[i]) { - strpool_free_str(strlist[i]); - ++i; - } - free(strlist); -} diff --git a/lib/util/src/strpool.c b/lib/util/src/strpool.c deleted file mode 100644 index dab54477..00000000 --- a/lib/util/src/strpool.c +++ /dev/null @@ -1,129 +0,0 @@ -/* - * strpool.c -- string pool - * - * Copyright (c) 2019, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include -#include -#include -#include -#include -#include - -#define STRPOOL_MARK 6699 - -typedef struct strpool_entry strpool_entry_t; - -struct strpool { - size_t size; - DictType type; - Dict *dict; -}; - -struct strpool_entry { - int32_t mark; - strpool_t *pool; - size_t count; - size_t length; - char *string; -}; - -strpool_t *strpool_create(void) -{ - strpool_t *pool; - - pool = malloc(sizeof(strpool_t)); - if (!pool) { - return NULL; - } - pool->size = 0; - Dict_InitStringKeyType(&pool->type); - pool->dict = Dict_Create(&pool->type, NULL); - return pool; -} - -char *strpool_alloc_str(strpool_t *pool, const char *str) -{ - size_t size; - size_t length; - strpool_entry_t *entry; - - entry = Dict_FetchValue(pool->dict, str); - if (!entry) { - length = strlen(str); - size = sizeof(strpool_entry_t) + length + 1; - entry = malloc(size); - if (!entry) { - return NULL; - } - entry->mark = STRPOOL_MARK; - entry->pool = pool; - entry->count = 0; - entry->length = length; - entry->string = ((char *)entry) + sizeof(strpool_entry_t); - strcpy(entry->string, str); - if (Dict_Add(pool->dict, entry->string, entry) != 0) { - free(entry); - return NULL; - } - pool->size += size; - } - entry->count += 1; - return entry->string; -} - -int strpool_free_str(char *str) -{ - strpool_entry_t *entry; - - entry = (strpool_entry_t *)(str - sizeof(strpool_entry_t)); - if (entry->mark != STRPOOL_MARK) { - return -1; - } - entry->count -= 1; - if (entry->count > 0) { - return 0; - } - entry->pool->size -= sizeof(strpool_entry_t) + strlen(str) + 1; - Dict_Delete(entry->pool->dict, str); - free(entry); - return 0; -} - -size_t strpool_size(strpool_t *pool) -{ - return pool->size; -} - -void strpool_destroy(strpool_t *pool) -{ - pool->size = 0; - Dict_Release(pool->dict); - free(pool); -} diff --git a/lib/util/src/time.c b/lib/util/src/time.c deleted file mode 100644 index abe31a62..00000000 --- a/lib/util/src/time.c +++ /dev/null @@ -1,114 +0,0 @@ -/* time.c -- The time operation set. - * - * Copyright (c) 2018, Liu chao All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of LCUI nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - - -#include -#include -#include -#include - -#define TIME_WRAP_VALUE (~(int64_t)0) - -#ifdef LCUI_BUILD_IN_WIN32 -#include - -static int hires_timer_available = 0; /**< 标志,指示高精度计数器是否可用 */ -static LONGLONG hires_ticks_per_second; /**< 高精度计数器每秒的滴答数 */ - -void LCUITime_Init(void) -{ - LARGE_INTEGER hires; - if (QueryPerformanceFrequency(&hires)) { - hires_timer_available = 1; - hires_ticks_per_second = hires.QuadPart; - } -} - -int64_t LCUI_GetTime(void) -{ - int64_t time; - LARGE_INTEGER hires_now; - FILETIME *ft = (FILETIME*)&time; - if (hires_timer_available) { - QueryPerformanceCounter(&hires_now); - time = hires_now.QuadPart * 1000; - return time / hires_ticks_per_second; - } - GetSystemTimeAsFileTime(ft); - return time / 1000 - 11644473600000; -} - -#elif defined LCUI_BUILD_IN_LINUX -#include -#include - - -void LCUITime_Init(void) -{ - return; -} - -int64_t LCUI_GetTime(void) -{ - int64_t t; - struct timeval tv; - - gettimeofday(&tv, NULL); - t = tv.tv_sec * 1000 + tv.tv_usec / 1000; - return t; -} - -#endif - -int64_t LCUI_GetTimeDelta(int64_t start) -{ - int64_t now = LCUI_GetTime(); - if (now < start) { - return (TIME_WRAP_VALUE - start) + now; - } - return now - start; -} - -void LCUI_Sleep(unsigned int s) -{ -#ifdef LCUI_BUILD_IN_WIN32 - Sleep(s * 1000); -#else - sleep(s); -#endif -} - -void LCUI_MSleep(unsigned int ms) -{ -#ifdef LCUI_BUILD_IN_WIN32 - Sleep(ms); -#else - usleep(ms * 1000); -#endif -} diff --git a/lib/util/xmake.lua b/lib/util/xmake.lua index b0a8c1e8..8b4363c6 100644 --- a/lib/util/xmake.lua +++ b/lib/util/xmake.lua @@ -1,3 +1,4 @@ target("lcui-util") set_kind("static") + add_deps("yutil") add_files("src/*.c") diff --git a/lib/worker/src/worker.c b/lib/worker/src/worker.c index e89e3995..42991c44 100644 --- a/lib/worker/src/worker.c +++ b/lib/worker/src/worker.c @@ -34,14 +34,13 @@ #include #include #include -#include -#include +#include #include #include typedef struct LCUI_WorkerRec_ { LCUI_BOOL active; /**< 是否处于活动状态 */ - LinkedList tasks; /**< 任务队列 */ + list_t tasks; /**< 任务队列 */ LCUI_Mutex mutex; /**< 互斥锁 */ LCUI_Cond cond; /**< 条件变量 */ LCUI_Thread thread; /**< 所在的线程 */ @@ -52,7 +51,7 @@ LCUI_Worker LCUIWorker_New(void) LCUI_Worker worker = NEW(LCUI_WorkerRec, 1); LCUIMutex_Init(&worker->mutex); LCUICond_Init(&worker->cond); - LinkedList_Init(&worker->tasks); + list_create(&worker->tasks); worker->active = FALSE; worker->thread = 0; return worker; @@ -64,7 +63,7 @@ void LCUIWorker_PostTask(LCUI_Worker worker, LCUI_Task task) newtask = NEW(LCUI_TaskRec, 1); *newtask = *task; LCUIMutex_Lock(&worker->mutex); - LinkedList_Append(&worker->tasks, newtask); + list_append(&worker->tasks, newtask); LCUICond_Signal(&worker->cond); LCUIMutex_Unlock(&worker->mutex); } @@ -72,14 +71,14 @@ void LCUIWorker_PostTask(LCUI_Worker worker, LCUI_Task task) LCUI_Task LCUIWorker_GetTask(LCUI_Worker worker) { LCUI_Task task; - LinkedListNode *node; + list_node_t *node; - node = LinkedList_GetNode(&worker->tasks, 0); + node = list_get_node(&worker->tasks, 0); if (!node) { return NULL; } task = node->data; - LinkedList_Unlink(&worker->tasks, node); + list_unlink(&worker->tasks, node); free(node); return task; } @@ -108,7 +107,7 @@ static void OnDeleteTask(void *arg) static void LCUIWorker_ExecDestroy(LCUI_Worker worker) { - LinkedList_Clear(&worker->tasks, OnDeleteTask); + list_destroy(&worker->tasks, OnDeleteTask); LCUIMutex_Unlock(&worker->mutex); LCUIMutex_Destroy(&worker->mutex); LCUICond_Destroy(&worker->cond); @@ -146,7 +145,7 @@ int LCUIWorker_RunAsync(LCUI_Worker worker) } worker->active = TRUE; LCUIThread_Create(&worker->thread, LCUIWorker_Thread, worker); - Logger_Debug("[worker] worker %u is running\n", worker->thread); + logger_debug("[worker] worker %u is running\n", worker->thread); return 0; } @@ -155,13 +154,13 @@ void LCUIWorker_Destroy(LCUI_Worker worker) LCUI_Thread thread = worker->thread; if (worker->active) { - Logger_Debug("[worker] worker %u is stopping...\n", thread); + logger_debug("[worker] worker %u is stopping...\n", thread); LCUIMutex_Lock(&worker->mutex); worker->active = FALSE; LCUICond_Signal(&worker->cond); LCUIMutex_Unlock(&worker->mutex); LCUIThread_Join(thread, NULL); - Logger_Debug("[worker] worker %u has stopped\n", thread); + logger_debug("[worker] worker %u has stopped\n", thread); return; } LCUIWorker_ExecDestroy(worker); diff --git a/lib/yutil b/lib/yutil new file mode 160000 index 00000000..2f6d14b0 --- /dev/null +++ b/lib/yutil @@ -0,0 +1 @@ +Subproject commit 2f6d14b0bbc784b4247937dc2de2dd0f1f0c6ac7 diff --git a/src/main.c b/src/main.c index 9a42288e..5f124177 100644 --- a/src/main.c +++ b/src/main.c @@ -102,7 +102,7 @@ static struct LCUI_App { LCUI_Mutex loop_mutex; /**< 互斥锁,确保一次只允许一个线程跑主循环 */ LCUI_Cond loop_changed; /**< 条件变量,用于指示当前运行的主循环是否改变 */ LCUI_MainLoop loop; /**< 当前运行的主循环 */ - LinkedList loops; /**< 主循环列表 */ + list_t loops; /**< 主循环列表 */ StepTimer timer; /**< 渲染循环计数器 */ LCUI_AppDriver driver; /**< 程序事件驱动支持 */ LCUI_BOOL driver_ready; /**< 事件驱动支持是否已经准备就绪 */ @@ -127,17 +127,17 @@ static void LCUIProfile_Print(LCUI_Profile profile) unsigned i; LCUI_FrameProfile frame; - Logger_Debug("\nframes_count: %zu, time: %ld\n", profile->frames_count, + logger_debug("\nframes_count: %zu, time: %ld\n", profile->frames_count, profile->end_time - profile->start_time); for (i = 0; i < profile->frames_count; ++i) { frame = &profile->frames[i]; - Logger_Debug("=== frame [%u/%u] ===\n", i + 1, + logger_debug("=== frame [%u/%u] ===\n", i + 1, profile->frames_count); - Logger_Debug("timers.count: %zu\ntimers.time: %ldms\n", + logger_debug("timers.count: %zu\ntimers.time: %ldms\n", frame->timers_count, frame->timers_time); - Logger_Debug("events.count: %zu\nevents.time: %ldms\n", + logger_debug("events.count: %zu\nevents.time: %ldms\n", frame->events_count, frame->events_time); - Logger_Debug("widget_tasks.time: %ldms\n" + logger_debug("widget_tasks.time: %ldms\n" "widget_tasks.update_count: %u\n" "widget_tasks.refresh_count: %u\n" "widget_tasks.layout_count: %u\n" @@ -151,7 +151,7 @@ static void LCUIProfile_Print(LCUI_Profile profile) frame->widget_tasks.user_task_count, frame->widget_tasks.destroy_count, frame->widget_tasks.destroy_time); - Logger_Debug("render: %zu, %ldms, %ldms\n", frame->render_count, + logger_debug("render: %zu, %ldms, %ldms\n", frame->render_count, frame->render_time, frame->present_time); } } @@ -191,7 +191,7 @@ static void OnSettingsChangeEvent(LCUI_SysEvent e, void *arg) void LCUI_RunFrameWithProfile(LCUI_FrameProfile profile) { profile->timers_time = clock(); - profile->timers_count = LCUI_ProcessTimers(); + profile->timers_count = lcui_process_timers(); profile->timers_time = clock() - profile->timers_time; profile->events_time = clock(); @@ -213,7 +213,7 @@ void LCUI_RunFrameWithProfile(LCUI_FrameProfile profile) void LCUI_RunFrame(void) { - LCUI_ProcessTimers(); + lcui_process_timers(); LCUI_ProcessEvents(); LCUICursor_Update(); LCUIWidget_Update(); @@ -409,10 +409,10 @@ int LCUIMainLoop_Run(LCUI_MainLoop loop) DEBUG_MSG("at_same_thread: %d\n", at_same_thread); if (!at_same_thread) { LCUIMutex_Lock(&MainApp.loop_mutex); - LinkedList_Insert(&MainApp.loops, 0, loop); + list_insert(&MainApp.loops, 0, loop); LCUIMutex_Unlock(&MainApp.loop_mutex); } else { - LinkedList_Insert(&MainApp.loops, 0, loop); + list_insert(&MainApp.loops, 0, loop); } DEBUG_MSG("loop: %p, enter\n", loop); MainApp.loop = loop; @@ -438,9 +438,9 @@ int LCUIMainLoop_Run(LCUI_MainLoop loop) loop->state = STATE_EXITED; DEBUG_MSG("loop: %p, exit\n", loop); LCUIMainLoop_Destroy(loop); - LinkedList_Delete(&MainApp.loops, 0); + list_delete(&MainApp.loops, 0); /* 获取处于列表表头的主循环 */ - loop = LinkedList_Get(&MainApp.loops, 0); + loop = list_get(&MainApp.loops, 0); /* 改变当前运行的主循环 */ MainApp.loop = loop; LCUICond_Broadcast(&MainApp.loop_changed); @@ -472,7 +472,7 @@ void LCUI_InitApp(LCUI_AppDriver app) MainApp.timer = StepTimer_Create(); LCUICond_Init(&MainApp.loop_changed); LCUIMutex_Init(&MainApp.loop_mutex); - LinkedList_Init(&MainApp.loops); + list_create(&MainApp.loops); LCUIProfile_Init(&MainApp.profile); LCUI_ResetSettings(); MainApp.settings_change_handler_id = LCUI_BindEvent( @@ -512,11 +512,11 @@ static void LCUI_FreeApp(void) { int i; LCUI_MainLoop loop; - LinkedListNode *node; + list_node_t *node; MainApp.active = FALSE; LCUI_UnbindEvent(MainApp.settings_change_handler_id); MainApp.settings_change_handler_id = -1; - for (LinkedList_Each(node, &MainApp.loops)) { + for (list_each(node, &MainApp.loops)) { loop = node->data; LCUIMainLoop_Quit(loop); LCUIThread_Join(loop->tid, NULL); @@ -524,7 +524,7 @@ static void LCUI_FreeApp(void) StepTimer_Destroy(MainApp.timer); LCUIMutex_Destroy(&MainApp.loop_mutex); LCUICond_Destroy(&MainApp.loop_changed); - LinkedList_Clear(&MainApp.loops, OnDeleteMainLoop); + list_destroy(&MainApp.loops, OnDeleteMainLoop); if (MainApp.driver_ready) { LCUI_DestroyAppDriver(MainApp.driver); } @@ -566,8 +566,8 @@ void *LCUI_GetAppData(void) static void LCUIApp_QuitAllMainLoop(void) { LCUI_MainLoop loop; - LinkedListNode *node; - for (LinkedList_Each(node, &MainApp.loops)) { + list_node_t *node; + for (list_each(node, &MainApp.loops)) { loop = node->data; if (loop) { loop->state = STATE_EXITED; @@ -577,7 +577,7 @@ static void LCUIApp_QuitAllMainLoop(void) static void LCUI_ShowCopyrightText(void) { - Logger_Log(LOGGER_LEVEL_INFO, + logger_log(LOGGER_LEVEL_INFO, "LCUI (LC's UI) version " PACKAGE_VERSION "\n" #ifdef _MSC_VER "Build tool: " @@ -655,8 +655,8 @@ void LCUI_InitBase(void) return; } #ifdef LCUI_BUILD_IN_WIN32 - Logger_SetHandler(Win32Logger_LogA); - Logger_SetHandlerW(Win32Logger_LogW); + logger_set_handler(Win32Logger_LogA); + logger_set_handler_w(Win32Logger_LogW); #endif System.exit_code = 0; System.state = STATE_ACTIVE; @@ -664,7 +664,7 @@ void LCUI_InitBase(void) LCUI_ShowCopyrightText(); LCUI_InitEvent(); LCUI_InitFontLibrary(); - LCUI_InitTimer(); + lcui_init_timers(); LCUI_InitCursor(); LCUI_InitWidget(); LCUI_InitMetrics(); @@ -712,7 +712,7 @@ int LCUI_Destroy(void) LCUI_FreeWidget(); LCUI_FreeCursor(); LCUI_FreeFontLibrary(); - LCUI_FreeTimer(); + lcui_destroy_timers(); LCUI_FreeEvent(); return System.exit_code; } diff --git a/src/settings.c b/src/settings.c index eaac3422..f9572fb7 100644 --- a/src/settings.c +++ b/src/settings.c @@ -51,9 +51,9 @@ void Settings_Init(LCUI_Settings settings) void LCUI_ApplySettings(LCUI_Settings settings) { self = *settings; - self.frame_rate_cap = max(self.frame_rate_cap, 1); + self.frame_rate_cap = y_max(self.frame_rate_cap, 1); self.parallel_rendering_threads = - max(self.parallel_rendering_threads, 1); + y_max(self.parallel_rendering_threads, 1); TriggerSettingsChangedEvent(); } diff --git a/test/cases/test_charset.c b/test/cases/test_charset.c deleted file mode 100644 index 47d13b2d..00000000 --- a/test/cases/test_charset.c +++ /dev/null @@ -1,39 +0,0 @@ -#include -#include -#include -#include -#include -#include "ctest.h" - -void test_charset(void) -{ - size_t len; - char str[64]; - wchar_t wcs[64]; - - len = LCUI_DecodeUTF8String(wcs, "hello", 64); - it_b("test decode ascii string", len == 5 && wcscmp(wcs, L"hello") == 0, - TRUE); -#ifdef _WIN32 - len = LCUI_DecodeString(wcs, "简体中文", 64, ENCODING_ANSI); - test_msg("test decode ansi string ... (%s)\n", - len == 4 && wcscmp(wcs, L"简体中文") == 0 ? "true" : "false"); - - len = LCUI_EncodeString(str, L"简体中文", 64, ENCODING_ANSI); - test_msg("test encode unicode string to ansi ... (%s)\n", - len == strlen("简体中文") && strcmp(str, "简体中文") == 0 - ? "true" - : "false"); -#else - len = LCUI_DecodeUTF8String(wcs, "简体中文", 64); - it_b("test decode utf-8 string", - len == 4 && wcscmp(wcs, L"简体中文") == 0, TRUE); - - len = LCUI_EncodeUTF8String(str, L"简体中文", 64); - it_b("test encode unicode string to utf-8", - len == strlen("简体中文") && strcmp(str, "简体中文") == 0, TRUE); -#endif - len = LCUI_EncodeUTF8String(str, L"hello", 64); - it_b("test encode ascii string to utf-8", - len == 5 && strcmp(str, "hello") == 0, TRUE); -} diff --git a/test/cases/test_image_reader.c b/test/cases/test_image_reader.c index c9f137bc..0ef36568 100644 --- a/test/cases/test_image_reader.c +++ b/test/cases/test_image_reader.c @@ -2,7 +2,7 @@ #include #include #include -#include +#include #include "ctest.h" void test_image_reader(void) @@ -15,14 +15,14 @@ void test_image_reader(void) width = height = 0; Graph_Init(&img); snprintf(file, 255, "test_image_reader.%s", formats[i]); - Logger_Debug("image file: %s\n", file); + logger_debug("image file: %s\n", file); it_i("check LCUI_ReadImageFile", LCUI_ReadImageFile(file, &img), 0); it_i("check image width with ReadImageFile", img.width, 91); it_i("check image height with ReadImageFile", img.height, 69); it_i("check LCUI_GetImageSize", LCUI_GetImageSize(file, &width, &height), 0); - Logger_Debug("image size: (%d, %d)\n", width, height); + logger_debug("image size: (%d, %d)\n", width, height); it_i("check image width with GetImageSize", width, 91); it_i("check image height with GetImageSize", height, 69); Graph_Free(&img); diff --git a/test/cases/test_linkedlist.c b/test/cases/test_linkedlist.c deleted file mode 100644 index 2a37d910..00000000 --- a/test/cases/test_linkedlist.c +++ /dev/null @@ -1,46 +0,0 @@ -#include -#include -#include "ctest.h" - -void test_linkedlist(void) -{ - int arr[] = { 8, 4, 64, 16, 32, 1024 }; - - size_t i; - size_t n = sizeof(arr) / sizeof(int); - - LinkedList list; - LinkedListNode *node; - - LinkedList_Init(&list); - for (i = 0; i < n; ++i) { - LinkedList_Append(&list, arr + i); - } - it_i("LinkedList_Append() should work", (int)list.length, (int)n); - i = 0; - for (LinkedList_Each(node, &list)) { - if (node->data != arr + i) { - break; - } - ++i; - } - it_b("LinkedList_Each() should work", - node == NULL && i == sizeof(arr) / sizeof(int), TRUE); - - i = n - 1; - for (LinkedList_EachReverse(node, &list)) { - if (node->data != arr + i) { - break; - } - if (i == 0) { - i = n; - break; - } - --i; - } - it_i("LinkedList_EachReverse() should work", (int)i, (int)n); - - LinkedList_Clear(&list, NULL); - it_b("LinkedList_ClearData() should work", - list.length == 0 && !list.head.next && !list.tail.prev, TRUE); -} diff --git a/test/cases/test_mainloop.c b/test/cases/test_mainloop.c index 0cf2d0d1..307553a6 100644 --- a/test/cases/test_mainloop.c +++ b/test/cases/test_mainloop.c @@ -22,8 +22,8 @@ static void OnBtnClick(LCUI_Widget w, LCUI_WidgetEvent e, void *arg) LCUI_MainLoop loop; loop = LCUIMainLoop_New(); - LCUI_SetTimeout(10, OnRefreshScreen, NULL); - LCUI_SetTimeout(50, OnQuit, NULL); + lcui_set_timeout(10, OnRefreshScreen, NULL); + lcui_set_timeout(50, OnQuit, NULL); LCUIMainLoop_Run(loop); } @@ -47,7 +47,7 @@ static void ObserverThread(void *arg) LCUI_BOOL *exited = arg; for (i = 0; i < 20 && !*exited; ++i) { - LCUI_MSleep(100); + sleep_ms(100); } it_b("main loop should exit within 2000ms", *exited, TRUE); if (!*exited) { @@ -72,7 +72,7 @@ void test_mainloop(void) /* Observe whether the main loop has exited in a new thread */ LCUIThread_Create(&tid, ObserverThread, &exited); /* Trigger the click event after the first frame is updated */ - LCUI_SetTimeout(50, OnTriggerBtnClick, btn); + lcui_set_timeout(50, OnTriggerBtnClick, btn); LCUI_Main(); exited = TRUE; LCUIThread_Join(tid, NULL); diff --git a/test/cases/test_object.c b/test/cases/test_object.c index 77689cd6..69f97dbd 100644 --- a/test/cases/test_object.c +++ b/test/cases/test_object.c @@ -2,7 +2,7 @@ #include #include #include -#include +#include #include #include "ctest.h" diff --git a/test/cases/test_settings.c b/test/cases/test_settings.c index e4f925d8..3449c5fe 100644 --- a/test/cases/test_settings.c +++ b/test/cases/test_settings.c @@ -89,28 +89,28 @@ void test_settings_frame_rate_cap(void) settings.frame_rate_cap = 30; LCUI_ApplySettings(&settings); - LCUI_SetTimeout(1000, check_settings_frame_rate_cap, + lcui_set_timeout(1000, check_settings_frame_rate_cap, &settings.frame_rate_cap); LCUI_Main(); LCUI_Init(); settings.frame_rate_cap = 5; LCUI_ApplySettings(&settings); - LCUI_SetTimeout(1000, check_settings_frame_rate_cap, + lcui_set_timeout(1000, check_settings_frame_rate_cap, &settings.frame_rate_cap); LCUI_Main(); LCUI_Init(); settings.frame_rate_cap = 90; LCUI_ApplySettings(&settings); - LCUI_SetTimeout(1000, check_settings_frame_rate_cap, + lcui_set_timeout(1000, check_settings_frame_rate_cap, &settings.frame_rate_cap); LCUI_Main(); LCUI_Init(); settings.frame_rate_cap = 25; LCUI_ApplySettings(&settings); - LCUI_SetTimeout(1000, check_settings_frame_rate_cap, + lcui_set_timeout(1000, check_settings_frame_rate_cap, &settings.frame_rate_cap); LCUI_Main(); } diff --git a/test/cases/test_string.c b/test/cases/test_string.c deleted file mode 100644 index dffe4b4f..00000000 --- a/test/cases/test_string.c +++ /dev/null @@ -1,67 +0,0 @@ -#include -#include -#include -#include -#include "ctest.h" - -static void test_cmdsplit(void) -{ - char **argv; - int argc = 0; - const char *cmd = "\"C:\\Program Files\\WindowsApps\\Test\\app.exe\" " - "--print \"Hello, Wolrd !\""; - const char *results[3] = { - "\"C:\\Program Files\\WindowsApps\\Test\\app.exe\"", "--print", - "\"Hello, Wolrd !\"" - }; - it_i("executable in command only", cmdsplit(" test.exe ", NULL), 1); - it_i("command with two parameters", cmdsplit(cmd, NULL), 3); - argc = cmdsplit(cmd, &argv); - char messageBuffer[1024]; - while (argc-- > 0) { - snprintf(messageBuffer, sizeof(messageBuffer), - "check argv[%d]: check [%s] == [%s]", argc, argv[argc], - results[argc]); - it_s(messageBuffer, argv[argc], results[argc]); - free(argv[argc]); - } - free(argv); -} - -void test_strs(void) -{ - char **strs = NULL; - strlist_add(&strs, "first-child"); - strlist_add(&strs, "last-child"); - strlist_add(&strs, "one two"); - it_b("check first-child is in the list", - strlist_has(strs, "first-child"), TRUE); - it_b("check last-child is in the list", strlist_has(strs, "last-child"), - TRUE); - it_b("check one is in the list", strlist_has(strs, "one"), TRUE); - it_b("check two is in the list", strlist_has(strs, "two"), TRUE); - it_b("check remove(last_child)", strlist_remove(&strs, "last-child"), - TRUE); - it_b("check remove(first-child", strlist_remove(&strs, "first-child"), - TRUE); - it_b("check remove(one)", strlist_remove(&strs, "one"), TRUE); - it_b("check first-child is removed", strlist_has(strs, "first-child"), - FALSE); - it_b("check one is removed", strlist_has(strs, "one"), FALSE); - it_b("check two is still in the list", strlist_has(strs, "two"), TRUE); - it_i("check strhash(123, \"123\") is consistent", strhash(123, "123"), - strhash(123, "123")); - it_b("check strhash(123, \"123\") != strhash(123, \"312\")", - strhash(123, "123") == strhash(123, "312"), FALSE); - it_b("check strhash(100, \"123\") != strhash(123, \"123\")", - strhash(100, "123") == strhash(123, "123"), FALSE); - it_b("check adding first-child", strlist_add(&strs, "first-child"), - TRUE); - strlist_free(strs); -} - -void test_string(void) -{ - describe("test cmdsplit", test_cmdsplit); - describe("test strs", test_strs); -} diff --git a/test/cases/test_strpool.c b/test/cases/test_strpool.c deleted file mode 100644 index 9139ccfe..00000000 --- a/test/cases/test_strpool.c +++ /dev/null @@ -1,26 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include "ctest.h" - -void test_strpool(void) -{ - char *str1, *str2; - strpool_t *pool; - - it_b("check strpool_create()", (pool = strpool_create()) != NULL, TRUE); - it_b("check strpool_alloc", - (str1 = strpool_alloc_str(pool, "hello")) != NULL, TRUE); - it_b("check strpool_alloc of already pooled string", - (str2 = strpool_alloc_str(pool, "hello")) != NULL, TRUE); - it_b("check string reused", str1 == str2, TRUE); - it_b("check strpool_size", strpool_size(pool) > 0, TRUE); - it_i("check release str1", strpool_free_str(str1), 0); - it_s("check str1 is still valid", str1, "hello"); - it_i("check release str2", strpool_free_str(str2), 0); - it_i("check strpool is empty", (int)strpool_size(pool), 0); - strpool_destroy(pool); -} diff --git a/test/cases/test_thread.c b/test/cases/test_thread.c index 8020c66d..e101627e 100644 --- a/test/cases/test_thread.c +++ b/test/cases/test_thread.c @@ -2,7 +2,7 @@ #include #include #include -#include +#include #include "ctest.h" typedef struct TestWorkerRec_ { @@ -24,13 +24,13 @@ static void TestWorker_Thread(void *arg) worker->data_count = 0; LCUIMutex_Lock(&worker->mutex); while (!worker->cancel && worker->data_count < 20) { - Logger_Debug("waiting...\n"); + logger_debug("waiting...\n"); LCUICond_Wait(&worker->cond, &worker->mutex); - Logger_Debug("get data: %s\n", worker->data); + logger_debug("get data: %s\n", worker->data); worker->data_count += 1; } LCUIMutex_Unlock(&worker->mutex); - Logger_Debug("count: %d\n", worker->data_count); + logger_debug("count: %d\n", worker->data_count); worker->active = FALSE; LCUIThread_Exit(NULL); } @@ -66,19 +66,19 @@ void test_thread(void) TestWorker_Init(&worker); LCUIThread_Create(&worker.thread, TestWorker_Thread, &worker); - LCUI_MSleep(100); + sleep_ms(100); TestWorker_Send(&worker, "hello"); - LCUI_MSleep(20); + sleep_ms(20); TestWorker_Send(&worker, "world"); - LCUI_MSleep(100); + sleep_ms(100); TestWorker_Send(&worker, "this"); - LCUI_MSleep(50); + sleep_ms(50); TestWorker_Send(&worker, "is"); - LCUI_MSleep(100); + sleep_ms(100); TestWorker_Send(&worker, "test"); - LCUI_MSleep(50); + sleep_ms(50); TestWorker_Send(&worker, "bye!"); - LCUI_MSleep(100); + sleep_ms(100); TestWorker_Destroy(&worker); it_i("check worker data count", worker.data_count, 7); it_b("check worker is no longer active", worker.active, FALSE); diff --git a/test/cases/test_widget_opacity.c b/test/cases/test_widget_opacity.c index 80fe0ad0..1733c281 100644 --- a/test/cases/test_widget_opacity.c +++ b/test/cases/test_widget_opacity.c @@ -5,6 +5,7 @@ #include #include #include +#include #include "ctest.h" #define PARENT_OPACITY 0.8f diff --git a/test/cases/test_widget_rect.c b/test/cases/test_widget_rect.c index e70f77f8..123542c8 100644 --- a/test/cases/test_widget_rect.c +++ b/test/cases/test_widget_rect.c @@ -13,7 +13,7 @@ void test_widget_rect(void) LCUI_SysEventRec ev; LCUI_Rect *rect; LCUI_Rect expected_rect; - LinkedList rects; + list_t rects; LCUI_Init(); root = LCUIWidget_GetRoot(); @@ -28,9 +28,9 @@ void test_widget_rect(void) Widget_Append(root, parent); LCUIWidget_Update(); - LinkedList_Init(&rects); + list_create(&rects); Widget_GetInvalidArea(root, &rects); - LinkedList_Clear(&rects, free); + list_destroy(&rects, free); ev.type = LCUI_MOUSEMOVE; ev.motion.x = 150; @@ -59,7 +59,7 @@ void test_widget_rect(void) expected_rect.width = 100; expected_rect.height = 100; it_rect("root.getInvalidArea()[0]", rect, &expected_rect); - LinkedList_Clear(&rects, free); + list_destroy(&rects, free); ev.motion.x = 40; ev.motion.y = 40; @@ -84,7 +84,7 @@ void test_widget_rect(void) rect = rects.head.next->data; it_rect("root.getInvalidArea()[0]", rect, &expected_rect); } - LinkedList_Clear(&rects, free); + list_destroy(&rects, free); ev.type = LCUI_MOUSEUP; LCUI_TriggerEvent(&ev, NULL); @@ -97,7 +97,7 @@ void test_widget_rect(void) rect = rects.head.next->data; it_rect("root.getInvalidArea()[0]", rect, &expected_rect); } - LinkedList_Clear(&rects, free); + list_destroy(&rects, free); ev.type = LCUI_MOUSEMOVE; ev.motion.x = 80; @@ -124,7 +124,7 @@ void test_widget_rect(void) rect = rects.head.next->data; it_rect("root.getInvalidArea()[0]", rect, &expected_rect); } - LinkedList_Clear(&rects, free); + list_destroy(&rects, free); expected_rect.x = 21; expected_rect.y = 11; @@ -139,7 +139,7 @@ void test_widget_rect(void) rect = rects.head.next->data; it_rect("root.getInvalidArea()[0]", rect, &expected_rect); } - LinkedList_Clear(&rects, free); + list_destroy(&rects, free); expected_rect.x = 0; expected_rect.y = 0; @@ -154,7 +154,7 @@ void test_widget_rect(void) rect = rects.head.next->data; it_rect("root.getInvalidArea()[0]", rect, &expected_rect); } - LinkedList_Clear(&rects, free); + list_destroy(&rects, free); LCUI_Destroy(); } diff --git a/test/lib/ctest/src/ctest.c b/test/lib/ctest/src/ctest.c index ed992154..9ba6f18f 100644 --- a/test/lib/ctest/src/ctest.c +++ b/test/lib/ctest/src/ctest.c @@ -37,8 +37,7 @@ int test_msg(const char *fmt, ...) void test_begin(void) { if (test_start_time == 0) { - LCUITime_Init(); - test_start_time = LCUI_GetTime(); + test_start_time = get_time_ms(); } test_msg_indent++; } @@ -59,7 +58,7 @@ int test_result(void) int print_test_result(void) { printf(GREEN(" %zu passing") " (%ums)\n", tests_passed, - (unsigned)LCUI_GetTimeDelta(test_start_time)); + (unsigned)get_time_delta(test_start_time)); if (tests_total > tests_passed) { printf(RED(" %zu faling\n\n"), tests_total - tests_passed); return (int)(tests_total - tests_passed); diff --git a/test/run_tests.c b/test/run_tests.c index 6bccfc19..f8f30b59 100644 --- a/test/run_tests.c +++ b/test/run_tests.c @@ -9,11 +9,7 @@ int tests_count = 0; int main(void) { int ret = 0; - Logger_SetLevel(LOGGER_LEVEL_OFF); - describe("test charset", test_charset); - describe("test linkedlist", test_linkedlist); - describe("test string", test_string); - describe("test strpool", test_strpool); + logger_set_level(LOGGER_LEVEL_OFF); describe("test settings", test_settings); describe("test object", test_object); describe("test thread", test_thread); diff --git a/test/run_tests.h b/test/run_tests.h index c77db109..9d110070 100644 --- a/test/run_tests.h +++ b/test/run_tests.h @@ -2,15 +2,11 @@ extern int tests_count; -void test_charset(void); -void test_string(void); void test_object(void); void test_settings(void); void test_thread(void); void test_font_load(void); void test_xml_parser(void); -void test_strpool(void); -void test_linkedlist(void); void test_widget_opacity(void); void test_widget_event(void); void test_textview_resize(void); diff --git a/test/test_block_layout.c b/test/test_block_layout.c index 7605cee6..ccef2eeb 100644 --- a/test/test_block_layout.c +++ b/test/test_block_layout.c @@ -3,7 +3,7 @@ int main(int argc, char **argv) { - Logger_SetLevel(LOGGER_LEVEL_INFO); + logger_set_level(LOGGER_LEVEL_INFO); LCUI_Init(); test_block_layout(); return LCUI_Main(); diff --git a/test/test_border.c b/test/test_border.c index b69bed47..96208058 100644 --- a/test/test_border.c +++ b/test/test_border.c @@ -1,10 +1,10 @@ #include #include -#include -#include #include #include #include +#include +#include int main(void) { diff --git a/test/test_char_render.c b/test/test_char_render.c index 827e7213..e9df2d21 100644 --- a/test/test_char_render.c +++ b/test/test_char_render.c @@ -1,6 +1,7 @@ #include #include #include +#include int main(void) { diff --git a/test/test_flex_layout.c b/test/test_flex_layout.c index bf66a4ff..90bbbafd 100644 --- a/test/test_flex_layout.c +++ b/test/test_flex_layout.c @@ -3,7 +3,7 @@ int main(int argc, char **argv) { - Logger_SetLevel(LOGGER_LEVEL_INFO); + logger_set_level(LOGGER_LEVEL_INFO); test_flex_layout(); return LCUI_Main(); } diff --git a/test/test_image_scaling_bench.c b/test/test_image_scaling_bench.c index 2d9c4662..30b2590a 100644 --- a/test/test_image_scaling_bench.c +++ b/test/test_image_scaling_bench.c @@ -27,23 +27,23 @@ int main(int argc, char **argv) } t_color.value = 0xffaa5500; Graph_FillRect(&g_src, t_color, NULL, false); - Logger_Info("%-20s%-20s%s\n", "image size\\method", "Graph_Zoom()", + logger_info("%-20s%-20s%s\n", "image size\\method", "Graph_Zoom()", "Graph_ZoomBilinear()"); for (i = 0; i < sizeof(resx) / sizeof(int); i++) { resy = resx[i] * 9 / 16; - t0 = LCUI_GetTime(); + t0 = get_time_ms(); Graph_Init(&g_dst); Graph_Zoom(&g_src, &g_dst, false, resx[i], resy); Graph_Free(&g_dst); - t1 = LCUI_GetTime(); + t1 = get_time_ms(); Graph_Init(&g_dst); Graph_ZoomBilinear(&g_src, &g_dst, false, resx[i], resy); Graph_Free(&g_dst); - t2 = LCUI_GetTime(); + t2 = get_time_ms(); sprintf(s_res, "%dx%d", resx[i], resy); sprintf(s_t0, "%ldms", t1 - t0); sprintf(s_t1, "%ldms", t2 - t1); - Logger_Info("%-20s%-20s%-20s\n", s_res, s_t0, s_t1); + logger_info("%-20s%-20s%-20s\n", s_res, s_t0, s_t1); } Graph_Free(&g_src); return 0; diff --git a/test/test_pixel_manipulation.c b/test/test_pixel_manipulation.c index 2e3eb0f6..66cb443a 100644 --- a/test/test_pixel_manipulation.c +++ b/test/test_pixel_manipulation.c @@ -39,13 +39,13 @@ void grayscale(LCUI_Graph *graph, LCUI_Rect rect) void sepia(LCUI_Graph *graph, LCUI_Rect rect) { PixelManipulationBegin; - pixel.red = (unsigned char)min( + pixel.red = (unsigned char)y_min( round(0.393 * pixel.red + 0.769 * pixel.green + 0.189 * pixel.blue), 255); - pixel.green = (unsigned char)min( + pixel.green = (unsigned char)y_min( round(0.349 * pixel.red + 0.686 * pixel.green + 0.168 * pixel.blue), 255); - pixel.blue = (unsigned char)min( + pixel.blue = (unsigned char)y_min( round(0.272 * pixel.red + 0.534 * pixel.green + 0.131 * pixel.blue), 255); PixelManipulationEnd; diff --git a/test/test_render.c b/test/test_render.c index 78a4201b..e73dda6e 100644 --- a/test/test_render.c +++ b/test/test_render.c @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -128,7 +129,7 @@ void InitRenderStatus(void) TextView_SetColor(status, white); Widget_Append(root, status); UpdateRenderStatus(status); - LCUI_SetInterval(1000, UpdateRenderStatus, status); + lcui_set_interval(1000, UpdateRenderStatus, status); } int main(void) @@ -136,7 +137,7 @@ int main(void) size_t i; int64_t t; - Logger_SetLevel(LOGGER_LEVEL_WARNING); + logger_set_level(LOGGER_LEVEL_WARNING); LCUI_Init(); LCUIDisplay_SetSize(SCREEN_WIDTH, SCREEN_HEIGHT); InitBackground(); @@ -144,11 +145,11 @@ int main(void) InitRenderStatus(); printf("running rendering performance test\n"); LCUI_RunFrame(); - t = LCUI_GetTime(); + t = get_time_ms(); self.color_index = 0; for (i = 0; i < 600; ++i) { UpdateFrame(self.box); - LCUI_ProcessTimers(); + lcui_process_timers(); LCUI_ProcessEvents(); LCUIWidget_Update(); LCUIDisplay_Update(); @@ -157,8 +158,8 @@ int main(void) ++self.fps; ++self.color_index; } - t = LCUI_GetTimeDelta(t); - Logger_Warning( + t = get_time_delta(t); + logger_warning( "rendered %zu frames in %.2lfs, rendering speed is %.2lf fps\n", i, t / 1000.f, i * 1000.f / t); return 0; diff --git a/test/test_string_render.c b/test/test_string_render.c index fd835d27..81f10511 100644 --- a/test/test_string_render.c +++ b/test/test_string_render.c @@ -1,6 +1,7 @@ #include #include #include +#include int main(void) { diff --git a/test/test_textview_resize.c b/test/test_textview_resize.c index d47ea47a..86328ccb 100644 --- a/test/test_textview_resize.c +++ b/test/test_textview_resize.c @@ -6,9 +6,9 @@ int main(void) LCUI_Init(); build(); - LCUI_SetTimeout(2000, test_textview_set_text, NULL); - LCUI_SetTimeout(4000, test_textview_set_short_content_css, NULL); - LCUI_SetTimeout(6000, test_textview_set_long_content_css, NULL); + lcui_set_timeout(2000, test_textview_set_text, NULL); + lcui_set_timeout(4000, test_textview_set_short_content_css, NULL); + lcui_set_timeout(6000, test_textview_set_long_content_css, NULL); return LCUI_Main(); } diff --git a/test/test_touch.c b/test/test_touch.c index 66982031..dc891e56 100644 --- a/test/test_touch.c +++ b/test/test_touch.c @@ -3,20 +3,20 @@ #include #include #include -#include #include #include +#include /** 触点绑定记录 */ typedef struct TouchPointBindingRec_ { int point_id; /**< 触点 ID */ LCUI_Widget widget; /**< 部件 */ - LinkedListNode node; /**< 在链表中的结点 */ + list_node_t node; /**< 在链表中的结点 */ LCUI_BOOL is_valid; /**< 是否有效 */ } TouchPointBindingRec, *TouchPointBinding; /** 触点绑定记录列表 */ -static LinkedList touch_bindings; +static list_t touch_bindings; static void OnTouchWidget(LCUI_Widget w, LCUI_WidgetEvent e, void *arg) { @@ -38,7 +38,7 @@ static void OnTouchWidget(LCUI_Widget w, LCUI_WidgetEvent e, void *arg) } /* 当触点释放后销毁部件及绑定记录 */ Widget_ReleaseTouchCapture(w, -1); - LinkedList_Unlink(&touch_bindings, &binding->node); + list_unlink(&touch_bindings, &binding->node); binding->is_valid = FALSE; Widget_Destroy(w); free(binding); @@ -53,7 +53,7 @@ static void OnTouch(LCUI_SysEvent e, void *arg) { int i; LCUI_Widget w; - LinkedListNode *node; + list_node_t *node; LCUI_TouchPoint point; LCUI_Color bgcolor = RGB(255, 0, 0); @@ -63,7 +63,7 @@ static void OnTouch(LCUI_SysEvent e, void *arg) point = &e->touch.points[i]; _DEBUG_MSG("point: %d\n", point->id); /* 检查该触点是否已经被绑定 */ - for (LinkedList_Each(node, &touch_bindings)) { + for (list_each(node, &touch_bindings)) { binding = node->data; if (binding->point_id == point->id) { is_existed = TRUE; @@ -86,7 +86,7 @@ static void OnTouch(LCUI_SysEvent e, void *arg) Widget_BindEvent(w, "touch", OnTouchWidget, binding, NULL); Widget_SetStyle(w, key_position, SV_ABSOLUTE, style); Widget_SetStyle(w, key_background_color, bgcolor, color); - LinkedList_AppendNode(&touch_bindings, &binding->node); + list_append_node(&touch_bindings, &binding->node); Widget_Top(w); } } @@ -94,7 +94,7 @@ static void OnTouch(LCUI_SysEvent e, void *arg) int main(int argc, char **argv) { LCUI_Init(); - LinkedList_Init(&touch_bindings); + list_create(&touch_bindings); LCUI_BindEvent(LCUI_TOUCH, OnTouch, NULL, NULL); return LCUI_Main(); } diff --git a/test/test_widget.c b/test/test_widget.c index 571dcb8c..9a880faf 100644 --- a/test/test_widget.c +++ b/test/test_widget.c @@ -4,7 +4,7 @@ #include #include #include -#include +#include int main(void) { @@ -19,7 +19,7 @@ int main(void) box = LCUIWidget_New(NULL); c = clock(); - Logger_Debug("start create %zu widgets...\n", n); + logger_debug("start create %zu widgets...\n", n); Widget_Append(LCUIWidget_GetRoot(), box); for (i = 0; i < n; ++i) { w = LCUIWidget_New("textview"); @@ -27,30 +27,31 @@ int main(void) Widget_Append(box, w); } sec = (clock() - c) * 1.0 / CLOCKS_PER_SEC; - Logger_Debug("%zu widgets have been created, which took %gs\n", n, sec); - Logger_Debug("it should take less than 1s\n"); + logger_debug("%zu widgets have been created, which took %gs\n", n, sec); + logger_debug("it should take less than 1s\n"); - Logger_Debug("start update %zu widgets...\n", n); + logger_debug("start update %zu widgets...\n", n); c = clock(); LCUIWidget_Update(); LCUIWidget_Update(); sec = (clock() - c) * 1.0 / CLOCKS_PER_SEC; - Logger_Debug("%zu widgets have been updated, which took %gs\n", n, sec); - Logger_Debug("it should take less than 6s\n"); + logger_debug("%zu widgets have been updated, which took %gs\n", n, sec); + logger_debug("it should take less than 6s\n"); - Logger_Debug("start remove %zu widgets...\n", n); + logger_debug("start remove %zu widgets...\n", n); c = clock(); Widget_Empty(box); sec = (clock() - c) * 1.0 / CLOCKS_PER_SEC; - Logger_Debug("%zu widgets have been removed, which took %gs\n", n, sec); - Logger_Debug("it should take less than 0.5s\n"); + logger_debug("%zu widgets have been removed, which took %gs\n", n, sec); + logger_debug("it should take less than 0.5s\n"); - Logger_Debug("start destroy %zu widgets...\n", n); + logger_debug("start destroy %zu widgets...\n", n); c = clock(); LCUIWidget_Update(); sec = (clock() - c) * 1.0 / CLOCKS_PER_SEC; - Logger_Debug("%zu widgets have been destroyed, which took %gs\n", n, sec); - Logger_Debug("it should take less than 1s\n"); + logger_debug("%zu widgets have been destroyed, which took %gs\n", n, + sec); + logger_debug("it should take less than 1s\n"); LCUI_FreeWidget(); LCUI_FreeFontLibrary(); diff --git a/test/test_widget_render.c b/test/test_widget_render.c index 2662765c..f25b8c15 100644 --- a/test/test_widget_render.c +++ b/test/test_widget_render.c @@ -1,8 +1,8 @@ #include -#include -#include #include #include +#include +#include int main(void) { diff --git a/xmake.lua b/xmake.lua index 2b2b2fc0..8cf6ee02 100644 --- a/xmake.lua +++ b/xmake.lua @@ -1,7 +1,7 @@ set_project("lcui") set_version("2.2.1") add_rules("mode.debug", "mode.release", "c++.openmp", "mode.coverage") -add_includedirs("include", "include/LCUI") +add_includedirs("include", "include/LCUI", "lib/yutil/include") add_rpathdirs("@loader_path/lib", "@loader_path") add_defines("LCUI_EXPORTS", "UNICODE") includes("lib/**/xmake.lua")