code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222 values | license stringclasses 20 values | size int64 1 1.05M |
|---|---|---|---|---|---|
#include "../lv_conf_internal.h"
#if LV_MEM_CUSTOM == 0
#ifndef LV_TLSF_H
#define LV_TLSF_H
/*
** Two Level Segregated Fit memory allocator, version 3.1.
** Written by Matthew Conte
** http://tlsf.baisoku.org
**
** Based on the original documentation by Miguel Masmano:
** http://www.gii.upv.es/tlsf/main/docs
**
** This implementation was written to the specification
** of the document, therefore no GPL restrictions apply.
**
** Copyright (c) 2006-2016, Matthew Conte
** 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 the copyright holder 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 MATTHEW CONTE 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 <stddef.h>
#if defined(__cplusplus)
extern "C" {
#endif
/* lv_tlsf_t: a TLSF structure. Can contain 1 to N pools. */
/* lv_pool_t: a block of memory that TLSF can manage. */
typedef void * lv_tlsf_t;
typedef void * lv_pool_t;
/* Create/destroy a memory pool. */
lv_tlsf_t lv_tlsf_create(void * mem);
lv_tlsf_t lv_tlsf_create_with_pool(void * mem, size_t bytes);
void lv_tlsf_destroy(lv_tlsf_t tlsf);
lv_pool_t lv_tlsf_get_pool(lv_tlsf_t tlsf);
/* Add/remove memory pools. */
lv_pool_t lv_tlsf_add_pool(lv_tlsf_t tlsf, void * mem, size_t bytes);
void lv_tlsf_remove_pool(lv_tlsf_t tlsf, lv_pool_t pool);
/* malloc/memalign/realloc/free replacements. */
void * lv_tlsf_malloc(lv_tlsf_t tlsf, size_t bytes);
void * lv_tlsf_memalign(lv_tlsf_t tlsf, size_t align, size_t bytes);
void * lv_tlsf_realloc(lv_tlsf_t tlsf, void * ptr, size_t size);
void lv_tlsf_free(lv_tlsf_t tlsf, void * ptr);
/* Returns internal block size, not original request size */
size_t lv_tlsf_block_size(void * ptr);
/* Overheads/limits of internal structures. */
size_t lv_tlsf_size(void);
size_t lv_tlsf_align_size(void);
size_t lv_tlsf_block_size_min(void);
size_t lv_tlsf_block_size_max(void);
size_t lv_tlsf_pool_overhead(void);
size_t lv_tlsf_alloc_overhead(void);
/* Debugging. */
typedef void (*lv_tlsf_walker)(void * ptr, size_t size, int used, void * user);
void lv_tlsf_walk_pool(lv_pool_t pool, lv_tlsf_walker walker, void * user);
/* Returns nonzero if any internal consistency check fails. */
int lv_tlsf_check(lv_tlsf_t tlsf);
int lv_tlsf_check_pool(lv_pool_t pool);
#if defined(__cplusplus)
};
#endif
#endif /*LV_TLSF_H*/
#endif /* LV_MEM_CUSTOM == 0 */
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/misc/lv_tlsf.h | C | apache-2.0 | 3,668 |
/**
* @file lv_text.c
*
*/
/*********************
* INCLUDES
*********************/
#include <stdarg.h>
#include "lv_txt.h"
#include "lv_txt_ap.h"
#include "lv_math.h"
#include "lv_log.h"
#include "lv_mem.h"
#include "lv_assert.h"
/*********************
* DEFINES
*********************/
#define NO_BREAK_FOUND UINT32_MAX
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
#if LV_TXT_ENC == LV_TXT_ENC_UTF8
static uint8_t lv_txt_utf8_size(const char * str);
static uint32_t lv_txt_unicode_to_utf8(uint32_t letter_uni);
static uint32_t lv_txt_utf8_conv_wc(uint32_t c);
static uint32_t lv_txt_utf8_next(const char * txt, uint32_t * i);
static uint32_t lv_txt_utf8_prev(const char * txt, uint32_t * i_start);
static uint32_t lv_txt_utf8_get_byte_id(const char * txt, uint32_t utf8_id);
static uint32_t lv_txt_utf8_get_char_id(const char * txt, uint32_t byte_id);
static uint32_t lv_txt_utf8_get_length(const char * txt);
#elif LV_TXT_ENC == LV_TXT_ENC_ASCII
static uint8_t lv_txt_iso8859_1_size(const char * str);
static uint32_t lv_txt_unicode_to_iso8859_1(uint32_t letter_uni);
static uint32_t lv_txt_iso8859_1_conv_wc(uint32_t c);
static uint32_t lv_txt_iso8859_1_next(const char * txt, uint32_t * i);
static uint32_t lv_txt_iso8859_1_prev(const char * txt, uint32_t * i_start);
static uint32_t lv_txt_iso8859_1_get_byte_id(const char * txt, uint32_t utf8_id);
static uint32_t lv_txt_iso8859_1_get_char_id(const char * txt, uint32_t byte_id);
static uint32_t lv_txt_iso8859_1_get_length(const char * txt);
#endif
/**********************
* STATIC VARIABLES
**********************/
/**********************
* GLOBAL VARIABLES
**********************/
#if LV_TXT_ENC == LV_TXT_ENC_UTF8
uint8_t (*_lv_txt_encoded_size)(const char *) = lv_txt_utf8_size;
uint32_t (*_lv_txt_unicode_to_encoded)(uint32_t) = lv_txt_unicode_to_utf8;
uint32_t (*_lv_txt_encoded_conv_wc)(uint32_t) = lv_txt_utf8_conv_wc;
uint32_t (*_lv_txt_encoded_next)(const char *, uint32_t *) = lv_txt_utf8_next;
uint32_t (*_lv_txt_encoded_prev)(const char *, uint32_t *) = lv_txt_utf8_prev;
uint32_t (*_lv_txt_encoded_get_byte_id)(const char *, uint32_t) = lv_txt_utf8_get_byte_id;
uint32_t (*_lv_txt_encoded_get_char_id)(const char *, uint32_t) = lv_txt_utf8_get_char_id;
uint32_t (*_lv_txt_get_encoded_length)(const char *) = lv_txt_utf8_get_length;
#elif LV_TXT_ENC == LV_TXT_ENC_ASCII
uint8_t (*_lv_txt_encoded_size)(const char *) = lv_txt_iso8859_1_size;
uint32_t (*_lv_txt_unicode_to_encoded)(uint32_t) = lv_txt_unicode_to_iso8859_1;
uint32_t (*_lv_txt_encoded_conv_wc)(uint32_t) = lv_txt_iso8859_1_conv_wc;
uint32_t (*_lv_txt_encoded_next)(const char *, uint32_t *) = lv_txt_iso8859_1_next;
uint32_t (*_lv_txt_encoded_prev)(const char *, uint32_t *) = lv_txt_iso8859_1_prev;
uint32_t (*_lv_txt_encoded_get_byte_id)(const char *, uint32_t) = lv_txt_iso8859_1_get_byte_id;
uint32_t (*_lv_txt_encoded_get_char_id)(const char *, uint32_t) = lv_txt_iso8859_1_get_char_id;
uint32_t (*_lv_txt_get_encoded_length)(const char *) = lv_txt_iso8859_1_get_length;
#endif
/**********************
* MACROS
**********************/
#define LV_IS_ASCII(value) ((value & 0x80U) == 0x00U)
#define LV_IS_2BYTES_UTF8_CODE(value) ((value & 0xE0U) == 0xC0U)
#define LV_IS_3BYTES_UTF8_CODE(value) ((value & 0xF0U) == 0xE0U)
#define LV_IS_4BYTES_UTF8_CODE(value) ((value & 0xF8U) == 0xF0U)
#define LV_IS_INVALID_UTF8_CODE(value) ((value & 0xC0U) != 0x80U)
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_txt_get_size(lv_point_t * size_res, const char * text, const lv_font_t * font, lv_coord_t letter_space,
lv_coord_t line_space, lv_coord_t max_width, lv_text_flag_t flag)
{
size_res->x = 0;
size_res->y = 0;
if(text == NULL) return;
if(font == NULL) return;
if(flag & LV_TEXT_FLAG_EXPAND) max_width = LV_COORD_MAX;
uint32_t line_start = 0;
uint32_t new_line_start = 0;
uint16_t letter_height = lv_font_get_line_height(font);
/*Calc. the height and longest line*/
while(text[line_start] != '\0') {
new_line_start += _lv_txt_get_next_line(&text[line_start], font, letter_space, max_width, flag);
if((unsigned long)size_res->y + (unsigned long)letter_height + (unsigned long)line_space > LV_MAX_OF(lv_coord_t)) {
LV_LOG_WARN("lv_txt_get_size: integer overflow while calculating text height");
return;
}
else {
size_res->y += letter_height;
size_res->y += line_space;
}
/*Calculate the longest line*/
lv_coord_t act_line_length = lv_txt_get_width(&text[line_start], new_line_start - line_start, font, letter_space,
flag);
size_res->x = LV_MAX(act_line_length, size_res->x);
line_start = new_line_start;
}
/*Make the text one line taller if the last character is '\n' or '\r'*/
if((line_start != 0) && (text[line_start - 1] == '\n' || text[line_start - 1] == '\r')) {
size_res->y += letter_height + line_space;
}
/*Correction with the last line space or set the height manually if the text is empty*/
if(size_res->y == 0)
size_res->y = letter_height;
else
size_res->y -= line_space;
}
/**
* Get the next word of text. A word is delimited by break characters.
*
* If the word cannot fit in the max_width space, obey LV_TXT_LINE_BREAK_LONG_* rules.
*
* If the next word cannot fit anything, return 0.
*
* If the first character is a break character, returns the next index.
*
* Example calls from lv_txt_get_next_line() assuming sufficient max_width and
* txt = "Test text\n"
* 0123456789
*
* Calls would be as follows:
* 1. Return i=4, pointing at breakchar ' ', for the string "Test"
* 2. Return i=5, since i=4 was a breakchar.
* 3. Return i=9, pointing at breakchar '\n'
* 4. Parenting lv_txt_get_next_line() would detect subsequent '\0'
*
* TODO: Returned word_w_ptr may overestimate the returned word's width when
* max_width is reached. In current usage, this has no impact.
*
* @param txt a '\0' terminated string
* @param font pointer to a font
* @param letter_space letter space
* @param max_width max with of the text (break the lines to fit this size) Set CORD_MAX to avoid line breaks
* @param flags settings for the text from 'txt_flag_type' enum
* @param[out] word_w_ptr width (in pixels) of the parsed word. May be NULL.
* @param force Force return the fraction of the word that can fit in the provided space.
* @return the index of the first char of the next word (in byte index not letter index. With UTF-8 they are different)
*/
static uint32_t lv_txt_get_next_word(const char * txt, const lv_font_t * font,
lv_coord_t letter_space, lv_coord_t max_width,
lv_text_flag_t flag, uint32_t * word_w_ptr, lv_text_cmd_state_t * cmd_state, bool force)
{
if(txt == NULL || txt[0] == '\0') return 0;
if(font == NULL) return 0;
if(flag & LV_TEXT_FLAG_EXPAND) max_width = LV_COORD_MAX;
uint32_t i = 0, i_next = 0, i_next_next = 0; /*Iterating index into txt*/
uint32_t letter = 0; /*Letter at i*/
uint32_t letter_next = 0; /*Letter at i_next*/
lv_coord_t letter_w;
lv_coord_t cur_w = 0; /*Pixel Width of transversed string*/
uint32_t word_len = 0; /*Number of characters in the transversed word*/
uint32_t break_index = NO_BREAK_FOUND; /*only used for "long" words*/
uint32_t break_letter_count = 0; /*Number of characters up to the long word break point*/
letter = _lv_txt_encoded_next(txt, &i_next);
i_next_next = i_next;
/*Obtain the full word, regardless if it fits or not in max_width*/
while(txt[i] != '\0') {
letter_next = _lv_txt_encoded_next(txt, &i_next_next);
word_len++;
/*Handle the recolor command*/
if((flag & LV_TEXT_FLAG_RECOLOR) != 0) {
if(_lv_txt_is_cmd(cmd_state, letter) != false) {
i = i_next;
i_next = i_next_next;
letter = letter_next;
continue; /*Skip the letter if it is part of a command*/
}
}
letter_w = lv_font_get_glyph_width(font, letter, letter_next);
cur_w += letter_w;
if(letter_w > 0) {
cur_w += letter_space;
}
/*Test if this character fits within max_width*/
if(break_index == NO_BREAK_FOUND && (cur_w - letter_space) > max_width) {
break_index = i;
break_letter_count = word_len - 1;
/*break_index is now pointing at the character that doesn't fit*/
}
/*Check for new line chars and breakchars*/
if(letter == '\n' || letter == '\r' || _lv_txt_is_break_char(letter)) {
/*Update the output width on the first character if it fits.
*Must do this here in case first letter is a break character.*/
if(i == 0 && break_index == NO_BREAK_FOUND && word_w_ptr != NULL) *word_w_ptr = cur_w;
word_len--;
break;
}
/*Update the output width*/
if(word_w_ptr != NULL && break_index == NO_BREAK_FOUND) *word_w_ptr = cur_w;
i = i_next;
i_next = i_next_next;
letter = letter_next;
}
/*Entire Word fits in the provided space*/
if(break_index == NO_BREAK_FOUND) {
if(word_len == 0 || (letter == '\r' && letter_next == '\n')) i = i_next;
return i;
}
#if LV_TXT_LINE_BREAK_LONG_LEN > 0
/*Word doesn't fit in provided space, but isn't "long"*/
if(word_len < LV_TXT_LINE_BREAK_LONG_LEN) {
if(force) return break_index;
if(word_w_ptr != NULL) *word_w_ptr = 0; /*Return no word*/
return 0;
}
/*Word is "long," but insufficient amounts can fit in provided space*/
if(break_letter_count < LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN) {
if(force) return break_index;
if(word_w_ptr != NULL) *word_w_ptr = 0;
return 0;
}
/*Word is a "long", but letters may need to be better distributed*/
{
i = break_index;
int32_t n_move = LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN - (word_len - break_letter_count);
/*Move pointer "i" backwards*/
for(; n_move > 0; n_move--) {
_lv_txt_encoded_prev(txt, &i);
// TODO: it would be appropriate to update the returned word width here
// However, in current usage, this doesn't impact anything.
}
}
return i;
#else
if(force) return break_index;
if(word_w_ptr != NULL) *word_w_ptr = 0; /*Return no word*/
(void) break_letter_count;
return 0;
#endif
}
uint32_t _lv_txt_get_next_line(const char * txt, const lv_font_t * font,
lv_coord_t letter_space, lv_coord_t max_width, lv_text_flag_t flag)
{
if(txt == NULL) return 0;
if(txt[0] == '\0') return 0;
if(font == NULL) return 0;
/*If max_width doesn't mater simply find the new line character
*without thinking about word wrapping*/
if((flag & LV_TEXT_FLAG_EXPAND) || (flag & LV_TEXT_FLAG_FIT)) {
uint32_t i;
for(i = 0; txt[i] != '\n' && txt[i] != '\r' && txt[i] != '\0'; i++) {
/*Just find the new line chars or string ends by incrementing `i`*/
}
if(txt[i] != '\0') i++; /*To go beyond `\n`*/
return i;
}
if(flag & LV_TEXT_FLAG_EXPAND) max_width = LV_COORD_MAX;
lv_text_cmd_state_t cmd_state = LV_TEXT_CMD_STATE_WAIT;
uint32_t i = 0; /*Iterating index into txt*/
while(txt[i] != '\0' && max_width > 0) {
uint32_t word_w = 0;
uint32_t advance = lv_txt_get_next_word(&txt[i], font, letter_space, max_width, flag, &word_w, &cmd_state, i == 0);
max_width -= word_w;
if(advance == 0) {
if(i == 0) _lv_txt_encoded_next(txt, &i); // prevent inf loops
break;
}
i += advance;
if(txt[0] == '\n' || txt[0] == '\r') break;
if(txt[i] == '\n' || txt[i] == '\r') {
i++; /*Include the following newline in the current line*/
break;
}
}
/*Always step at least one to avoid infinite loops*/
if(i == 0) {
_lv_txt_encoded_next(txt, &i);
}
return i;
}
lv_coord_t lv_txt_get_width(const char * txt, uint32_t length, const lv_font_t * font, lv_coord_t letter_space,
lv_text_flag_t flag)
{
if(txt == NULL) return 0;
if(font == NULL) return 0;
if(txt[0] == '\0') return 0;
uint32_t i = 0;
lv_coord_t width = 0;
lv_text_cmd_state_t cmd_state = LV_TEXT_CMD_STATE_WAIT;
if(length != 0) {
while(i < length) {
uint32_t letter;
uint32_t letter_next;
_lv_txt_encoded_letter_next_2(txt, &letter, &letter_next, &i);
if((flag & LV_TEXT_FLAG_RECOLOR) != 0) {
if(_lv_txt_is_cmd(&cmd_state, letter) != false) {
continue;
}
}
lv_coord_t char_width = lv_font_get_glyph_width(font, letter, letter_next);
if(char_width > 0) {
width += char_width;
width += letter_space;
}
}
if(width > 0) {
width -= letter_space; /*Trim the last letter space. Important if the text is center
aligned*/
}
}
return width;
}
bool _lv_txt_is_cmd(lv_text_cmd_state_t * state, uint32_t c)
{
bool ret = false;
if(c == (uint32_t)LV_TXT_COLOR_CMD[0]) {
if(*state == LV_TEXT_CMD_STATE_WAIT) { /*Start char*/
*state = LV_TEXT_CMD_STATE_PAR;
ret = true;
}
/*Other start char in parameter is escaped cmd. char*/
else if(*state == LV_TEXT_CMD_STATE_PAR) {
*state = LV_TEXT_CMD_STATE_WAIT;
}
/*Command end*/
else if(*state == LV_TEXT_CMD_STATE_IN) {
*state = LV_TEXT_CMD_STATE_WAIT;
ret = true;
}
}
/*Skip the color parameter and wait the space after it*/
if(*state == LV_TEXT_CMD_STATE_PAR) {
if(c == ' ') {
*state = LV_TEXT_CMD_STATE_IN; /*After the parameter the text is in the command*/
}
ret = true;
}
return ret;
}
void _lv_txt_ins(char * txt_buf, uint32_t pos, const char * ins_txt)
{
if(txt_buf == NULL || ins_txt == NULL) return;
size_t old_len = strlen(txt_buf);
size_t ins_len = strlen(ins_txt);
if(ins_len == 0) return;
size_t new_len = ins_len + old_len;
pos = _lv_txt_encoded_get_byte_id(txt_buf, pos); /*Convert to byte index instead of letter index*/
/*Copy the second part into the end to make place to text to insert*/
size_t i;
for(i = new_len; i >= pos + ins_len; i--) {
txt_buf[i] = txt_buf[i - ins_len];
}
/*Copy the text into the new space*/
lv_memcpy_small(txt_buf + pos, ins_txt, ins_len);
}
void _lv_txt_cut(char * txt, uint32_t pos, uint32_t len)
{
if(txt == NULL) return;
size_t old_len = strlen(txt);
pos = _lv_txt_encoded_get_byte_id(txt, pos); /*Convert to byte index instead of letter index*/
len = _lv_txt_encoded_get_byte_id(&txt[pos], len);
/*Copy the second part into the end to make place to text to insert*/
uint32_t i;
for(i = pos; i <= old_len - len; i++) {
txt[i] = txt[i + len];
}
}
char * _lv_txt_set_text_vfmt(const char * fmt, va_list ap)
{
/*Allocate space for the new text by using trick from C99 standard section 7.19.6.12*/
va_list ap_copy;
va_copy(ap_copy, ap);
uint32_t len = lv_vsnprintf(NULL, 0, fmt, ap_copy);
va_end(ap_copy);
char * text = 0;
#if LV_USE_ARABIC_PERSIAN_CHARS
/*Put together the text according to the format string*/
char * raw_txt = lv_mem_buf_get(len + 1);
LV_ASSERT_MALLOC(raw_txt);
if(raw_txt == NULL) {
return NULL;
}
lv_vsnprintf(raw_txt, len + 1, fmt, ap);
/*Get the size of the Arabic text and process it*/
size_t len_ap = _lv_txt_ap_calc_bytes_cnt(raw_txt);
text = lv_mem_alloc(len_ap + 1);
LV_ASSERT_MALLOC(text);
if(text == NULL) {
return NULL;
}
_lv_txt_ap_proc(raw_txt, text);
lv_mem_buf_release(raw_txt);
#else
text = lv_mem_alloc(len + 1);
LV_ASSERT_MALLOC(text);
if(text == NULL) {
return NULL;
}
text[len] = 0; /*Ensure NULL termination*/
lv_vsnprintf(text, len + 1, fmt, ap);
#endif
return text;
}
void _lv_txt_encoded_letter_next_2(const char * txt, uint32_t * letter, uint32_t * letter_next, uint32_t * ofs)
{
*letter = _lv_txt_encoded_next(txt, ofs);
*letter_next = *letter != '\0' ? _lv_txt_encoded_next(&txt[*ofs], NULL) : 0;
}
#if LV_TXT_ENC == LV_TXT_ENC_UTF8
/*******************************
* UTF-8 ENCODER/DECODER
******************************/
/**
* Give the size of an UTF-8 coded character
* @param str pointer to a character in a string
* @return length of the UTF-8 character (1,2,3 or 4), 0 on invalid code.
*/
static uint8_t lv_txt_utf8_size(const char * str)
{
if(LV_IS_ASCII(str[0]))
return 1;
else if(LV_IS_2BYTES_UTF8_CODE(str[0]))
return 2;
else if(LV_IS_3BYTES_UTF8_CODE(str[0]))
return 3;
else if(LV_IS_4BYTES_UTF8_CODE(str[0]))
return 4;
return 0;
}
/**
* Convert an Unicode letter to UTF-8.
* @param letter_uni an Unicode letter
* @return UTF-8 coded character in Little Endian to be compatible with C chars (e.g. 'Á', 'Ű')
*/
static uint32_t lv_txt_unicode_to_utf8(uint32_t letter_uni)
{
if(letter_uni < 128) return letter_uni;
uint8_t bytes[4];
if(letter_uni < 0x0800) {
bytes[0] = ((letter_uni >> 6) & 0x1F) | 0xC0;
bytes[1] = ((letter_uni >> 0) & 0x3F) | 0x80;
bytes[2] = 0;
bytes[3] = 0;
}
else if(letter_uni < 0x010000) {
bytes[0] = ((letter_uni >> 12) & 0x0F) | 0xE0;
bytes[1] = ((letter_uni >> 6) & 0x3F) | 0x80;
bytes[2] = ((letter_uni >> 0) & 0x3F) | 0x80;
bytes[3] = 0;
}
else if(letter_uni < 0x110000) {
bytes[0] = ((letter_uni >> 18) & 0x07) | 0xF0;
bytes[1] = ((letter_uni >> 12) & 0x3F) | 0x80;
bytes[2] = ((letter_uni >> 6) & 0x3F) | 0x80;
bytes[3] = ((letter_uni >> 0) & 0x3F) | 0x80;
}
uint32_t * res_p = (uint32_t *)bytes;
return *res_p;
}
/**
* Convert a wide character, e.g. 'Á' little endian to be UTF-8 compatible
* @param c a wide character or a Little endian number
* @return `c` in big endian
*/
static uint32_t lv_txt_utf8_conv_wc(uint32_t c)
{
#if LV_BIG_ENDIAN_SYSTEM == 0
/*Swap the bytes (UTF-8 is big endian, but the MCUs are little endian)*/
if((c & 0x80) != 0) {
uint32_t swapped;
uint8_t c8[4];
lv_memcpy_small(c8, &c, 4);
swapped = (c8[0] << 24) + (c8[1] << 16) + (c8[2] << 8) + (c8[3]);
uint8_t i;
for(i = 0; i < 4; i++) {
if((swapped & 0xFF) == 0)
swapped = (swapped >> 8); /*Ignore leading zeros (they were in the end originally)*/
}
c = swapped;
}
#endif
return c;
}
/**
* Decode an UTF-8 character from a string.
* @param txt pointer to '\0' terminated string
* @param i start byte index in 'txt' where to start.
* After call it will point to the next UTF-8 char in 'txt'.
* NULL to use txt[0] as index
* @return the decoded Unicode character or 0 on invalid UTF-8 code
*/
static uint32_t lv_txt_utf8_next(const char * txt, uint32_t * i)
{
/**
* Unicode to UTF-8
* 00000000 00000000 00000000 0xxxxxxx -> 0xxxxxxx
* 00000000 00000000 00000yyy yyxxxxxx -> 110yyyyy 10xxxxxx
* 00000000 00000000 zzzzyyyy yyxxxxxx -> 1110zzzz 10yyyyyy 10xxxxxx
* 00000000 000wwwzz zzzzyyyy yyxxxxxx -> 11110www 10zzzzzz 10yyyyyy 10xxxxxx
*/
uint32_t result = 0;
/*Dummy 'i' pointer is required*/
uint32_t i_tmp = 0;
if(i == NULL) i = &i_tmp;
/*Normal ASCII*/
if(LV_IS_ASCII(txt[*i])) {
result = txt[*i];
(*i)++;
}
/*Real UTF-8 decode*/
else {
/*2 bytes UTF-8 code*/
if(LV_IS_2BYTES_UTF8_CODE(txt[*i])) {
result = (uint32_t)(txt[*i] & 0x1F) << 6;
(*i)++;
if(LV_IS_INVALID_UTF8_CODE(txt[*i])) return 0;
result += (txt[*i] & 0x3F);
(*i)++;
}
/*3 bytes UTF-8 code*/
else if(LV_IS_3BYTES_UTF8_CODE(txt[*i])) {
result = (uint32_t)(txt[*i] & 0x0F) << 12;
(*i)++;
if(LV_IS_INVALID_UTF8_CODE(txt[*i])) return 0;
result += (uint32_t)(txt[*i] & 0x3F) << 6;
(*i)++;
if(LV_IS_INVALID_UTF8_CODE(txt[*i])) return 0;
result += (txt[*i] & 0x3F);
(*i)++;
}
/*4 bytes UTF-8 code*/
else if(LV_IS_4BYTES_UTF8_CODE(txt[*i])) {
result = (uint32_t)(txt[*i] & 0x07) << 18;
(*i)++;
if(LV_IS_INVALID_UTF8_CODE(txt[*i])) return 0;
result += (uint32_t)(txt[*i] & 0x3F) << 12;
(*i)++;
if(LV_IS_INVALID_UTF8_CODE(txt[*i])) return 0;
result += (uint32_t)(txt[*i] & 0x3F) << 6;
(*i)++;
if(LV_IS_INVALID_UTF8_CODE(txt[*i])) return 0;
result += txt[*i] & 0x3F;
(*i)++;
}
else {
(*i)++; /*Not UTF-8 char. Go the next.*/
}
}
return result;
}
/**
* Get previous UTF-8 character form a string.
* @param txt pointer to '\0' terminated string
* @param i start byte index in 'txt' where to start. After the call it will point to the previous
* UTF-8 char in 'txt'.
* @return the decoded Unicode character or 0 on invalid UTF-8 code
*/
static uint32_t lv_txt_utf8_prev(const char * txt, uint32_t * i)
{
uint8_t c_size;
uint8_t cnt = 0;
/*Try to find a !0 long UTF-8 char by stepping one character back*/
(*i)--;
do {
if(cnt >= 4) return 0; /*No UTF-8 char found before the initial*/
c_size = _lv_txt_encoded_size(&txt[*i]);
if(c_size == 0) {
if(*i != 0)
(*i)--;
else
return 0;
}
cnt++;
} while(c_size == 0);
uint32_t i_tmp = *i;
uint32_t letter = _lv_txt_encoded_next(txt, &i_tmp); /*Character found, get it*/
return letter;
}
/**
* Convert a character index (in an UTF-8 text) to byte index.
* E.g. in "AÁRT" index of 'R' is 2th char but start at byte 3 because 'Á' is 2 bytes long
* @param txt a '\0' terminated UTF-8 string
* @param utf8_id character index
* @return byte index of the 'utf8_id'th letter
*/
static uint32_t lv_txt_utf8_get_byte_id(const char * txt, uint32_t utf8_id)
{
uint32_t i;
uint32_t byte_cnt = 0;
for(i = 0; i < utf8_id && txt[byte_cnt] != '\0'; i++) {
uint8_t c_size = _lv_txt_encoded_size(&txt[byte_cnt]);
/* If the char was invalid tell it's 1 byte long*/
byte_cnt += c_size ? c_size : 1;
}
return byte_cnt;
}
/**
* Convert a byte index (in an UTF-8 text) to character index.
* E.g. in "AÁRT" index of 'R' is 2th char but start at byte 3 because 'Á' is 2 bytes long
* @param txt a '\0' terminated UTF-8 string
* @param byte_id byte index
* @return character index of the letter at 'byte_id'th position
*/
static uint32_t lv_txt_utf8_get_char_id(const char * txt, uint32_t byte_id)
{
uint32_t i = 0;
uint32_t char_cnt = 0;
while(i < byte_id) {
_lv_txt_encoded_next(txt, &i); /*'i' points to the next letter so use the prev. value*/
char_cnt++;
}
return char_cnt;
}
/**
* Get the number of characters (and NOT bytes) in a string. Decode it with UTF-8 if enabled.
* E.g.: "ÁBC" is 3 characters (but 4 bytes)
* @param txt a '\0' terminated char string
* @return number of characters
*/
static uint32_t lv_txt_utf8_get_length(const char * txt)
{
uint32_t len = 0;
uint32_t i = 0;
while(txt[i] != '\0') {
_lv_txt_encoded_next(txt, &i);
len++;
}
return len;
}
#elif LV_TXT_ENC == LV_TXT_ENC_ASCII
/*******************************
* ASCII ENCODER/DECOER
******************************/
/**
* Give the size of an ISO8859-1 coded character
* @param str pointer to a character in a string
* @return length of the UTF-8 character (1,2,3 or 4). O on invalid code
*/
static uint8_t lv_txt_iso8859_1_size(const char * str)
{
LV_UNUSED(str); /*Unused*/
return 1;
}
/**
* Convert an Unicode letter to ISO8859-1.
* @param letter_uni an Unicode letter
* @return ISO8859-1 coded character in Little Endian to be compatible with C chars (e.g. 'Á', 'Ű')
*/
static uint32_t lv_txt_unicode_to_iso8859_1(uint32_t letter_uni)
{
if(letter_uni < 256)
return letter_uni;
else
return ' ';
}
/**
* Convert wide characters to ASCII, however wide characters in ASCII range (e.g. 'A') are ASCII compatible by default.
* So this function does nothing just returns with `c`.
* @param c a character, e.g. 'A'
* @return same as `c`
*/
static uint32_t lv_txt_iso8859_1_conv_wc(uint32_t c)
{
return c;
}
/**
* Decode an ISO8859-1 character from a string.
* @param txt pointer to '\0' terminated string
* @param i start byte index in 'txt' where to start.
* After call it will point to the next UTF-8 char in 'txt'.
* NULL to use txt[0] as index
* @return the decoded Unicode character or 0 on invalid UTF-8 code
*/
static uint32_t lv_txt_iso8859_1_next(const char * txt, uint32_t * i)
{
if(i == NULL) return txt[1]; /*Get the next char*/
uint8_t letter = txt[*i];
(*i)++;
return letter;
}
/**
* Get previous ISO8859-1 character form a string.
* @param txt pointer to '\0' terminated string
* @param i start byte index in 'txt' where to start. After the call it will point to the previous UTF-8 char in 'txt'.
* @return the decoded Unicode character or 0 on invalid UTF-8 code
*/
static uint32_t lv_txt_iso8859_1_prev(const char * txt, uint32_t * i)
{
if(i == NULL) return *(txt - 1); /*Get the prev. char*/
(*i)--;
uint8_t letter = txt[*i];
return letter;
}
/**
* Convert a character index (in an ISO8859-1 text) to byte index.
* E.g. in "AÁRT" index of 'R' is 2th char but start at byte 3 because 'Á' is 2 bytes long
* @param txt a '\0' terminated UTF-8 string
* @param utf8_id character index
* @return byte index of the 'utf8_id'th letter
*/
static uint32_t lv_txt_iso8859_1_get_byte_id(const char * txt, uint32_t utf8_id)
{
LV_UNUSED(txt); /*Unused*/
return utf8_id; /*In Non encoded no difference*/
}
/**
* Convert a byte index (in an ISO8859-1 text) to character index.
* E.g. in "AÁRT" index of 'R' is 2th char but start at byte 3 because 'Á' is 2 bytes long
* @param txt a '\0' terminated UTF-8 string
* @param byte_id byte index
* @return character index of the letter at 'byte_id'th position
*/
static uint32_t lv_txt_iso8859_1_get_char_id(const char * txt, uint32_t byte_id)
{
LV_UNUSED(txt); /*Unused*/
return byte_id; /*In Non encoded no difference*/
}
/**
* Get the number of characters (and NOT bytes) in a string. Decode it with UTF-8 if enabled.
* E.g.: "ÁBC" is 3 characters (but 4 bytes)
* @param txt a '\0' terminated char string
* @return number of characters
*/
static uint32_t lv_txt_iso8859_1_get_length(const char * txt)
{
return strlen(txt);
}
#else
#error "Invalid character encoding. See `LV_TXT_ENC` in `lv_conf.h`"
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/misc/lv_txt.c | C | apache-2.0 | 28,172 |
/**
* @file lv_text.h
*
*/
#ifndef LV_TXT_H
#define LV_TXT_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#include <stdbool.h>
#include <stdarg.h>
#include "lv_area.h"
#include "../font/lv_font.h"
#include "lv_printf.h"
#include "lv_types.h"
/*********************
* DEFINES
*********************/
#ifndef LV_TXT_COLOR_CMD
#define LV_TXT_COLOR_CMD "#"
#endif
#define LV_TXT_ENC_UTF8 1
#define LV_TXT_ENC_ASCII 2
/**********************
* TYPEDEFS
**********************/
/**
* Options for text rendering.
*/
enum {
LV_TEXT_FLAG_NONE = 0x00,
LV_TEXT_FLAG_RECOLOR = 0x01, /**< Enable parsing of recolor command*/
LV_TEXT_FLAG_EXPAND = 0x02, /**< Ignore max-width to avoid automatic word wrapping*/
LV_TEXT_FLAG_FIT = 0x04, /**< Max-width is already equal to the longest line. (Used to skip some calculation)*/
};
typedef uint8_t lv_text_flag_t;
/**
* State machine for text renderer.*/
enum {
LV_TEXT_CMD_STATE_WAIT, /**< Waiting for command*/
LV_TEXT_CMD_STATE_PAR, /**< Processing the parameter*/
LV_TEXT_CMD_STATE_IN, /**< Processing the command*/
};
typedef uint8_t lv_text_cmd_state_t;
/** Label align policy*/
enum {
LV_TEXT_ALIGN_AUTO, /**< Align text auto*/
LV_TEXT_ALIGN_LEFT, /**< Align text to left*/
LV_TEXT_ALIGN_CENTER, /**< Align text to center*/
LV_TEXT_ALIGN_RIGHT, /**< Align text to right*/
};
typedef uint8_t lv_text_align_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Get size of a text
* @param size_res pointer to a 'point_t' variable to store the result
* @param text pointer to a text
* @param font pointer to font of the text
* @param letter_space letter space of the text
* @param line_space line space of the text
* @param flags settings for the text from ::lv_text_flag_t
* @param max_width max with of the text (break the lines to fit this size) Set CORD_MAX to avoid
* line breaks
*/
void lv_txt_get_size(lv_point_t * size_res, const char * text, const lv_font_t * font, lv_coord_t letter_space,
lv_coord_t line_space, lv_coord_t max_width, lv_text_flag_t flag);
/**
* Get the next line of text. Check line length and break chars too.
* @param txt a '\0' terminated string
* @param font pointer to a font
* @param letter_space letter space
* @param max_width max with of the text (break the lines to fit this size) Set CORD_MAX to avoid
* line breaks
* @param flags settings for the text from 'txt_flag_type' enum
* @return the index of the first char of the new line (in byte index not letter index. With UTF-8
* they are different)
*/
uint32_t _lv_txt_get_next_line(const char * txt, const lv_font_t * font, lv_coord_t letter_space, lv_coord_t max_width,
lv_text_flag_t flag);
/**
* Give the length of a text with a given font
* @param txt a '\0' terminate string
* @param length length of 'txt' in byte count and not characters (Á is 1 character but 2 bytes in
* UTF-8)
* @param font pointer to a font
* @param letter_space letter space
* @param flags settings for the text from 'txt_flag_t' enum
* @return length of a char_num long text
*/
lv_coord_t lv_txt_get_width(const char * txt, uint32_t length, const lv_font_t * font, lv_coord_t letter_space,
lv_text_flag_t flag);
/**
* Check next character in a string and decide if the character is part of the command or not
* @param state pointer to a txt_cmd_state_t variable which stores the current state of command
* processing
* @param c the current character
* @return true: the character is part of a command and should not be written,
* false: the character should be written
*/
bool _lv_txt_is_cmd(lv_text_cmd_state_t * state, uint32_t c);
/**
* Insert a string into an other
* @param txt_buf the original text (must be big enough for the result text and NULL terminated)
* @param pos position to insert (0: before the original text, 1: after the first char etc.)
* @param ins_txt text to insert, must be '\0' terminated
*/
void _lv_txt_ins(char * txt_buf, uint32_t pos, const char * ins_txt);
/**
* Delete a part of a string
* @param txt string to modify, must be '\0' terminated and should point to a heap or stack frame, not read-only memory.
* @param pos position where to start the deleting (0: before the first char, 1: after the first
* char etc.)
* @param len number of characters to delete
*/
void _lv_txt_cut(char * txt, uint32_t pos, uint32_t len);
/**
* return a new formatted text. Memory will be allocated to store the text.
* @param fmt `printf`-like format
* @return pointer to the allocated text string.
*/
char * _lv_txt_set_text_vfmt(const char * fmt, va_list ap) LV_FORMAT_ATTRIBUTE(1, 0);
/**
* Decode two encoded character from a string.
* @param txt pointer to '\0' terminated string
* @param letter the first decoded Unicode character or 0 on invalid data code
* @param letter_next the second decoded Unicode character or 0 on invalid data code
* @param ofs start index in 'txt' where to start.
* After the call it will point to the next encoded char in 'txt'.
* NULL to use txt[0] as index
*/
void _lv_txt_encoded_letter_next_2(const char * txt, uint32_t * letter, uint32_t * letter_next, uint32_t * ofs);
/**
* Test if char is break char or not (a text can broken here or not)
* @param letter a letter
* @return false: 'letter' is not break char
*/
static inline bool _lv_txt_is_break_char(uint32_t letter)
{
uint8_t i;
bool ret = false;
/* each chinese character can be break */
if(letter >= 0x4E00 && letter <= 0x9FA5) {
return true;
}
/*Compare the letter to TXT_BREAK_CHARS*/
for(i = 0; LV_TXT_BREAK_CHARS[i] != '\0'; i++) {
if(letter == (uint32_t)LV_TXT_BREAK_CHARS[i]) {
ret = true; /*If match then it is break char*/
break;
}
}
return ret;
}
/***************************************************************
* GLOBAL FUNCTION POINTERS FOR CHARACTER ENCODING INTERFACE
***************************************************************/
/**
* Give the size of an encoded character
* @param str pointer to a character in a string
* @return length of the encoded character (1,2,3 ...). O in invalid
*/
extern uint8_t (*_lv_txt_encoded_size)(const char *);
/**
* Convert an Unicode letter to encoded
* @param letter_uni an Unicode letter
* @return Encoded character in Little Endian to be compatible with C chars (e.g. 'Á', 'Ü')
*/
extern uint32_t (*_lv_txt_unicode_to_encoded)(uint32_t);
/**
* Convert a wide character, e.g. 'Á' little endian to be compatible with the encoded format.
* @param c a wide character
* @return `c` in the encoded format
*/
extern uint32_t (*_lv_txt_encoded_conv_wc)(uint32_t c);
/**
* Decode the next encoded character from a string.
* @param txt pointer to '\0' terminated string
* @param i start index in 'txt' where to start.
* After the call it will point to the next encoded char in 'txt'.
* NULL to use txt[0] as index
* @return the decoded Unicode character or 0 on invalid data code
*/
extern uint32_t (*_lv_txt_encoded_next)(const char *, uint32_t *);
/**
* Get the previous encoded character form a string.
* @param txt pointer to '\0' terminated string
* @param i_start index in 'txt' where to start. After the call it will point to the previous
* encoded char in 'txt'.
* @return the decoded Unicode character or 0 on invalid data
*/
extern uint32_t (*_lv_txt_encoded_prev)(const char *, uint32_t *);
/**
* Convert a letter index (in the encoded text) to byte index.
* E.g. in UTF-8 "AÁRT" index of 'R' is 2 but start at byte 3 because 'Á' is 2 bytes long
* @param txt a '\0' terminated UTF-8 string
* @param enc_id letter index
* @return byte index of the 'enc_id'th letter
*/
extern uint32_t (*_lv_txt_encoded_get_byte_id)(const char *, uint32_t);
/**
* Convert a byte index (in an encoded text) to character index.
* E.g. in UTF-8 "AÁRT" index of 'R' is 2 but start at byte 3 because 'Á' is 2 bytes long
* @param txt a '\0' terminated UTF-8 string
* @param byte_id byte index
* @return character index of the letter at 'byte_id'th position
*/
extern uint32_t (*_lv_txt_encoded_get_char_id)(const char *, uint32_t);
/**
* Get the number of characters (and NOT bytes) in a string.
* E.g. in UTF-8 "ÁBC" is 3 characters (but 4 bytes)
* @param txt a '\0' terminated char string
* @return number of characters
*/
extern uint32_t (*_lv_txt_get_encoded_length)(const char *);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*USE_TXT*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/misc/lv_txt.h | C | apache-2.0 | 8,837 |
/**
* @file lv_txt_ap.c
*
*/
/*********************
* INCLUDES
*********************/
#include <stddef.h>
#include "lv_bidi.h"
#include "lv_txt.h"
#include "lv_txt_ap.h"
#include "lv_mem.h"
#include "../draw/lv_draw.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
uint8_t char_offset;
uint16_t char_end_form;
int8_t char_begining_form_offset;
int8_t char_middle_form_offset;
int8_t char_isolated_form_offset;
struct {
uint8_t conj_to_previous;
uint8_t conj_to_next;
} ap_chars_conjunction;
} ap_chars_map_t;
/**********************
* STATIC PROTOTYPES
**********************/
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
static uint32_t lv_ap_get_char_index(uint16_t c);
static uint32_t lv_txt_lam_alef(uint32_t ch_curr, uint32_t ch_next);
static bool lv_txt_is_arabic_vowel(uint16_t c);
/**********************
* STATIC VARIABLES
**********************/
const ap_chars_map_t ap_chars_map[] = {
/*{Key Offset, End, Beginning, Middle, Isolated, {conjunction}}*/
{1, 0xFE84, -1, 0, -1, {1, 0}}, // أ
{2, 0xFE86, -1, 0, -1, {1, 0}}, // ؤ
{3, 0xFE88, -1, 0, -1, {1, 0}}, // ﺇ
{4, 0xFE8A, 1, 2, -1, {1, 0}}, // ئ
{5, 0xFE8E, -1, 0, -1, {1, 0}}, // آ
{6, 0xFE90, 1, 2, -1, {1, 1}}, // ب
{92, 0xFB57, 1, 2, -1, {1, 1}}, // پ
{8, 0xFE96, 1, 2, -1, {1, 1}}, // ت
{9, 0xFE9A, 1, 2, -1, {1, 1}}, // ث
{10, 0xFE9E, 1, 2, -1, {1, 1}}, // ج
{100, 0xFB7B, 1, 2, -1, {1, 1}}, // چ
{11, 0xFEA2, 1, 2, -1, {1, 1}}, // ح
{12, 0xFEA6, 1, 2, -1, {1, 1}}, // خ
{13, 0xFEAA, -1, 0, -1, {1, 0}}, // د
{14, 0xFEAC, -1, 0, -1, {1, 0}}, // ذ
{15, 0xFEAE, -1, 0, -1, {1, 0}}, // ر
{16, 0xFEB0, -1, 0, -1, {1, 0}}, // ز
{118, 0xFB8B, -1, 0, -1, {1, 0}}, // ژ
{17, 0xFEB2, 1, 2, -1, {1, 1}}, // س
{18, 0xFEB6, 1, 2, -1, {1, 1}}, // ش
{19, 0xFEBA, 1, 2, -1, {1, 1}}, // ص
{20, 0xFEBE, 1, 2, -1, {1, 1}}, // ض
{21, 0xFEC2, 1, 2, -1, {1, 1}}, // ط
{22, 0xFEC6, 1, 2, -1, {1, 1}}, // ظ
{23, 0xFECA, 1, 2, -1, {1, 1}}, // ع
{24, 0xFECE, 1, 2, -1, {1, 1}}, // غ
{30, 0x0640, 0, 0, 0, {1, 1}}, // - (mad, hyphen)
{31, 0xFED2, 1, 2, -1, {1, 1}}, // ف
{32, 0xFED6, 1, 2, -1, {1, 1}}, // ق
{135, 0xFB8F, 1, 2, -1, {1, 1}}, // ک
{33, 0xFEDA, 1, 2, -1, {1, 1}}, // ﻙ
{141, 0xFB93, 1, 2, -1, {1, 1}}, // گ
{34, 0xFEDE, 1, 2, -1, {1, 1}}, // ل
{35, 0xFEE2, 1, 2, -1, {1, 1}}, // م
{36, 0xFEE6, 1, 2, -1, {1, 1}}, // ن
{38, 0xFEEE, -1, 0, -1, {1, 0}}, // و
{37, 0xFEEA, 1, 2, -1, {1, 1}}, // ه
{39, 0xFEF0, 0, 0, -1, {1, 0}}, // ى
{40, 0xFEF2, 1, 2, -1, {1, 1}}, // ي
{170, 0xFBFD, 1, 2, -1, {1, 1}}, // ی
{7, 0xFE94, 1, 2, -1, {1, 0}}, // ة
{206, 0x06F0, 1, 2, -1, {0, 0}}, // ۰
{207, 0x06F1, 0, 0, 0, {0, 0}}, // ۱
{208, 0x06F2, 0, 0, 0, {0, 0}}, // ۲
{209, 0x06F3, 0, 0, 0, {0, 0}}, // ۳
{210, 0x06F4, 0, 0, 0, {0, 0}}, // ۴
{211, 0x06F5, 0, 0, 0, {0, 0}}, // ۵
{212, 0x06F6, 0, 0, 0, {0, 0}}, // ۶
{213, 0x06F7, 0, 0, 0, {0, 0}}, // ۷
{214, 0x06F8, 0, 0, 0, {0, 0}}, // ۸
{215, 0x06F9, 0, 0, 0, {0, 0}}, // ۹
LV_AP_END_CHARS_LIST
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
uint32_t _lv_txt_ap_calc_bytes_cnt(const char * txt)
{
uint32_t txt_length = 0;
uint32_t chars_cnt = 0;
uint32_t current_ap_idx = 0;
uint32_t i, j;
uint32_t ch_enc;
txt_length = _lv_txt_get_encoded_length(txt);
i = 0;
j = 0;
while(i < txt_length) {
ch_enc = _lv_txt_encoded_next(txt, &j);
current_ap_idx = lv_ap_get_char_index(ch_enc);
if(current_ap_idx != LV_UNDEF_ARABIC_PERSIAN_CHARS)
ch_enc = ap_chars_map[current_ap_idx].char_end_form;
if(ch_enc < 0x80)
chars_cnt++;
else if(ch_enc < 0x0800)
chars_cnt += 2;
else if(ch_enc < 0x010000)
chars_cnt += 3;
else
chars_cnt += 4;
i++;
}
return chars_cnt + 1;
}
void _lv_txt_ap_proc(const char * txt, char * txt_out)
{
uint32_t txt_length = 0;
uint32_t index_current, idx_next, idx_previous, i, j;
uint32_t * ch_enc;
uint32_t * ch_fin;
char * txt_out_temp;
txt_length = _lv_txt_get_encoded_length(txt);
ch_enc = (uint32_t *)lv_mem_alloc(sizeof(uint32_t) * (txt_length + 1));
ch_fin = (uint32_t *)lv_mem_alloc(sizeof(uint32_t) * (txt_length + 1));
i = 0;
j = 0;
while(j < txt_length)
ch_enc[j++] = _lv_txt_encoded_next(txt, &i);
ch_enc[j] = 0;
i = 0;
j = 0;
idx_previous = LV_UNDEF_ARABIC_PERSIAN_CHARS;
while(i < txt_length) {
index_current = lv_ap_get_char_index(ch_enc[i]);
idx_next = lv_ap_get_char_index(ch_enc[i + 1]);
if(lv_txt_is_arabic_vowel(ch_enc[i])) { // Current character is a vowel
ch_fin[j] = ch_enc[i];
i++;
j++;
continue; // Skip this character
}
else if(lv_txt_is_arabic_vowel(ch_enc[i + 1])) { // Next character is a vowel
idx_next = lv_ap_get_char_index(ch_enc[i + 2]); // Skip the vowel character to join with the character after it
}
if(index_current == LV_UNDEF_ARABIC_PERSIAN_CHARS) {
ch_fin[j] = ch_enc[i];
j++;
i++;
idx_previous = LV_UNDEF_ARABIC_PERSIAN_CHARS;
continue;
}
uint8_t conjunction_to_previuse = (i == 0 ||
idx_previous == LV_UNDEF_ARABIC_PERSIAN_CHARS) ? 0 : ap_chars_map[idx_previous].ap_chars_conjunction.conj_to_next;
uint8_t conjunction_to_next = ((i == txt_length - 1) ||
idx_next == LV_UNDEF_ARABIC_PERSIAN_CHARS) ? 0 : ap_chars_map[idx_next].ap_chars_conjunction.conj_to_previous;
uint32_t lam_alef = lv_txt_lam_alef(index_current, idx_next);
if(lam_alef) {
if(conjunction_to_previuse) {
lam_alef ++;
}
ch_fin[j] = lam_alef;
idx_previous = LV_UNDEF_ARABIC_PERSIAN_CHARS;
i += 2;
j++;
continue;
}
if(conjunction_to_previuse && conjunction_to_next)
ch_fin[j] = ap_chars_map[index_current].char_end_form + ap_chars_map[index_current].char_middle_form_offset;
else if(!conjunction_to_previuse && conjunction_to_next)
ch_fin[j] = ap_chars_map[index_current].char_end_form + ap_chars_map[index_current].char_begining_form_offset;
else if(conjunction_to_previuse && !conjunction_to_next)
ch_fin[j] = ap_chars_map[index_current].char_end_form;
else
ch_fin[j] = ap_chars_map[index_current].char_end_form + ap_chars_map[index_current].char_isolated_form_offset;
idx_previous = index_current;
i++;
j++;
}
ch_fin[j] = 0;
for(i = 0; i < txt_length; i++)
ch_enc[i] = 0;
for(i = 0; i < j; i++)
ch_enc[i] = ch_fin[i];
lv_mem_free(ch_fin);
txt_out_temp = txt_out;
i = 0;
while(i < txt_length) {
if(ch_enc[i] < 0x80) {
*(txt_out_temp++) = ch_enc[i] & 0xFF;
}
else if(ch_enc[i] < 0x0800) {
*(txt_out_temp++) = ((ch_enc[i] >> 6) & 0x1F) | 0xC0;
*(txt_out_temp++) = ((ch_enc[i] >> 0) & 0x3F) | 0x80;
}
else if(ch_enc[i] < 0x010000) {
*(txt_out_temp++) = ((ch_enc[i] >> 12) & 0x0F) | 0xE0;
*(txt_out_temp++) = ((ch_enc[i] >> 6) & 0x3F) | 0x80;
*(txt_out_temp++) = ((ch_enc[i] >> 0) & 0x3F) | 0x80;
}
else if(ch_enc[i] < 0x110000) {
*(txt_out_temp++) = ((ch_enc[i] >> 18) & 0x07) | 0xF0;
*(txt_out_temp++) = ((ch_enc[i] >> 12) & 0x3F) | 0x80;
*(txt_out_temp++) = ((ch_enc[i] >> 6) & 0x3F) | 0x80;
*(txt_out_temp++) = ((ch_enc[i] >> 0) & 0x3F) | 0x80;
}
i++;
}
*(txt_out_temp) = '\0';
lv_mem_free(ch_enc);
}
/**********************
* STATIC FUNCTIONS
**********************/
static uint32_t lv_ap_get_char_index(uint16_t c)
{
for(uint8_t i = 0; ap_chars_map[i].char_end_form; i++) {
if(c == (ap_chars_map[i].char_offset + LV_AP_ALPHABET_BASE_CODE))
return i;
else if(c == ap_chars_map[i].char_end_form //is it an End form
|| c == (ap_chars_map[i].char_end_form + ap_chars_map[i].char_begining_form_offset) //is it a Beginning form
|| c == (ap_chars_map[i].char_end_form + ap_chars_map[i].char_middle_form_offset) //is it a middle form
|| c == (ap_chars_map[i].char_end_form + ap_chars_map[i].char_isolated_form_offset)) { //is it an isolated form
return i;
}
}
return LV_UNDEF_ARABIC_PERSIAN_CHARS;
}
static uint32_t lv_txt_lam_alef(uint32_t ch_curr, uint32_t ch_next)
{
uint32_t ch_code = 0;
if(ap_chars_map[ch_curr].char_offset != 34) {
return 0;
}
if(ch_next == LV_UNDEF_ARABIC_PERSIAN_CHARS) {
return 0;
}
ch_code = ap_chars_map[ch_next].char_offset + LV_AP_ALPHABET_BASE_CODE;
if(ch_code == 0x0622) {
return 0xFEF5; // (lam-alef) mad
}
if(ch_code == 0x0623) {
return 0xFEF7; // (lam-alef) top hamza
}
if(ch_code == 0x0625) {
return 0xFEF9; // (lam-alef) bot hamza
}
if(ch_code == 0x0627) {
return 0xFEFB; // (lam-alef) alef
}
return 0;
}
static bool lv_txt_is_arabic_vowel(uint16_t c)
{
return (c >= 0x064B) && (c <= 0x0652);
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/misc/lv_txt_ap.c | C | apache-2.0 | 10,026 |
/**
* @file lv_txt_ap.h
*
*/
#ifndef LV_TXT_AP_H
#define LV_TXT_AP_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include <stddef.h>
#include "lv_txt.h"
#include "../draw/lv_draw.h"
#if LV_USE_ARABIC_PERSIAN_CHARS == 1
/*********************
* DEFINES
*********************/
#define LV_UNDEF_ARABIC_PERSIAN_CHARS (UINT32_MAX)
#define LV_AP_ALPHABET_BASE_CODE 0x0622
#define LV_AP_END_CHARS_LIST {0,0,0,0,0,{0,0}}
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
uint32_t _lv_txt_ap_calc_bytes_cnt(const char * txt);
void _lv_txt_ap_proc(const char * txt, char * txt_out);
/**********************
* MACROS
**********************/
#endif // LV_USE_ARABIC_PERSIAN_CHARS
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_TXT_AP_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/misc/lv_txt_ap.h | C | apache-2.0 | 933 |
/**
* @file lv_types.h
*
*/
#ifndef LV_TYPES_H
#define LV_TYPES_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include <stdint.h>
/*********************
* DEFINES
*********************/
// If __UINTPTR_MAX__ or UINTPTR_MAX are available, use them to determine arch size
#if defined(__UINTPTR_MAX__) && __UINTPTR_MAX__ > 0xFFFFFFFF
#define LV_ARCH_64
#elif defined(UINTPTR_MAX) && UINTPTR_MAX > 0xFFFFFFFF
#define LV_ARCH_64
// Otherwise use compiler-dependent means to determine arch size
#elif defined(_WIN64) || defined(__x86_64__) || defined(__ppc64__) || defined (__aarch64__)
#define LV_ARCH_64
#endif
/**********************
* TYPEDEFS
**********************/
/**
* LVGL error codes.
*/
enum {
LV_RES_INV = 0, /*Typically indicates that the object is deleted (become invalid) in the action
function or an operation was failed*/
LV_RES_OK, /*The object is valid (no deleted) after the action*/
};
typedef uint8_t lv_res_t;
#if defined(__cplusplus) || __STDC_VERSION__ >= 199901L
// If c99 or newer, use the definition of uintptr_t directly from <stdint.h>
typedef uintptr_t lv_uintptr_t;
#else
// Otherwise, use the arch size determination
#ifdef LV_ARCH_64
typedef uint64_t lv_uintptr_t;
#else
typedef uint32_t lv_uintptr_t;
#endif
#endif
/**********************
* GLOBAL PROTOTYPES
**********************/
/**********************
* MACROS
**********************/
#define LV_UNUSED(x) ((void)x)
#define _LV_CONCAT(x, y) x ## y
#define LV_CONCAT(x, y) _LV_CONCAT(x, y)
#define _LV_CONCAT3(x, y, z) x ## y ## z
#define LV_CONCAT3(x, y, z) _LV_CONCAT3(x, y, z)
#if defined(PYCPARSER)
#define LV_FORMAT_ATTRIBUTE(fmtstr, vararg)
#elif defined(__GNUC__) && ((__GNUC__ == 4 && __GNUC_MINOR__ >= 4) || __GNUC__ > 4)
#define LV_FORMAT_ATTRIBUTE(fmtstr, vararg) __attribute__((format(gnu_printf, fmtstr, vararg)))
#elif (defined(__clang__) || defined(__GNUC__) || defined(__GNUG__))
#define LV_FORMAT_ATTRIBUTE(fmtstr, vararg) __attribute__((format(printf, fmtstr, vararg)))
#else
#define LV_FORMAT_ATTRIBUTE(fmtstr, vararg)
#endif
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_TYPES_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/misc/lv_types.h | C | apache-2.0 | 2,240 |
/**
* @file lv_utils.c
*
*/
/*********************
* INCLUDES
*********************/
#include <stddef.h>
#include "lv_utils.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/** Searches base[0] to base[n - 1] for an item that matches *key.
*
* @note The function cmp must return negative if its first
* argument (the search key) is less that its second (a table entry),
* zero if equal, and positive if greater.
*
* @note Items in the array must be in ascending order.
*
* @param key Pointer to item being searched for
* @param base Pointer to first element to search
* @param n Number of elements
* @param size Size of each element
* @param cmp Pointer to comparison function (see #lv_font_codeCompare as a comparison function
* example)
*
* @return a pointer to a matching item, or NULL if none exists.
*/
void * _lv_utils_bsearch(const void * key, const void * base, uint32_t n, uint32_t size,
int32_t (*cmp)(const void * pRef, const void * pElement))
{
const char * middle;
int32_t c;
for(middle = base; n != 0;) {
middle += (n / 2) * size;
if((c = (*cmp)(key, middle)) > 0) {
n = (n / 2) - ((n & 1) == 0);
base = (middle += size);
}
else if(c < 0) {
n /= 2;
middle = base;
}
else {
return (char *)middle;
}
}
return NULL;
}
/**********************
* STATIC FUNCTIONS
**********************/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/misc/lv_utils.c | C | apache-2.0 | 1,878 |
/**
* @file lv_utils.h
*
*/
#ifndef LV_UTILS_H
#define LV_UTILS_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include <stdint.h>
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/** Searches base[0] to base[n - 1] for an item that matches *key.
*
* @note The function cmp must return negative if it's first
* argument (the search key) is less that it's second (a table entry),
* zero if equal, and positive if greater.
*
* @note Items in the array must be in ascending order.
*
* @param key Pointer to item being searched for
* @param base Pointer to first element to search
* @param n Number of elements
* @param size Size of each element
* @param cmp Pointer to comparison function (see #lv_font_codeCompare as a comparison function
* example)
*
* @return a pointer to a matching item, or NULL if none exists.
*/
void * _lv_utils_bsearch(const void * key, const void * base, uint32_t n, uint32_t size,
int32_t (*cmp)(const void * pRef, const void * pElement));
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/misc/lv_utils.h | C | apache-2.0 | 1,359 |
/**
* @file lv_arc.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_arc.h"
#if LV_USE_ARC != 0
#include "../core/lv_group.h"
#include "../core/lv_indev.h"
#include "../misc/lv_assert.h"
#include "../misc/lv_math.h"
#include "../draw/lv_draw_arc.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_arc_class
#define VALUE_UNSET INT16_MIN
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_arc_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_arc_draw(lv_event_t * e);
static void lv_arc_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void inv_arc_area(lv_obj_t * arc, uint16_t start_angle, uint16_t end_angle, lv_part_t part);
static void get_center(lv_obj_t * obj, lv_point_t * center, lv_coord_t * arc_r);
static void get_knob_area(lv_obj_t * arc, const lv_point_t * center, lv_coord_t r, lv_area_t * knob_area);
static void value_update(lv_obj_t * arc);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_arc_class = {
.constructor_cb = lv_arc_constructor,
.event_cb = lv_arc_event,
.instance_size = sizeof(lv_arc_t),
.editable = LV_OBJ_CLASS_EDITABLE_TRUE,
.base_class = &lv_obj_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_arc_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*======================
* Add/remove functions
*=====================*/
/*
* New object specific "add" or "remove" functions come here
*/
/*=====================
* Setter functions
*====================*/
void lv_arc_set_start_angle(lv_obj_t * obj, uint16_t start)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_arc_t * arc = (lv_arc_t *)obj;
if(start > 360) start -= 360;
int16_t old_delta = arc->indic_angle_end - arc->indic_angle_start;
int16_t new_delta = arc->indic_angle_end - start;
if(old_delta < 0) old_delta = 360 + old_delta;
if(new_delta < 0) new_delta = 360 + new_delta;
if(LV_ABS(new_delta - old_delta) > 180) lv_obj_invalidate(obj);
else if(new_delta < old_delta) inv_arc_area(obj, arc->indic_angle_start, start, LV_PART_INDICATOR);
else if(old_delta < new_delta) inv_arc_area(obj, start, arc->indic_angle_start, LV_PART_INDICATOR);
arc->indic_angle_start = start;
}
void lv_arc_set_end_angle(lv_obj_t * obj, uint16_t end)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_arc_t * arc = (lv_arc_t *)obj;
if(end > 360) end -= 360;
int16_t old_delta = arc->indic_angle_end - arc->indic_angle_start;
int16_t new_delta = end - arc->indic_angle_start;
if(old_delta < 0) old_delta = 360 + old_delta;
if(new_delta < 0) new_delta = 360 + new_delta;
if(LV_ABS(new_delta - old_delta) > 180) lv_obj_invalidate(obj);
else if(new_delta < old_delta) inv_arc_area(obj, end, arc->indic_angle_end, LV_PART_INDICATOR);
else if(old_delta < new_delta) inv_arc_area(obj, arc->indic_angle_end, end, LV_PART_INDICATOR);
arc->indic_angle_end = end;
}
void lv_arc_set_angles(lv_obj_t * obj, uint16_t start, uint16_t end)
{
lv_arc_set_end_angle(obj, end);
lv_arc_set_start_angle(obj, start);
}
void lv_arc_set_bg_start_angle(lv_obj_t * obj, uint16_t start)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_arc_t * arc = (lv_arc_t *)obj;
if(start > 360) start -= 360;
int16_t old_delta = arc->bg_angle_end - arc->bg_angle_start;
int16_t new_delta = arc->bg_angle_end - start;
if(old_delta < 0) old_delta = 360 + old_delta;
if(new_delta < 0) new_delta = 360 + new_delta;
if(LV_ABS(new_delta - old_delta) > 180) lv_obj_invalidate(obj);
else if(new_delta < old_delta) inv_arc_area(obj, arc->bg_angle_start, start, LV_PART_MAIN);
else if(old_delta < new_delta) inv_arc_area(obj, start, arc->bg_angle_start, LV_PART_MAIN);
arc->bg_angle_start = start;
value_update(obj);
}
void lv_arc_set_bg_end_angle(lv_obj_t * obj, uint16_t end)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_arc_t * arc = (lv_arc_t *)obj;
if(end > 360) end -= 360;
int16_t old_delta = arc->bg_angle_end - arc->bg_angle_start;
int16_t new_delta = end - arc->bg_angle_start;
if(old_delta < 0) old_delta = 360 + old_delta;
if(new_delta < 0) new_delta = 360 + new_delta;
if(LV_ABS(new_delta - old_delta) > 180) lv_obj_invalidate(obj);
else if(new_delta < old_delta) inv_arc_area(obj, end, arc->bg_angle_end, LV_PART_MAIN);
else if(old_delta < new_delta) inv_arc_area(obj, arc->bg_angle_end, end, LV_PART_MAIN);
arc->bg_angle_end = end;
value_update(obj);
}
void lv_arc_set_bg_angles(lv_obj_t * obj, uint16_t start, uint16_t end)
{
lv_arc_set_bg_end_angle(obj, end);
lv_arc_set_bg_start_angle(obj, start);
}
void lv_arc_set_rotation(lv_obj_t * obj, uint16_t rotation)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_arc_t * arc = (lv_arc_t *)obj;
arc->rotation = rotation;
lv_obj_invalidate(obj);
}
void lv_arc_set_mode(lv_obj_t * obj, lv_arc_mode_t type)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_arc_t * arc = (lv_arc_t *)obj;
int16_t val = arc->value;
arc->type = type;
arc->value = -1; /** Force set_value handling*/
int16_t bg_midpoint, bg_end = arc->bg_angle_end;
if(arc->bg_angle_end < arc->bg_angle_start) bg_end = arc->bg_angle_end + 360;
switch(arc->type) {
case LV_ARC_MODE_SYMMETRICAL:
bg_midpoint = (arc->bg_angle_start + bg_end) / 2;
lv_arc_set_start_angle(obj, bg_midpoint);
lv_arc_set_end_angle(obj, bg_midpoint);
break;
case LV_ARC_MODE_REVERSE:
lv_arc_set_end_angle(obj, arc->bg_angle_end);
break;
default: /** LV_ARC_TYPE_NORMAL*/
lv_arc_set_start_angle(obj, arc->bg_angle_start);
}
lv_arc_set_value(obj, val);
}
void lv_arc_set_value(lv_obj_t * obj, int16_t value)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_arc_t * arc = (lv_arc_t *)obj;
if(arc->value == value) return;
int16_t new_value;
new_value = value > arc->max_value ? arc->max_value : value;
new_value = new_value < arc->min_value ? arc->min_value : new_value;
if(arc->value == new_value) return;
arc->value = new_value;
value_update(obj);
}
void lv_arc_set_range(lv_obj_t * obj, int16_t min, int16_t max)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_arc_t * arc = (lv_arc_t *)obj;
if(arc->min_value == min && arc->max_value == max) return;
arc->min_value = min;
arc->max_value = max;
if(arc->value < min) {
arc->value = min;
}
if(arc->value > max) {
arc->value = max;
}
value_update(obj); /*value has changed relative to the new range*/
}
void lv_arc_set_change_rate(lv_obj_t * obj, uint16_t rate)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_arc_t * arc = (lv_arc_t *)obj;
arc->chg_rate = rate;
}
/*=====================
* Getter functions
*====================*/
uint16_t lv_arc_get_angle_start(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
return ((lv_arc_t *) obj)->indic_angle_start;
}
uint16_t lv_arc_get_angle_end(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
return ((lv_arc_t *) obj)->indic_angle_end;
}
uint16_t lv_arc_get_bg_angle_start(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
return ((lv_arc_t *) obj)->bg_angle_start;
}
uint16_t lv_arc_get_bg_angle_end(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
return ((lv_arc_t *) obj)->bg_angle_end;
}
int16_t lv_arc_get_value(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
return ((lv_arc_t *) obj)->value;
}
int16_t lv_arc_get_min_value(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
return ((lv_arc_t *) obj)->min_value;
}
int16_t lv_arc_get_max_value(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
return ((lv_arc_t *) obj)->max_value;
}
lv_arc_mode_t lv_arc_get_mode(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
return ((lv_arc_t *) obj)->type;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_arc_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_arc_t * arc = (lv_arc_t *)obj;
/*Initialize the allocated 'ext'*/
arc->rotation = 0;
arc->bg_angle_start = 135;
arc->bg_angle_end = 45;
arc->indic_angle_start = 135;
arc->indic_angle_end = 270;
arc->type = LV_ARC_MODE_NORMAL;
arc->value = VALUE_UNSET;
arc->min_close = 1;
arc->min_value = 0;
arc->max_value = 100;
arc->dragging = false;
arc->chg_rate = 720;
arc->last_tick = lv_tick_get();
arc->last_angle = arc->indic_angle_end;
lv_obj_add_flag(obj, LV_OBJ_FLAG_CLICKABLE);
lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLL_CHAIN);
lv_obj_set_ext_click_area(obj, LV_DPI_DEF / 10);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_arc_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
lv_arc_t * arc = (lv_arc_t *)lv_event_get_target(e);
if(code == LV_EVENT_PRESSING) {
lv_indev_t * indev = lv_indev_get_act();
if(indev == NULL) return;
/*Handle only pointers here*/
lv_indev_type_t indev_type = lv_indev_get_type(indev);
if(indev_type != LV_INDEV_TYPE_POINTER) return;
lv_point_t p;
lv_indev_get_point(indev, &p);
/*Make point relative to the arc's center*/
lv_point_t center;
lv_coord_t r;
get_center(obj, ¢er, &r);
p.x -= center.x;
p.y -= center.y;
/*Enter dragging mode if pressed out of the knob*/
if(arc->dragging == false) {
lv_coord_t indic_width = lv_obj_get_style_arc_width(obj, LV_PART_INDICATOR);
r -= indic_width;
/*Add some more sensitive area if there is no advanced git testing.
* (Advanced hit testing is more precise)*/
if(lv_obj_has_flag(obj, LV_OBJ_FLAG_ADV_HITTEST)) {
r -= indic_width;
} else {
r -= LV_MAX(r / 4, indic_width);
}
if(r < 1) r = 1;
if(p.x * p.x + p.y * p.y > r * r) {
arc->dragging = true;
arc->last_tick = lv_tick_get(); /*Capture timestamp at dragging start*/
}
}
/*It must be in "dragging" mode to turn the arc*/
if(arc->dragging == false) return;
/*No angle can be determined if exactly the middle of the arc is being pressed*/
if(p.x == 0 && p.y == 0) return;
/*Calculate the angle of the pressed point*/
int16_t angle;
int16_t bg_end = arc->bg_angle_end;
if(arc->bg_angle_end < arc->bg_angle_start) {
bg_end = arc->bg_angle_end + 360;
}
angle = lv_atan2(p.y, p.x);
angle -= arc->rotation;
angle -= arc->bg_angle_start; /*Make the angle relative to the start angle*/
if(angle < 0) angle += 360;
int16_t deg_range = bg_end - arc->bg_angle_start;
int16_t last_angle_rel = arc->last_angle - arc->bg_angle_start;
int16_t delta_angle = angle - last_angle_rel;
/*Do not allow big jumps.
*It's mainly to avoid jumping to the opposite end if the "dead" range between min. and max. is crossed.
*Check which end was closer on the last valid press (arc->min_close) and prefer that end*/
if(LV_ABS(delta_angle) > 280) {
if(arc->min_close) angle = 0;
else angle = deg_range;
}
else {
if(angle < deg_range / 2)arc->min_close = 1;
else arc->min_close = 0;
}
/*Calculate the slew rate limited angle based on change rate (degrees/sec)*/
delta_angle = angle - last_angle_rel;
uint32_t delta_tick = lv_tick_elaps(arc->last_tick);
int16_t delta_angle_max = (arc->chg_rate * delta_tick) / 1000;
if(delta_angle > delta_angle_max) {
delta_angle = delta_angle_max;
}
else if(delta_angle < -delta_angle_max) {
delta_angle = -delta_angle_max;
}
angle = last_angle_rel + delta_angle; /*Apply the limited angle change*/
/*Rounding for symmetry*/
int32_t round = ((bg_end - arc->bg_angle_start) * 8) / (arc->max_value - arc->min_value);
round = (round + 4) >> 4;
angle += round;
angle += arc->bg_angle_start; /*Make the angle absolute again*/
/*Set the new value*/
int16_t old_value = arc->value;
int16_t new_value = lv_map(angle, arc->bg_angle_start, bg_end, arc->min_value, arc->max_value);
if(new_value != lv_arc_get_value(obj)) {
arc->last_tick = lv_tick_get(); /*Cache timestamp for the next iteration*/
lv_arc_set_value(obj, new_value); /*set_value caches the last_angle for the next iteration*/
if(new_value != old_value) {
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL);
if(res != LV_RES_OK) return;
}
}
/*Don't let the elapsed time become too big while sitting on an end point*/
if(new_value == arc->min_value || new_value == arc->max_value) {
arc->last_tick = lv_tick_get(); /*Cache timestamp for the next iteration*/
}
}
else if(code == LV_EVENT_RELEASED || code == LV_EVENT_PRESS_LOST) {
arc->dragging = false;
/*Leave edit mode if released. (No need to wait for LONG_PRESS)*/
lv_group_t * g = lv_obj_get_group(obj);
bool editing = lv_group_get_editing(g);
lv_indev_type_t indev_type = lv_indev_get_type(lv_indev_get_act());
if(indev_type == LV_INDEV_TYPE_ENCODER) {
if(editing) lv_group_set_editing(g, false);
}
}
else if(code == LV_EVENT_KEY) {
char c = *((char *)lv_event_get_param(e));
int16_t old_value = arc->value;
if(c == LV_KEY_RIGHT || c == LV_KEY_UP) {
lv_arc_set_value(obj, lv_arc_get_value(obj) + 1);
}
else if(c == LV_KEY_LEFT || c == LV_KEY_DOWN) {
lv_arc_set_value(obj, lv_arc_get_value(obj) - 1);
}
if(old_value != arc->value) {
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL);
if(res != LV_RES_OK) return;
}
}
else if(code == LV_EVENT_HIT_TEST) {
lv_hit_test_info_t * info = lv_event_get_param(e);;
lv_point_t p;
lv_coord_t r;
get_center(obj, &p, &r);
lv_coord_t ext_click_area = 0;
if(obj->spec_attr) ext_click_area = obj->spec_attr->ext_click_pad;
lv_coord_t w = lv_obj_get_style_arc_width(obj, LV_PART_MAIN);
r -= w + ext_click_area;
lv_area_t a;
/*Invalid if clicked inside*/
lv_area_set(&a, p.x - r, p.y - r, p.x + r, p.y + r);
if(_lv_area_is_point_on(&a, info->point, LV_RADIUS_CIRCLE)) {
info->res = false;
return;
}
/*Valid if no clicked outside*/
lv_area_increase(&a, w + ext_click_area * 2, w + ext_click_area * 2);
info->res = _lv_area_is_point_on(&a, info->point, LV_RADIUS_CIRCLE);
}
else if(code == LV_EVENT_REFR_EXT_DRAW_SIZE) {
lv_coord_t bg_left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t bg_right = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
lv_coord_t bg_top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_coord_t bg_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
lv_coord_t bg_pad = LV_MAX4(bg_left, bg_right, bg_top, bg_bottom);
lv_coord_t knob_left = lv_obj_get_style_pad_left(obj, LV_PART_KNOB);
lv_coord_t knob_right = lv_obj_get_style_pad_right(obj, LV_PART_KNOB);
lv_coord_t knob_top = lv_obj_get_style_pad_top(obj, LV_PART_KNOB);
lv_coord_t knob_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_KNOB);
lv_coord_t knob_pad = LV_MAX4(knob_left, knob_right, knob_top, knob_bottom) + 2;
lv_coord_t * s = lv_event_get_param(e);
*s = LV_MAX(*s, knob_pad - bg_pad);
}
else if(code == LV_EVENT_DRAW_MAIN) {
lv_arc_draw(e);
}
}
static void lv_arc_draw(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_arc_t * arc = (lv_arc_t *)obj;
const lv_area_t * clip_area = lv_event_get_param(e);
lv_point_t center;
lv_coord_t arc_r;
get_center(obj, ¢er, &arc_r);
lv_obj_draw_part_dsc_t part_draw_dsc;
lv_obj_draw_dsc_init(&part_draw_dsc, clip_area);
/*Draw the background arc*/
lv_draw_arc_dsc_t arc_dsc;
if(arc_r > 0) {
lv_draw_arc_dsc_init(&arc_dsc);
lv_obj_init_draw_arc_dsc(obj, LV_PART_MAIN, &arc_dsc);
part_draw_dsc.part = LV_PART_MAIN;
part_draw_dsc.class_p = MY_CLASS;
part_draw_dsc.type = LV_ARC_DRAW_PART_BACKGROUND;
part_draw_dsc.p1 = ¢er;
part_draw_dsc.radius = arc_r;
part_draw_dsc.arc_dsc = &arc_dsc;
lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_draw_dsc);
lv_draw_arc(center.x, center.y, part_draw_dsc.radius, arc->bg_angle_start + arc->rotation,
arc->bg_angle_end + arc->rotation, clip_area,
&arc_dsc);
lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_draw_dsc);
}
/*make the indicator arc smaller or larger according to its greatest padding value*/
lv_coord_t left_indic = lv_obj_get_style_pad_left(obj, LV_PART_INDICATOR);
lv_coord_t right_indic = lv_obj_get_style_pad_right(obj, LV_PART_INDICATOR);
lv_coord_t top_indic = lv_obj_get_style_pad_top(obj, LV_PART_INDICATOR);
lv_coord_t bottom_indic = lv_obj_get_style_pad_bottom(obj, LV_PART_INDICATOR);
lv_coord_t indic_r = arc_r - LV_MAX4(left_indic, right_indic, top_indic, bottom_indic);
if(indic_r > 0) {
lv_draw_arc_dsc_init(&arc_dsc);
lv_obj_init_draw_arc_dsc(obj, LV_PART_INDICATOR, &arc_dsc);
part_draw_dsc.part = LV_PART_INDICATOR;
part_draw_dsc.class_p = MY_CLASS;
part_draw_dsc.type = LV_ARC_DRAW_PART_FOREGROUND;
part_draw_dsc.p1 = ¢er;
part_draw_dsc.radius = indic_r;
part_draw_dsc.arc_dsc = &arc_dsc;
lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_draw_dsc);
if(arc_dsc.width > part_draw_dsc.radius) arc_dsc.width = part_draw_dsc.radius;
lv_draw_arc(center.x, center.y, part_draw_dsc.radius, arc->indic_angle_start + arc->rotation,
arc->indic_angle_end + arc->rotation, clip_area,
&arc_dsc);
lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_draw_dsc);
}
lv_area_t knob_area;
get_knob_area(obj, ¢er, arc_r, &knob_area);
lv_draw_rect_dsc_t knob_rect_dsc;
lv_draw_rect_dsc_init(&knob_rect_dsc);
lv_obj_init_draw_rect_dsc(obj, LV_PART_KNOB, &knob_rect_dsc);
part_draw_dsc.part = LV_PART_KNOB;
part_draw_dsc.class_p = MY_CLASS;
part_draw_dsc.type = LV_ARC_DRAW_PART_KNOB;
part_draw_dsc.draw_area = &knob_area;
part_draw_dsc.rect_dsc = &knob_rect_dsc;
lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_draw_dsc);
lv_draw_rect(&knob_area, clip_area, &knob_rect_dsc);
lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_draw_dsc);
}
static void inv_arc_area(lv_obj_t * obj, uint16_t start_angle, uint16_t end_angle, lv_part_t part)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_arc_t * arc = (lv_arc_t *)obj;
if(start_angle == end_angle) return;
if(start_angle > 360) start_angle -= 360;
if(end_angle > 360) end_angle -= 360;
/*Skip this complicated invalidation if the arc is not visible*/
if(lv_obj_is_visible(obj) == false) return;
lv_coord_t left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t right = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
lv_coord_t top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_coord_t bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
lv_coord_t rout = (LV_MIN(lv_obj_get_width(obj) - left - right, lv_obj_get_height(obj) - top - bottom)) / 2;
lv_coord_t x = obj->coords.x1 + rout + left;
lv_coord_t y = obj->coords.y1 + rout + top;
lv_coord_t w = lv_obj_get_style_arc_width(obj, part);
lv_coord_t rounded = lv_obj_get_style_arc_rounded(obj, part);
if(part == LV_PART_INDICATOR) {
lv_coord_t knob_extra_size = lv_obj_calculate_ext_draw_size(obj, LV_PART_KNOB);
lv_coord_t knob_left = lv_obj_get_style_pad_left(obj, LV_PART_KNOB);
lv_coord_t knob_right = lv_obj_get_style_pad_right(obj, LV_PART_KNOB);
lv_coord_t knob_top = lv_obj_get_style_pad_top(obj, LV_PART_KNOB);
lv_coord_t knob_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_KNOB);
knob_extra_size += LV_MAX4(knob_left, knob_right, knob_top, knob_bottom);
w += knob_extra_size * 2 + 2;
rout += knob_extra_size + 2;
}
start_angle += arc->rotation;
end_angle += arc->rotation;
if(start_angle > 360) start_angle -= 360;
if(end_angle > 360) end_angle -= 360;
lv_area_t inv_area;
lv_draw_arc_get_area(x, y, rout, start_angle, end_angle, w, rounded, &inv_area);
lv_obj_invalidate_area(obj, &inv_area);
}
static void get_center(lv_obj_t * obj, lv_point_t * center, lv_coord_t * arc_r)
{
lv_coord_t left_bg = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t right_bg = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
lv_coord_t top_bg = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_coord_t bottom_bg = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
lv_coord_t r = (LV_MIN(lv_obj_get_width(obj) - left_bg - right_bg,
lv_obj_get_height(obj) - top_bg - bottom_bg)) / 2;
*arc_r = r;
center->x = obj->coords.x1 + r + left_bg;
center->y = obj->coords.y1 + r + top_bg;
lv_coord_t indic_width = lv_obj_get_style_arc_width(obj, LV_PART_INDICATOR);
r -= indic_width;
}
static void get_knob_area(lv_obj_t * obj, const lv_point_t * center, lv_coord_t r, lv_area_t * knob_area)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_arc_t * arc = (lv_arc_t *)obj;
lv_coord_t indic_width = lv_obj_get_style_arc_width(obj, LV_PART_INDICATOR);
lv_coord_t indic_width_half = indic_width / 2;
r -= indic_width_half;
uint16_t angle = arc->rotation;
if(arc->type == LV_ARC_MODE_NORMAL) {
angle += arc->indic_angle_end;
}
else if(arc->type == LV_ARC_MODE_REVERSE) {
angle += arc->indic_angle_start;
}
else if(arc->type == LV_ARC_MODE_SYMMETRICAL) {
int32_t range_midpoint = (int32_t)(arc->min_value + arc->max_value) / 2;
if(arc->value < range_midpoint) angle += arc->indic_angle_start;
else angle += arc->indic_angle_end;
}
lv_coord_t knob_x = (r * lv_trigo_sin(angle + 90)) >> LV_TRIGO_SHIFT;
lv_coord_t knob_y = (r * lv_trigo_sin(angle)) >> LV_TRIGO_SHIFT;
lv_coord_t left_knob = lv_obj_get_style_pad_left(obj, LV_PART_KNOB);
lv_coord_t right_knob = lv_obj_get_style_pad_right(obj, LV_PART_KNOB);
lv_coord_t top_knob = lv_obj_get_style_pad_top(obj, LV_PART_KNOB);
lv_coord_t bottom_knob = lv_obj_get_style_pad_bottom(obj, LV_PART_KNOB);
knob_area->x1 = center->x + knob_x - left_knob - indic_width_half;
knob_area->x2 = center->x + knob_x + right_knob + indic_width_half;
knob_area->y1 = center->y + knob_y - top_knob - indic_width_half;
knob_area->y2 = center->y + knob_y + bottom_knob + indic_width_half;
}
/**
* Used internally to update arc angles after a value change
* @param arc pointer to an arc object
*/
static void value_update(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_arc_t * arc = (lv_arc_t *)obj;
/*If the value is still not set to any value do not update*/
if(arc->value == VALUE_UNSET) return;
int16_t bg_midpoint, range_midpoint, bg_end = arc->bg_angle_end;
if(arc->bg_angle_end < arc->bg_angle_start) bg_end = arc->bg_angle_end + 360;
int16_t angle;
switch(arc->type) {
case LV_ARC_MODE_SYMMETRICAL:
bg_midpoint = (arc->bg_angle_start + bg_end) / 2;
range_midpoint = (int32_t)(arc->min_value + arc->max_value) / 2;
if(arc->value < range_midpoint) {
angle = lv_map(arc->value, arc->min_value, range_midpoint, arc->bg_angle_start, bg_midpoint);
lv_arc_set_start_angle(obj, angle);
lv_arc_set_end_angle(obj, bg_midpoint);
}
else {
angle = lv_map(arc->value, range_midpoint, arc->max_value, bg_midpoint, bg_end);
lv_arc_set_start_angle(obj, bg_midpoint);
lv_arc_set_end_angle(obj, angle);
}
break;
case LV_ARC_MODE_REVERSE:
angle = lv_map(arc->value, arc->min_value, arc->max_value, arc->bg_angle_start, bg_end);
lv_arc_set_angles(obj, angle, arc->bg_angle_end);
break;
case LV_ARC_MODE_NORMAL:
angle = lv_map(arc->value, arc->min_value, arc->max_value, arc->bg_angle_start, bg_end);
lv_arc_set_angles(obj, arc->bg_angle_start, angle);
break;
default:
LV_LOG_WARN("Invalid mode: %d", arc->type);
return;
}
arc->last_angle = angle; /*Cache angle for slew rate limiting*/
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_arc.c | C | apache-2.0 | 26,015 |
/**
* @file lv_arc.h
*
*/
#ifndef LV_ARC_H
#define LV_ARC_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_ARC != 0
#include "../core/lv_obj.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
enum {
LV_ARC_MODE_NORMAL,
LV_ARC_MODE_SYMMETRICAL,
LV_ARC_MODE_REVERSE
};
typedef uint8_t lv_arc_mode_t;
typedef struct {
lv_obj_t obj;
uint16_t rotation;
uint16_t indic_angle_start;
uint16_t indic_angle_end;
uint16_t bg_angle_start;
uint16_t bg_angle_end;
int16_t value; /*Current value of the arc*/
int16_t min_value; /*Minimum value of the arc*/
int16_t max_value; /*Maximum value of the arc*/
uint16_t dragging : 1;
uint16_t type : 2;
uint16_t min_close : 1; /*1: the last pressed angle was closer to minimum end*/
uint16_t chg_rate; /*Drag angle rate of change of the arc (degrees/sec)*/
uint32_t last_tick; /*Last dragging event timestamp of the arc*/
int16_t last_angle; /*Last dragging angle of the arc*/
} lv_arc_t;
extern const lv_obj_class_t lv_arc_class;
/**
* `type` field in `lv_obj_draw_part_dsc_t` if `class_p = lv_arc_class`
* Used in `LV_EVENT_DRAW_PART_BEGIN` and `LV_EVENT_DRAW_PART_END`
*/
typedef enum {
LV_ARC_DRAW_PART_BACKGROUND, /**< The background arc*/
LV_ARC_DRAW_PART_FOREGROUND, /**< The foreground arc*/
LV_ARC_DRAW_PART_KNOB, /**< The knob*/
} lv_arc_draw_part_type_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create an arc object
* @param par pointer to an object, it will be the parent of the new arc
* @return pointer to the created arc
*/
lv_obj_t * lv_arc_create(lv_obj_t * parent);
/*======================
* Add/remove functions
*=====================*/
/*=====================
* Setter functions
*====================*/
/**
* Set the start angle of an arc. 0 deg: right, 90 bottom, etc.
* @param arc pointer to an arc object
* @param start the start angle
*/
void lv_arc_set_start_angle(lv_obj_t * arc, uint16_t start);
/**
* Set the end angle of an arc. 0 deg: right, 90 bottom, etc.
* @param arc pointer to an arc object
* @param end the end angle
*/
void lv_arc_set_end_angle(lv_obj_t * arc, uint16_t end);
/**
* Set the start and end angles
* @param arc pointer to an arc object
* @param start the start angle
* @param end the end angle
*/
void lv_arc_set_angles(lv_obj_t * arc, uint16_t start, uint16_t end);
/**
* Set the start angle of an arc background. 0 deg: right, 90 bottom, etc.
* @param arc pointer to an arc object
* @param start the start angle
*/
void lv_arc_set_bg_start_angle(lv_obj_t * arc, uint16_t start);
/**
* Set the start angle of an arc background. 0 deg: right, 90 bottom etc.
* @param arc pointer to an arc object
* @param end the end angle
*/
void lv_arc_set_bg_end_angle(lv_obj_t * arc, uint16_t end);
/**
* Set the start and end angles of the arc background
* @param arc pointer to an arc object
* @param start the start angle
* @param end the end angle
*/
void lv_arc_set_bg_angles(lv_obj_t * arc, uint16_t start, uint16_t end);
/**
* Set the rotation for the whole arc
* @param arc pointer to an arc object
* @param rotation rotation angle
*/
void lv_arc_set_rotation(lv_obj_t * arc, uint16_t rotation);
/**
* Set the type of arc.
* @param arc pointer to arc object
* @param mode arc's mode
*/
void lv_arc_set_mode(lv_obj_t * arc, lv_arc_mode_t type);
/**
* Set a new value on the arc
* @param arc pointer to an arc object
* @param value new value
*/
void lv_arc_set_value(lv_obj_t * arc, int16_t value);
/**
* Set minimum and the maximum values of an arc
* @param arc pointer to the arc object
* @param min minimum value
* @param max maximum value
*/
void lv_arc_set_range(lv_obj_t * arc, int16_t min, int16_t max);
/**
* Set a change rate to limit the speed how fast the arc should reach the pressed point.
* @param arc pointer to an arc object
* @param rate the change rate
*/
void lv_arc_set_change_rate(lv_obj_t * arc, uint16_t rate);
/*=====================
* Getter functions
*====================*/
/**
* Get the start angle of an arc.
* @param arc pointer to an arc object
* @return the start angle [0..360]
*/
uint16_t lv_arc_get_angle_start(lv_obj_t * obj);
/**
* Get the end angle of an arc.
* @param arc pointer to an arc object
* @return the end angle [0..360]
*/
uint16_t lv_arc_get_angle_end(lv_obj_t * obj);
/**
* Get the start angle of an arc background.
* @param arc pointer to an arc object
* @return the start angle [0..360]
*/
uint16_t lv_arc_get_bg_angle_start(lv_obj_t * obj);
/**
* Get the end angle of an arc background.
* @param arc pointer to an arc object
* @return the end angle [0..360]
*/
uint16_t lv_arc_get_bg_angle_end(lv_obj_t * obj);
/**
* Get the value of an arc
* @param arc pointer to an arc object
* @return the value of the arc
*/
int16_t lv_arc_get_value(const lv_obj_t * obj);
/**
* Get the minimum value of an arc
* @param arc pointer to an arc object
* @return the minimum value of the arc
*/
int16_t lv_arc_get_min_value(const lv_obj_t * obj);
/**
* Get the maximum value of an arc
* @param arc pointer to an arc object
* @return the maximum value of the arc
*/
int16_t lv_arc_get_max_value(const lv_obj_t * obj);
/**
* Get whether the arc is type or not.
* @param arc pointer to an arc object
* @return arc's mode
*/
lv_arc_mode_t lv_arc_get_mode(const lv_obj_t * obj);
/*=====================
* Other functions
*====================*/
/**********************
* MACROS
**********************/
#endif /*LV_USE_ARC*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_ARC_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_arc.h | C | apache-2.0 | 6,036 |
/**
* @file lv_bar.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_bar.h"
#if LV_USE_BAR != 0
#include "../misc/lv_assert.h"
#include "../draw/lv_draw.h"
#include "../misc/lv_anim.h"
#include "../misc/lv_math.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_bar_class
/** hor. pad and ver. pad cannot make the indicator smaller than this [px]*/
#define LV_BAR_SIZE_MIN 4
#define LV_BAR_IS_ANIMATING(anim_struct) (((anim_struct).anim_state) != LV_BAR_ANIM_STATE_INV)
#define LV_BAR_GET_ANIM_VALUE(orig_value, anim_struct) (LV_BAR_IS_ANIMATING(anim_struct) ? ((anim_struct).anim_end) : (orig_value))
/** Bar animation start value. (Not the real value of the Bar just indicates process animation)*/
#define LV_BAR_ANIM_STATE_START 0
/** Bar animation end value. (Not the real value of the Bar just indicates process animation)*/
#define LV_BAR_ANIM_STATE_END 256
/** Mark no animation is in progress*/
#define LV_BAR_ANIM_STATE_INV -1
/** log2(LV_BAR_ANIM_STATE_END) used to normalize data*/
#define LV_BAR_ANIM_STATE_NORM 8
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_bar_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_bar_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_bar_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void draw_indic(lv_event_t * e);
static void lv_bar_set_value_with_anim(lv_obj_t * obj, int32_t new_value, int32_t * value_ptr,
_lv_bar_anim_t * anim_info, lv_anim_enable_t en);
static void lv_bar_init_anim(lv_obj_t * bar, _lv_bar_anim_t * bar_anim);
static void lv_bar_anim(void * bar, int32_t value);
static void lv_bar_anim_ready(lv_anim_t * a);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_bar_class = {
.constructor_cb = lv_bar_constructor,
.destructor_cb = lv_bar_destructor,
.event_cb = lv_bar_event,
.width_def = LV_DPI_DEF * 2,
.height_def = LV_DPI_DEF / 10,
.instance_size = sizeof(lv_bar_t),
.base_class = &lv_obj_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_bar_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*=====================
* Setter functions
*====================*/
void lv_bar_set_value(lv_obj_t * obj, int32_t value, lv_anim_enable_t anim)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_bar_t * bar = (lv_bar_t *)obj;
if(bar->cur_value == value) return;
value = LV_CLAMP(bar->min_value, value, bar->max_value);
value = value < bar->start_value ? bar->start_value : value; /*Can't be smaller than the left value*/
if(bar->cur_value == value) return;
lv_bar_set_value_with_anim(obj, value, &bar->cur_value, &bar->cur_value_anim, anim);
}
void lv_bar_set_start_value(lv_obj_t * obj, int32_t value, lv_anim_enable_t anim)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_bar_t * bar = (lv_bar_t *)obj;
value = LV_CLAMP(bar->min_value, value, bar->max_value);
value = value > bar->cur_value ? bar->cur_value : value; /*Can't be greater than the right value*/
if(bar->start_value == value) return;
lv_bar_set_value_with_anim(obj, value, &bar->start_value, &bar->start_value_anim, anim);
}
void lv_bar_set_range(lv_obj_t * obj, int32_t min, int32_t max)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_bar_t * bar = (lv_bar_t *)obj;
if(bar->min_value == min && bar->max_value == max) return;
bar->max_value = max;
bar->min_value = min;
if(lv_bar_get_mode(obj) != LV_BAR_MODE_RANGE)
bar->start_value = min;
if(bar->cur_value > max) {
bar->cur_value = max;
lv_bar_set_value(obj, bar->cur_value, false);
}
if(bar->cur_value < min) {
bar->cur_value = min;
lv_bar_set_value(obj, bar->cur_value, false);
}
lv_obj_invalidate(obj);
}
void lv_bar_set_mode(lv_obj_t * obj, lv_bar_mode_t mode)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_bar_t * bar = (lv_bar_t *)obj;
bar->mode = mode;
if(bar->mode != LV_BAR_MODE_RANGE) {
bar->start_value = bar->min_value;
}
lv_obj_invalidate(obj);
}
/*=====================
* Getter functions
*====================*/
int32_t lv_bar_get_value(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_bar_t * bar = (lv_bar_t *)obj;
return LV_BAR_GET_ANIM_VALUE(bar->cur_value, bar->cur_value_anim);
}
int32_t lv_bar_get_start_value(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_bar_t * bar = (lv_bar_t *)obj;
if(bar->mode != LV_BAR_MODE_RANGE) return bar->min_value;
return LV_BAR_GET_ANIM_VALUE(bar->start_value, bar->start_value_anim);
}
int32_t lv_bar_get_min_value(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_bar_t * bar = (lv_bar_t *)obj;
return bar->min_value;
}
int32_t lv_bar_get_max_value(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_bar_t * bar = (lv_bar_t *)obj;
return bar->max_value;
}
lv_bar_mode_t lv_bar_get_mode(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_bar_t * bar = (lv_bar_t *)obj;
return bar->mode;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_bar_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_bar_t * bar = (lv_bar_t *)obj;
bar->min_value = 0;
bar->max_value = 100;
bar->start_value = 0;
bar->cur_value = 0;
bar->mode = LV_BAR_MODE_NORMAL;
lv_bar_init_anim(obj, &bar->cur_value_anim);
lv_bar_init_anim(obj, &bar->start_value_anim);
lv_obj_clear_flag(obj, LV_OBJ_FLAG_CHECKABLE);
lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLLABLE);
lv_bar_set_value(obj, 0, LV_ANIM_OFF);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_bar_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_bar_t * bar = (lv_bar_t *)obj;
lv_anim_del(&bar->cur_value_anim, NULL);
lv_anim_del(&bar->start_value_anim, NULL);
}
static void draw_indic(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_bar_t * bar = (lv_bar_t *)obj;
const lv_area_t * clip_area = lv_event_get_param(e);
lv_area_t bar_coords;
lv_obj_get_coords(obj, &bar_coords);
lv_coord_t transf_w = lv_obj_get_style_transform_width(obj, LV_PART_MAIN);
lv_coord_t transf_h = lv_obj_get_style_transform_height(obj, LV_PART_MAIN);
bar_coords.x1 -= transf_w;
bar_coords.x2 += transf_w;
bar_coords.y1 -= transf_h;
bar_coords.y2 += transf_h;
lv_coord_t barw = lv_area_get_width(&bar_coords);
lv_coord_t barh = lv_area_get_height(&bar_coords);
int32_t range = bar->max_value - bar->min_value;
bool hor = barw >= barh ? true : false;
bool sym = false;
if(bar->mode == LV_BAR_MODE_SYMMETRICAL && bar->min_value < 0 && bar->max_value > 0 &&
bar->start_value == bar->min_value) sym = true;
/*Calculate the indicator area*/
lv_coord_t bg_left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t bg_right = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
lv_coord_t bg_top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_coord_t bg_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
/*Respect padding and minimum width/height too*/
lv_area_copy(&bar->indic_area, &bar_coords);
bar->indic_area.x1 += bg_left;
bar->indic_area.x2 -= bg_right;
bar->indic_area.y1 += bg_top;
bar->indic_area.y2 -= bg_bottom;
if(hor && lv_area_get_height(&bar->indic_area) < LV_BAR_SIZE_MIN) {
bar->indic_area.y1 = obj->coords.y1 + (barh / 2) - (LV_BAR_SIZE_MIN / 2);
bar->indic_area.y2 = bar->indic_area.y1 + LV_BAR_SIZE_MIN;
}
else if(!hor && lv_area_get_width(&bar->indic_area) < LV_BAR_SIZE_MIN) {
bar->indic_area.x1 = obj->coords.x1 + (barw / 2) - (LV_BAR_SIZE_MIN / 2);
bar->indic_area.x2 = bar->indic_area.x1 + LV_BAR_SIZE_MIN;
}
lv_coord_t indicw = lv_area_get_width(&bar->indic_area);
lv_coord_t indich = lv_area_get_height(&bar->indic_area);
/*Calculate the indicator length*/
lv_coord_t anim_length = hor ? indicw : indich;
lv_coord_t anim_cur_value_x, anim_start_value_x;
lv_coord_t * axis1, * axis2;
lv_coord_t (*indic_length_calc)(const lv_area_t * area);
if(hor) {
axis1 = &bar->indic_area.x1;
axis2 = &bar->indic_area.x2;
indic_length_calc = lv_area_get_width;
}
else {
axis1 = &bar->indic_area.y1;
axis2 = &bar->indic_area.y2;
indic_length_calc = lv_area_get_height;
}
if(LV_BAR_IS_ANIMATING(bar->start_value_anim)) {
lv_coord_t anim_start_value_start_x =
(int32_t)((int32_t)anim_length * (bar->start_value_anim.anim_start - bar->min_value)) / range;
lv_coord_t anim_start_value_end_x =
(int32_t)((int32_t)anim_length * (bar->start_value_anim.anim_end - bar->min_value)) / range;
anim_start_value_x = (((anim_start_value_end_x - anim_start_value_start_x) * bar->start_value_anim.anim_state) /
LV_BAR_ANIM_STATE_END);
anim_start_value_x += anim_start_value_start_x;
}
else {
anim_start_value_x = (int32_t)((int32_t)anim_length * (bar->start_value - bar->min_value)) / range;
}
if(LV_BAR_IS_ANIMATING(bar->cur_value_anim)) {
lv_coord_t anim_cur_value_start_x =
(int32_t)((int32_t)anim_length * (bar->cur_value_anim.anim_start - bar->min_value)) / range;
lv_coord_t anim_cur_value_end_x =
(int32_t)((int32_t)anim_length * (bar->cur_value_anim.anim_end - bar->min_value)) / range;
anim_cur_value_x = anim_cur_value_start_x + (((anim_cur_value_end_x - anim_cur_value_start_x) *
bar->cur_value_anim.anim_state) /
LV_BAR_ANIM_STATE_END);
}
else {
anim_cur_value_x = (int32_t)((int32_t)anim_length * (bar->cur_value - bar->min_value)) / range;
}
lv_base_dir_t base_dir = lv_obj_get_style_base_dir(obj, LV_PART_MAIN);
if(hor && base_dir == LV_BASE_DIR_RTL) {
/*Swap axes*/
lv_coord_t * tmp;
tmp = axis1;
axis1 = axis2;
axis2 = tmp;
anim_cur_value_x = -anim_cur_value_x;
anim_start_value_x = -anim_start_value_x;
}
/*Set the indicator length*/
if(hor) {
*axis2 = *axis1 + anim_cur_value_x;
*axis1 += anim_start_value_x;
}
else {
*axis1 = *axis2 - anim_cur_value_x + 1;
*axis2 -= anim_start_value_x;
}
if(sym) {
lv_coord_t zero, shift;
shift = (-bar->min_value * anim_length) / range;
if(hor) {
zero = *axis1 + shift;
if(*axis2 > zero)
*axis1 = zero;
else {
*axis1 = *axis2;
*axis2 = zero;
}
}
else {
zero = *axis2 - shift + 1;
if(*axis1 > zero)
*axis2 = zero;
else {
*axis2 = *axis1;
*axis1 = zero;
}
if(*axis2 < *axis1) {
/*swap*/
zero = *axis1;
*axis1 = *axis2;
*axis2 = zero;
}
}
}
/*Do not draw a zero length indicator but at least call the draw part events*/
if(!sym && indic_length_calc(&bar->indic_area) <= 1) {
lv_obj_draw_part_dsc_t part_draw_dsc;
lv_obj_draw_dsc_init(&part_draw_dsc, clip_area);
part_draw_dsc.part = LV_PART_INDICATOR;
part_draw_dsc.class_p = MY_CLASS;
part_draw_dsc.type = LV_BAR_DRAW_PART_INDICATOR;
part_draw_dsc.draw_area = &bar->indic_area;
lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_draw_dsc);
lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_draw_dsc);
return;
}
lv_coord_t bg_radius = lv_obj_get_style_radius(obj, LV_PART_MAIN);
lv_coord_t short_side = LV_MIN(barw, barh);
if(bg_radius > short_side >> 1) bg_radius = short_side >> 1;
lv_area_t indic_area;
lv_area_copy(&indic_area, &bar->indic_area);
lv_draw_rect_dsc_t draw_rect_dsc;
lv_draw_rect_dsc_init(&draw_rect_dsc);
lv_obj_init_draw_rect_dsc(obj, LV_PART_INDICATOR, &draw_rect_dsc);
lv_obj_draw_part_dsc_t part_draw_dsc;
lv_obj_draw_dsc_init(&part_draw_dsc, clip_area);
part_draw_dsc.part = LV_PART_INDICATOR;
part_draw_dsc.class_p = MY_CLASS;
part_draw_dsc.type = LV_BAR_DRAW_PART_INDICATOR;
part_draw_dsc.rect_dsc = &draw_rect_dsc;
part_draw_dsc.draw_area = &bar->indic_area;
lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_draw_dsc);
/*Draw only the shadow if the indicator is long enough.
*The radius of the bg and the indicator can make a strange shape where
*it'd be very difficult to draw shadow.*/
if((hor && lv_area_get_width(&bar->indic_area) > bg_radius * 2) ||
(!hor && lv_area_get_height(&bar->indic_area) > bg_radius * 2)) {
lv_opa_t bg_opa = draw_rect_dsc.bg_opa;
lv_opa_t bg_img_opa = draw_rect_dsc.bg_img_opa;
lv_opa_t border_opa = draw_rect_dsc.border_opa;
draw_rect_dsc.bg_opa = LV_OPA_TRANSP;
draw_rect_dsc.bg_img_opa = LV_OPA_TRANSP;
draw_rect_dsc.border_opa = LV_OPA_TRANSP;
lv_draw_rect(&bar->indic_area, clip_area, &draw_rect_dsc);
draw_rect_dsc.bg_opa = bg_opa;
draw_rect_dsc.bg_img_opa = bg_img_opa;
draw_rect_dsc.border_opa = border_opa;
}
#if LV_DRAW_COMPLEX
lv_draw_mask_radius_param_t mask_bg_param;
lv_area_t bg_mask_area;
bg_mask_area.x1 = obj->coords.x1 + bg_left;
bg_mask_area.x2 = obj->coords.x2 - bg_right;
bg_mask_area.y1 = obj->coords.y1 + bg_top;
bg_mask_area.y2 = obj->coords.y2 - bg_bottom;
lv_draw_mask_radius_init(&mask_bg_param, &bg_mask_area, bg_radius, false);
lv_coord_t mask_bg_id = lv_draw_mask_add(&mask_bg_param, NULL);
#endif
/*Draw_only the background and background image*/
lv_opa_t shadow_opa = draw_rect_dsc.shadow_opa;
lv_opa_t border_opa = draw_rect_dsc.border_opa;
draw_rect_dsc.border_opa = LV_OPA_TRANSP;
draw_rect_dsc.shadow_opa = LV_OPA_TRANSP;
/*Get the max possible indicator area. The gradient should be applied on this*/
lv_area_t mask_indic_max_area;
lv_area_copy(&mask_indic_max_area, &bar_coords);
mask_indic_max_area.x1 += bg_left;
mask_indic_max_area.y1 += bg_top;
mask_indic_max_area.x2 -= bg_right;
mask_indic_max_area.y2 -= bg_bottom;
if(hor && lv_area_get_height(&mask_indic_max_area) < LV_BAR_SIZE_MIN) {
mask_indic_max_area.y1 = obj->coords.y1 + (barh / 2) - (LV_BAR_SIZE_MIN / 2);
mask_indic_max_area.y2 = mask_indic_max_area.y1 + LV_BAR_SIZE_MIN;
}
else if(!hor && lv_area_get_width(&mask_indic_max_area) < LV_BAR_SIZE_MIN) {
mask_indic_max_area.x1 = obj->coords.x1 + (barw / 2) - (LV_BAR_SIZE_MIN / 2);
mask_indic_max_area.x2 = mask_indic_max_area.x1 + LV_BAR_SIZE_MIN;
}
#if LV_DRAW_COMPLEX
/*Create a mask to the current indicator area to see only this part from the whole gradient.*/
lv_draw_mask_radius_param_t mask_indic_param;
lv_draw_mask_radius_init(&mask_indic_param, &bar->indic_area, draw_rect_dsc.radius, false);
int16_t mask_indic_id = lv_draw_mask_add(&mask_indic_param, NULL);
#endif
lv_draw_rect(&mask_indic_max_area, clip_area, &draw_rect_dsc);
draw_rect_dsc.border_opa = border_opa;
draw_rect_dsc.shadow_opa = shadow_opa;
/*Draw the border*/
draw_rect_dsc.bg_opa = LV_OPA_TRANSP;
draw_rect_dsc.bg_img_opa = LV_OPA_TRANSP;
draw_rect_dsc.shadow_opa = LV_OPA_TRANSP;
lv_draw_rect(&bar->indic_area, clip_area, &draw_rect_dsc);
#if LV_DRAW_COMPLEX
lv_draw_mask_free_param(&mask_indic_param);
lv_draw_mask_free_param(&mask_bg_param);
lv_draw_mask_remove_id(mask_indic_id);
lv_draw_mask_remove_id(mask_bg_id);
#endif
lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_draw_dsc);
}
static void lv_bar_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
if(code == LV_EVENT_REFR_EXT_DRAW_SIZE) {
lv_coord_t indic_size;
indic_size = lv_obj_calculate_ext_draw_size(obj, LV_PART_INDICATOR);
/*Bg size is handled by lv_obj*/
lv_coord_t * s = lv_event_get_param(e);
*s = LV_MAX(*s, indic_size);
/*Calculate the indicator area*/
lv_coord_t bg_left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t bg_right = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
lv_coord_t bg_top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_coord_t bg_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
lv_coord_t pad = LV_MIN4(bg_left, bg_right, bg_top, bg_bottom);
if(pad < 0) {
*s = LV_MAX(*s, -pad);
}
}
else if(code == LV_EVENT_PRESSED || code == LV_EVENT_RELEASED) {
lv_bar_t * bar = (lv_bar_t *)obj;
lv_obj_invalidate_area(obj, &bar->indic_area);
}
else if(code == LV_EVENT_DRAW_MAIN) {
draw_indic(e);
}
}
static void lv_bar_anim(void * var, int32_t value)
{
_lv_bar_anim_t * bar_anim = var;
bar_anim->anim_state = value;
lv_obj_invalidate(bar_anim->bar);
}
static void lv_bar_anim_ready(lv_anim_t * a)
{
_lv_bar_anim_t * var = a->var;
lv_obj_t * obj = (lv_obj_t *)var->bar;
lv_bar_t * bar = (lv_bar_t *)obj;
var->anim_state = LV_BAR_ANIM_STATE_INV;
if(var == &bar->cur_value_anim)
bar->cur_value = var->anim_end;
else if(var == &bar->start_value_anim)
bar->start_value = var->anim_end;
lv_obj_invalidate(var->bar);
}
static void lv_bar_set_value_with_anim(lv_obj_t * obj, int32_t new_value, int32_t * value_ptr,
_lv_bar_anim_t * anim_info, lv_anim_enable_t en)
{
if(en == LV_ANIM_OFF) {
*value_ptr = new_value;
lv_obj_invalidate((lv_obj_t *)obj);
}
else {
/*No animation in progress -> simply set the values*/
if(anim_info->anim_state == LV_BAR_ANIM_STATE_INV) {
anim_info->anim_start = *value_ptr;
anim_info->anim_end = new_value;
}
/*Animation in progress. Start from the animation end value*/
else {
anim_info->anim_start = anim_info->anim_end;
anim_info->anim_end = new_value;
}
*value_ptr = new_value;
/*Stop the previous animation if it exists*/
lv_anim_del(anim_info, NULL);
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, anim_info);
lv_anim_set_exec_cb(&a, lv_bar_anim);
lv_anim_set_values(&a, LV_BAR_ANIM_STATE_START, LV_BAR_ANIM_STATE_END);
lv_anim_set_ready_cb(&a, lv_bar_anim_ready);
lv_anim_set_time(&a, lv_obj_get_style_anim_time(obj, LV_PART_MAIN));
lv_anim_start(&a);
}
}
static void lv_bar_init_anim(lv_obj_t * obj, _lv_bar_anim_t * bar_anim)
{
bar_anim->bar = obj;
bar_anim->anim_start = 0;
bar_anim->anim_end = 0;
bar_anim->anim_state = LV_BAR_ANIM_STATE_INV;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_bar.c | C | apache-2.0 | 19,891 |
/**
* @file lv_bar.h
*
*/
#ifndef LV_BAR_H
#define LV_BAR_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_BAR != 0
#include "../core/lv_obj.h"
#include "../misc/lv_anim.h"
#include "lv_btn.h"
#include "lv_label.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
enum {
LV_BAR_MODE_NORMAL,
LV_BAR_MODE_SYMMETRICAL,
LV_BAR_MODE_RANGE
};
typedef uint8_t lv_bar_mode_t;
typedef struct {
lv_obj_t * bar;
int32_t anim_start;
int32_t anim_end;
int32_t anim_state;
} _lv_bar_anim_t;
typedef struct {
lv_obj_t obj;
int32_t cur_value; /**< Current value of the bar*/
int32_t min_value; /**< Minimum value of the bar*/
int32_t max_value; /**< Maximum value of the bar*/
int32_t start_value; /**< Start value of the bar*/
lv_area_t indic_area; /**< Save the indicator area. Might be used by derived types*/
_lv_bar_anim_t cur_value_anim;
_lv_bar_anim_t start_value_anim;
lv_bar_mode_t mode : 2; /**< Type of bar*/
} lv_bar_t;
extern const lv_obj_class_t lv_bar_class;
/**
* `type` field in `lv_obj_draw_part_dsc_t` if `class_p = lv_bar_class`
* Used in `LV_EVENT_DRAW_PART_BEGIN` and `LV_EVENT_DRAW_PART_END`
*/
typedef enum {
LV_BAR_DRAW_PART_INDICATOR, /**< The indicator*/
} lv_bar_draw_part_type_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a bar objects
* @param parent pointer to an object, it will be the parent of the new bar
* @return pointer to the created bar
*/
lv_obj_t * lv_bar_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set a new value on the bar
* @param bar pointer to a bar object
* @param value new value
* @param anim LV_ANIM_ON: set the value with an animation; LV_ANIM_OFF: change the value immediately
*/
void lv_bar_set_value(lv_obj_t * obj, int32_t value, lv_anim_enable_t anim);
/**
* Set a new start value on the bar
* @param obj pointer to a bar object
* @param value new start value
* @param anim LV_ANIM_ON: set the value with an animation; LV_ANIM_OFF: change the value immediately
*/
void lv_bar_set_start_value(lv_obj_t * obj, int32_t start_value, lv_anim_enable_t anim);
/**
* Set minimum and the maximum values of a bar
* @param obj pointer to the bar object
* @param min minimum value
* @param max maximum value
*/
void lv_bar_set_range(lv_obj_t * obj, int32_t min, int32_t max);
/**
* Set the type of bar.
* @param obj pointer to bar object
* @param mode bar type from ::lv_bar_mode_t
*/
void lv_bar_set_mode(lv_obj_t * obj, lv_bar_mode_t mode);
/*=====================
* Getter functions
*====================*/
/**
* Get the value of a bar
* @param obj pointer to a bar object
* @return the value of the bar
*/
int32_t lv_bar_get_value(const lv_obj_t * obj);
/**
* Get the start value of a bar
* @param obj pointer to a bar object
* @return the start value of the bar
*/
int32_t lv_bar_get_start_value(const lv_obj_t * obj);
/**
* Get the minimum value of a bar
* @param obj pointer to a bar object
* @return the minimum value of the bar
*/
int32_t lv_bar_get_min_value(const lv_obj_t * obj);
/**
* Get the maximum value of a bar
* @param obj pointer to a bar object
* @return the maximum value of the bar
*/
int32_t lv_bar_get_max_value(const lv_obj_t * obj);
/**
* Get the type of bar.
* @param obj pointer to bar object
* @return bar type from ::lv_bar_mode_t
*/
lv_bar_mode_t lv_bar_get_mode(lv_obj_t * obj);
/**********************
* MACROS
**********************/
#endif /*LV_USE_BAR*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_BAR_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_bar.h | C | apache-2.0 | 4,012 |
/**
* @file lv_btn.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_btn.h"
#if LV_USE_BTN != 0
#include "../extra/layouts/flex/lv_flex.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_btn_class
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_btn_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_btn_class = {
.constructor_cb = lv_btn_constructor,
.width_def = LV_SIZE_CONTENT,
.height_def = LV_SIZE_CONTENT,
.group_def = LV_OBJ_CLASS_GROUP_DEF_TRUE,
.instance_size = sizeof(lv_btn_t),
.base_class = &lv_obj_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_btn_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_btn_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
LV_TRACE_OBJ_CREATE("finished");
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_btn.c | C | apache-2.0 | 1,526 |
/**
* @file lv_btn.h
*
*/
#ifndef LV_BTN_H
#define LV_BTN_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_BTN != 0
#include "../core/lv_obj.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_obj_t obj;
} lv_btn_t;
extern const lv_obj_class_t lv_btn_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a button object
* @param parent pointer to an object, it will be the parent of the new button
* @return pointer to the created button
*/
lv_obj_t * lv_btn_create(lv_obj_t * parent);
/**********************
* MACROS
**********************/
#endif /*LV_USE_BTN*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_BTN_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_btn.h | C | apache-2.0 | 909 |
/**
* @file lv_btnmatrix.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_btnmatrix.h"
#if LV_USE_BTNMATRIX != 0
#include "../misc/lv_assert.h"
#include "../core/lv_indev.h"
#include "../core/lv_group.h"
#include "../draw/lv_draw.h"
#include "../core/lv_refr.h"
#include "../misc/lv_txt.h"
#include "../misc/lv_txt_ap.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_btnmatrix_class
#define BTN_EXTRA_CLICK_AREA_MAX (LV_DPI_DEF / 10)
#define LV_BTNMATRIX_WIDTH_MASK 0x0007
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_btnmatrix_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_btnmatrix_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_btnmatrix_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void draw_main(lv_event_t * e);
static uint8_t get_button_width(lv_btnmatrix_ctrl_t ctrl_bits);
static bool button_is_hidden(lv_btnmatrix_ctrl_t ctrl_bits);
static bool button_is_checked(lv_btnmatrix_ctrl_t ctrl_bits);
static bool button_is_repeat_disabled(lv_btnmatrix_ctrl_t ctrl_bits);
static bool button_is_inactive(lv_btnmatrix_ctrl_t ctrl_bits);
static bool button_is_click_trig(lv_btnmatrix_ctrl_t ctrl_bits);
static bool button_is_popover(lv_btnmatrix_ctrl_t ctrl_bits);
static bool button_is_checkable(lv_btnmatrix_ctrl_t ctrl_bits);
static bool button_is_recolor(lv_btnmatrix_ctrl_t ctrl_bits);
static bool button_get_checked(lv_btnmatrix_ctrl_t ctrl_bits);
static uint16_t get_button_from_point(lv_obj_t * obj, lv_point_t * p);
static void allocate_btn_areas_and_controls(const lv_obj_t * obj, const char ** map);
static void invalidate_button_area(const lv_obj_t * obj, uint16_t btn_idx);
static void make_one_button_checked(lv_obj_t * obj, uint16_t btn_idx);
static bool has_popovers_in_top_row(lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
static const char * lv_btnmatrix_def_map[] = {"Btn1", "Btn2", "Btn3", "\n", "Btn4", "Btn5", ""};
const lv_obj_class_t lv_btnmatrix_class = {
.constructor_cb = lv_btnmatrix_constructor,
.destructor_cb = lv_btnmatrix_destructor,
.event_cb = lv_btnmatrix_event,
.width_def = LV_DPI_DEF * 2,
.height_def = LV_DPI_DEF,
.instance_size = sizeof(lv_btnmatrix_t),
.editable = LV_OBJ_CLASS_EDITABLE_TRUE,
.group_def = LV_OBJ_CLASS_GROUP_DEF_TRUE,
.base_class = &lv_obj_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_btnmatrix_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*=====================
* Setter functions
*====================*/
void lv_btnmatrix_set_map(lv_obj_t * obj, const char * map[])
{
LV_ASSERT_OBJ(obj, MY_CLASS);
if(map == NULL) return;
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;
/*Analyze the map and create the required number of buttons*/
allocate_btn_areas_and_controls(obj, map);
btnm->map_p = map;
lv_base_dir_t base_dir = lv_obj_get_style_base_dir(obj, LV_PART_MAIN);
/*Set size and positions of the buttons*/
lv_coord_t pleft = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t ptop = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_coord_t prow = lv_obj_get_style_pad_row(obj, LV_PART_MAIN);
lv_coord_t pcol = lv_obj_get_style_pad_column(obj, LV_PART_MAIN);
lv_coord_t max_w = lv_obj_get_content_width(obj);
lv_coord_t max_h = lv_obj_get_content_height(obj);
/*Calculate the position of each row*/
lv_coord_t max_h_no_gap = max_h - (prow * (btnm->row_cnt - 1));
/*Count the units and the buttons in a line
*(A button can be 1,2,3... unit wide)*/
uint32_t txt_tot_i = 0; /*Act. index in the str map*/
uint32_t btn_tot_i = 0; /*Act. index of button areas*/
const char ** map_row = map;
/*Count the units and the buttons in a line*/
uint32_t row;
for(row = 0; row < btnm->row_cnt; row++) {
uint16_t unit_cnt = 0; /*Number of units in a row*/
uint16_t btn_cnt = 0; /*Number of buttons in a row*/
/*Count the buttons and units in this row*/
while(map_row[btn_cnt] && strcmp(map_row[btn_cnt], "\n") != 0 && map_row[btn_cnt][0] != '\0') {
unit_cnt += get_button_width(btnm->ctrl_bits[btn_tot_i + btn_cnt]);
btn_cnt++;
}
/*Only deal with the non empty lines*/
if(btn_cnt == 0) {
map_row = &map_row[btn_cnt + 1]; /*Set the map to the next row*/
continue;
}
lv_coord_t row_y1 = ptop + (max_h_no_gap * row) / btnm->row_cnt + row * prow;
lv_coord_t row_y2 = ptop + (max_h_no_gap * (row + 1)) / btnm->row_cnt + row * prow - 1;
/*Set the button size and positions*/
lv_coord_t max_w_no_gap = max_w - (pcol * (btn_cnt - 1));
if(max_w_no_gap < 0) max_w_no_gap = 0;
uint32_t row_unit_cnt = 0; /*The current unit position in the row*/
uint32_t btn;
for(btn = 0; btn < btn_cnt; btn++, btn_tot_i++, txt_tot_i++) {
uint32_t btn_u = get_button_width(btnm->ctrl_bits[btn_tot_i]);
lv_coord_t btn_x1 = (max_w_no_gap * row_unit_cnt) / unit_cnt + btn * pcol;
lv_coord_t btn_x2 = (max_w_no_gap * (row_unit_cnt + btn_u)) / unit_cnt + btn * pcol - 1;
/*If RTL start from the right*/
if(base_dir == LV_BASE_DIR_RTL) {
lv_coord_t tmp = btn_x1;
btn_x1 = btn_x2;
btn_x2 = tmp;
btn_x1 = max_w - btn_x1;
btn_x2 = max_w - btn_x2;
}
btn_x1 += pleft;
btn_x2 += pleft;
lv_area_set(&btnm->button_areas[btn_tot_i], btn_x1, row_y1, btn_x2, row_y2);
row_unit_cnt += btn_u;
}
map_row = &map_row[btn_cnt + 1]; /*Set the map to the next line*/
}
/*Popovers in the top row will draw outside the widget and the extended draw size depends on
*the row height which may have changed when setting the new map*/
lv_obj_refresh_ext_draw_size(obj);
lv_obj_invalidate(obj);
}
void lv_btnmatrix_set_ctrl_map(lv_obj_t * obj, const lv_btnmatrix_ctrl_t ctrl_map[])
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;
lv_memcpy(btnm->ctrl_bits, ctrl_map, sizeof(lv_btnmatrix_ctrl_t) * btnm->btn_cnt);
lv_btnmatrix_set_map(obj, btnm->map_p);
}
void lv_btnmatrix_set_selected_btn(lv_obj_t * obj, uint16_t btn_id)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;
if(btn_id >= btnm->btn_cnt && btn_id != LV_BTNMATRIX_BTN_NONE) return;
invalidate_button_area(obj, btnm->btn_id_sel);
btnm->btn_id_sel = btn_id;
invalidate_button_area(obj, btn_id);
}
void lv_btnmatrix_set_btn_ctrl(lv_obj_t * obj, uint16_t btn_id, lv_btnmatrix_ctrl_t ctrl)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;;
if(btn_id >= btnm->btn_cnt) return;
if(btnm->one_check && (ctrl & LV_BTNMATRIX_CTRL_CHECKED)) {
lv_btnmatrix_clear_btn_ctrl_all(obj, LV_BTNMATRIX_CTRL_CHECKED);
}
btnm->ctrl_bits[btn_id] |= ctrl;
invalidate_button_area(obj, btn_id);
if (ctrl & LV_BTNMATRIX_CTRL_POPOVER) {
lv_obj_refresh_ext_draw_size(obj);
}
}
void lv_btnmatrix_clear_btn_ctrl(lv_obj_t * obj, uint16_t btn_id, lv_btnmatrix_ctrl_t ctrl)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;;
if(btn_id >= btnm->btn_cnt) return;
btnm->ctrl_bits[btn_id] &= (~ctrl);
invalidate_button_area(obj, btn_id);
if (ctrl & LV_BTNMATRIX_CTRL_POPOVER) {
lv_obj_refresh_ext_draw_size(obj);
}
}
void lv_btnmatrix_set_btn_ctrl_all(lv_obj_t * obj, lv_btnmatrix_ctrl_t ctrl)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;;
uint16_t i;
for(i = 0; i < btnm->btn_cnt; i++) {
lv_btnmatrix_set_btn_ctrl(obj, i, ctrl);
}
}
void lv_btnmatrix_clear_btn_ctrl_all(lv_obj_t * obj, lv_btnmatrix_ctrl_t ctrl)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;;
uint16_t i;
for(i = 0; i < btnm->btn_cnt; i++) {
lv_btnmatrix_clear_btn_ctrl(obj, i, ctrl);
}
}
void lv_btnmatrix_set_btn_width(lv_obj_t * obj, uint16_t btn_id, uint8_t width)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;;
if(btn_id >= btnm->btn_cnt) return;
btnm->ctrl_bits[btn_id] &= (~LV_BTNMATRIX_WIDTH_MASK);
btnm->ctrl_bits[btn_id] |= (LV_BTNMATRIX_WIDTH_MASK & width);
lv_btnmatrix_set_map(obj, btnm->map_p);
}
void lv_btnmatrix_set_one_checked(lv_obj_t * obj, bool en)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;;
btnm->one_check = en;
/*If more than one button is toggled only the first one should be*/
make_one_button_checked(obj, 0);
}
/*=====================
* Getter functions
*====================*/
const char ** lv_btnmatrix_get_map(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;;
return btnm->map_p;
}
uint16_t lv_btnmatrix_get_selected_btn(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;;
return btnm->btn_id_sel;
}
const char * lv_btnmatrix_get_btn_text(const lv_obj_t * obj, uint16_t btn_id)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
if(btn_id == LV_BTNMATRIX_BTN_NONE) return NULL;
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;
if(btn_id > btnm->btn_cnt) return NULL;
uint16_t txt_i = 0;
uint16_t btn_i = 0;
/*Search the text of btnm->btn_pr the buttons text in the map
*Skip "\n"-s*/
while(btn_i != btn_id) {
btn_i++;
txt_i++;
if(strcmp(btnm->map_p[txt_i], "\n") == 0) txt_i++;
}
if(btn_i == btnm->btn_cnt) return NULL;
return btnm->map_p[txt_i];
}
bool lv_btnmatrix_has_btn_ctrl(lv_obj_t * obj, uint16_t btn_id, lv_btnmatrix_ctrl_t ctrl)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;;
if(btn_id >= btnm->btn_cnt) return false;
return ((btnm->ctrl_bits[btn_id] & ctrl) == ctrl) ? true : false;
}
bool lv_btnmatrix_get_one_checked(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;;
return btnm->one_check;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_btnmatrix_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;
btnm->btn_cnt = 0;
btnm->row_cnt = 0;
btnm->btn_id_sel = LV_BTNMATRIX_BTN_NONE;
btnm->button_areas = NULL;
btnm->ctrl_bits = NULL;
btnm->map_p = NULL;
btnm->one_check = 0;
lv_btnmatrix_set_map(obj, lv_btnmatrix_def_map);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_btnmatrix_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_TRACE_OBJ_CREATE("begin");
LV_UNUSED(class_p);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;
lv_mem_free(btnm->button_areas);
lv_mem_free(btnm->ctrl_bits);
btnm->button_areas = NULL;
btnm->ctrl_bits = NULL;
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_btnmatrix_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;
lv_point_t p;
if(code == LV_EVENT_REFR_EXT_DRAW_SIZE) {
lv_coord_t * s = lv_event_get_param(e);
if (has_popovers_in_top_row(obj)) {
/*reserve one row worth of extra space to account for popovers in the top row*/
*s = btnm->row_cnt > 0 ? lv_obj_get_content_height(obj) / btnm->row_cnt : 0;
} else {
*s = 0;
}
}
if(code == LV_EVENT_STYLE_CHANGED) {
lv_btnmatrix_set_map(obj, btnm->map_p);
}
else if(code == LV_EVENT_SIZE_CHANGED) {
lv_btnmatrix_set_map(obj, btnm->map_p);
}
else if(code == LV_EVENT_PRESSED) {
void * param = lv_event_get_param(e);
invalidate_button_area(obj, btnm->btn_id_sel);
lv_indev_type_t indev_type = lv_indev_get_type(lv_indev_get_act());
if(indev_type == LV_INDEV_TYPE_POINTER || indev_type == LV_INDEV_TYPE_BUTTON) {
uint16_t btn_pr;
/*Search the pressed area*/
lv_indev_get_point(param, &p);
btn_pr = get_button_from_point(obj, &p);
/*Handle the case where there is no button there*/
if(btn_pr != LV_BTNMATRIX_BTN_NONE) {
if(button_is_inactive(btnm->ctrl_bits[btn_pr]) == false &&
button_is_hidden(btnm->ctrl_bits[btn_pr]) == false) {
btnm->btn_id_sel = btn_pr;
invalidate_button_area(obj, btnm->btn_id_sel); /*Invalidate the new area*/
}
}
}
if(btnm->btn_id_sel != LV_BTNMATRIX_BTN_NONE) {
if(button_is_click_trig(btnm->ctrl_bits[btnm->btn_id_sel]) == false &&
button_is_popover(btnm->ctrl_bits[btnm->btn_id_sel]) == false &&
button_is_inactive(btnm->ctrl_bits[btnm->btn_id_sel]) == false &&
button_is_hidden(btnm->ctrl_bits[btnm->btn_id_sel]) == false) {
uint32_t b = btnm->btn_id_sel;
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, &b);
if(res != LV_RES_OK) return;
}
}
}
else if(code == LV_EVENT_PRESSING) {
void * param = lv_event_get_param(e);
uint16_t btn_pr = LV_BTNMATRIX_BTN_NONE;
/*Search the pressed area*/
lv_indev_t * indev = lv_indev_get_act();
lv_indev_type_t indev_type = lv_indev_get_type(indev);
if(indev_type == LV_INDEV_TYPE_ENCODER || indev_type == LV_INDEV_TYPE_KEYPAD) return;
lv_indev_get_point(indev, &p);
btn_pr = get_button_from_point(obj, &p);
/*Invalidate to old and the new areas*/
if(btn_pr != btnm->btn_id_sel) {
if(btnm->btn_id_sel != LV_BTNMATRIX_BTN_NONE) {
invalidate_button_area(obj, btnm->btn_id_sel);
}
btnm->btn_id_sel = btn_pr;
lv_indev_reset_long_press(param); /*Start the log press time again on the new button*/
if(btn_pr != LV_BTNMATRIX_BTN_NONE &&
button_is_inactive(btnm->ctrl_bits[btn_pr]) == false &&
button_is_hidden(btnm->ctrl_bits[btn_pr]) == false) {
invalidate_button_area(obj, btn_pr);
/*Send VALUE_CHANGED for the newly pressed button*/
if(button_is_click_trig(btnm->ctrl_bits[btn_pr]) == false &&
button_is_popover(btnm->ctrl_bits[btnm->btn_id_sel]) == false) {
uint32_t b = btn_pr;
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, &b);
if(res != LV_RES_OK) return;
}
}
}
}
else if(code == LV_EVENT_RELEASED) {
if(btnm->btn_id_sel != LV_BTNMATRIX_BTN_NONE) {
/*Toggle the button if enabled*/
if(button_is_checkable(btnm->ctrl_bits[btnm->btn_id_sel]) &&
!button_is_inactive(btnm->ctrl_bits[btnm->btn_id_sel])) {
if(button_get_checked(btnm->ctrl_bits[btnm->btn_id_sel]) && !btnm->one_check) {
btnm->ctrl_bits[btnm->btn_id_sel] &= (~LV_BTNMATRIX_CTRL_CHECKED);
}
else {
btnm->ctrl_bits[btnm->btn_id_sel] |= LV_BTNMATRIX_CTRL_CHECKED;
}
if(btnm->one_check) make_one_button_checked(obj, btnm->btn_id_sel);
}
if((button_is_click_trig(btnm->ctrl_bits[btnm->btn_id_sel]) == true ||
button_is_popover(btnm->ctrl_bits[btnm->btn_id_sel]) == true) &&
button_is_inactive(btnm->ctrl_bits[btnm->btn_id_sel]) == false &&
button_is_hidden(btnm->ctrl_bits[btnm->btn_id_sel]) == false) {
uint32_t b = btnm->btn_id_sel;
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, &b);
if(res != LV_RES_OK) return;
}
}
/*Invalidate to old pressed area*/;
invalidate_button_area(obj, btnm->btn_id_sel);
lv_indev_type_t indev_type = lv_indev_get_type(lv_indev_get_act());
if(indev_type == LV_INDEV_TYPE_POINTER || indev_type == LV_INDEV_TYPE_BUTTON) {
btnm->btn_id_sel = LV_BTNMATRIX_BTN_NONE;
}
}
else if(code == LV_EVENT_LONG_PRESSED_REPEAT) {
if(btnm->btn_id_sel != LV_BTNMATRIX_BTN_NONE) {
if(button_is_repeat_disabled(btnm->ctrl_bits[btnm->btn_id_sel]) == false &&
button_is_inactive(btnm->ctrl_bits[btnm->btn_id_sel]) == false &&
button_is_hidden(btnm->ctrl_bits[btnm->btn_id_sel]) == false) {
uint32_t b = btnm->btn_id_sel;
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, &b);
if(res != LV_RES_OK) return;
}
}
}
else if(code == LV_EVENT_PRESS_LOST) {
invalidate_button_area(obj, btnm->btn_id_sel);
btnm->btn_id_sel = LV_BTNMATRIX_BTN_NONE;
}
else if(code == LV_EVENT_FOCUSED) {
lv_indev_t * indev = lv_event_get_param(e);
lv_indev_type_t indev_type = lv_indev_get_type(indev);
/*If not focused by an input device assume the last input device*/
if(indev == NULL) {
indev = lv_indev_get_next(NULL);
indev_type = lv_indev_get_type(indev);
}
bool editing = lv_group_get_editing(lv_obj_get_group(obj));
/*Focus the first button if there is not selected button*/
if(btnm->btn_id_sel == LV_BTNMATRIX_BTN_NONE) {
if(indev_type == LV_INDEV_TYPE_KEYPAD || (indev_type == LV_INDEV_TYPE_ENCODER && editing)) {
uint32_t b = 0;
if(btnm->one_check) {
while(button_is_hidden(btnm->ctrl_bits[b]) || button_is_inactive(btnm->ctrl_bits[b]) ||
button_is_checked(btnm->ctrl_bits[b]) == false) b++;
}
else {
while(button_is_hidden(btnm->ctrl_bits[b]) || button_is_inactive(btnm->ctrl_bits[b])) b++;
}
btnm->btn_id_sel = b;
}
else {
btnm->btn_id_sel = LV_BTNMATRIX_BTN_NONE;
}
}
}
else if(code == LV_EVENT_DEFOCUSED || code == LV_EVENT_LEAVE) {
if(btnm->btn_id_sel != LV_BTNMATRIX_BTN_NONE) invalidate_button_area(obj, btnm->btn_id_sel);
btnm->btn_id_sel = LV_BTNMATRIX_BTN_NONE;
}
else if(code == LV_EVENT_KEY) {
invalidate_button_area(obj, btnm->btn_id_sel);
char c = *((char *)lv_event_get_param(e));
if(c == LV_KEY_RIGHT) {
if(btnm->btn_id_sel == LV_BTNMATRIX_BTN_NONE) btnm->btn_id_sel = 0;
else btnm->btn_id_sel++;
if(btnm->btn_id_sel >= btnm->btn_cnt) btnm->btn_id_sel = 0;
while(button_is_hidden(btnm->ctrl_bits[btnm->btn_id_sel]) || button_is_inactive(btnm->ctrl_bits[btnm->btn_id_sel])) {
btnm->btn_id_sel++;
if(btnm->btn_id_sel >= btnm->btn_cnt) btnm->btn_id_sel = 0;
}
}
else if(c == LV_KEY_LEFT) {
if(btnm->btn_id_sel == LV_BTNMATRIX_BTN_NONE) btnm->btn_id_sel = 0;
if(btnm->btn_id_sel == 0) btnm->btn_id_sel = btnm->btn_cnt - 1;
else if(btnm->btn_id_sel > 0) btnm->btn_id_sel--;
while(button_is_hidden(btnm->ctrl_bits[btnm->btn_id_sel]) || button_is_inactive(btnm->ctrl_bits[btnm->btn_id_sel])) {
if(btnm->btn_id_sel > 0) btnm->btn_id_sel--;
else btnm->btn_id_sel = btnm->btn_cnt - 1;
}
}
else if(c == LV_KEY_DOWN) {
lv_coord_t col_gap = lv_obj_get_style_pad_column(obj, LV_PART_MAIN);
/*Find the area below the the current*/
if(btnm->btn_id_sel == LV_BTNMATRIX_BTN_NONE) {
btnm->btn_id_sel = 0;
while(button_is_hidden(btnm->ctrl_bits[btnm->btn_id_sel]) || button_is_inactive(btnm->ctrl_bits[btnm->btn_id_sel])) {
btnm->btn_id_sel++;
if(btnm->btn_id_sel >= btnm->btn_cnt) btnm->btn_id_sel = 0;
}
}
else {
uint16_t area_below;
lv_coord_t pr_center =
btnm->button_areas[btnm->btn_id_sel].x1 + (lv_area_get_width(&btnm->button_areas[btnm->btn_id_sel]) >> 1);
for(area_below = btnm->btn_id_sel; area_below < btnm->btn_cnt; area_below++) {
if(btnm->button_areas[area_below].y1 > btnm->button_areas[btnm->btn_id_sel].y1 &&
pr_center >= btnm->button_areas[area_below].x1 &&
pr_center <= btnm->button_areas[area_below].x2 + col_gap &&
button_is_inactive(btnm->ctrl_bits[area_below]) == false &&
button_is_hidden(btnm->ctrl_bits[area_below]) == false) {
break;
}
}
if(area_below < btnm->btn_cnt) btnm->btn_id_sel = area_below;
}
}
else if(c == LV_KEY_UP) {
lv_coord_t col_gap = lv_obj_get_style_pad_column(obj, LV_PART_MAIN);
/*Find the area below the the current*/
if(btnm->btn_id_sel == LV_BTNMATRIX_BTN_NONE) {
btnm->btn_id_sel = 0;
while(button_is_hidden(btnm->ctrl_bits[btnm->btn_id_sel]) || button_is_inactive(btnm->ctrl_bits[btnm->btn_id_sel])) {
btnm->btn_id_sel++;
if(btnm->btn_id_sel >= btnm->btn_cnt) btnm->btn_id_sel = 0;
}
}
else {
int16_t area_above;
lv_coord_t pr_center =
btnm->button_areas[btnm->btn_id_sel].x1 + (lv_area_get_width(&btnm->button_areas[btnm->btn_id_sel]) >> 1);
for(area_above = btnm->btn_id_sel; area_above >= 0; area_above--) {
if(btnm->button_areas[area_above].y1 < btnm->button_areas[btnm->btn_id_sel].y1 &&
pr_center >= btnm->button_areas[area_above].x1 - col_gap &&
pr_center <= btnm->button_areas[area_above].x2 &&
button_is_inactive(btnm->ctrl_bits[area_above]) == false &&
button_is_hidden(btnm->ctrl_bits[area_above]) == false) {
break;
}
}
if(area_above >= 0) btnm->btn_id_sel = area_above;
}
}
invalidate_button_area(obj, btnm->btn_id_sel);
}
else if(code == LV_EVENT_DRAW_MAIN) {
draw_main(e);
}
}
static void draw_main(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;
if(btnm->btn_cnt == 0) return;
const lv_area_t * clip_area = lv_event_get_param(e);
obj->skip_trans = 1;
lv_area_t area_obj;
lv_obj_get_coords(obj, &area_obj);
lv_area_t btn_area;
uint16_t btn_i = 0;
uint16_t txt_i = 0;
lv_draw_rect_dsc_t draw_rect_dsc_act;
lv_draw_label_dsc_t draw_label_dsc_act;
lv_draw_rect_dsc_t draw_rect_dsc_def;
lv_draw_label_dsc_t draw_label_dsc_def;
lv_state_t state_ori = obj->state;
obj->state = LV_STATE_DEFAULT;
obj->skip_trans = 1;
lv_draw_rect_dsc_init(&draw_rect_dsc_def);
lv_draw_label_dsc_init(&draw_label_dsc_def);
lv_obj_init_draw_rect_dsc(obj, LV_PART_ITEMS, &draw_rect_dsc_def);
lv_obj_init_draw_label_dsc(obj, LV_PART_ITEMS, &draw_label_dsc_def);
obj->skip_trans = 0;
obj->state = state_ori;
lv_coord_t ptop = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_coord_t pbottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
lv_coord_t pleft = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t pright = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
#if LV_USE_ARABIC_PERSIAN_CHARS
const size_t txt_ap_size = 256 ;
char * txt_ap = lv_mem_buf_get(txt_ap_size);
#endif
lv_obj_draw_part_dsc_t part_draw_dsc;
lv_obj_draw_dsc_init(&part_draw_dsc, clip_area);
part_draw_dsc.part = LV_PART_ITEMS;
part_draw_dsc.class_p = MY_CLASS;
part_draw_dsc.type = LV_BTNMATRIX_DRAW_PART_BTN;
part_draw_dsc.rect_dsc = &draw_rect_dsc_act;
part_draw_dsc.label_dsc = &draw_label_dsc_act;
for(btn_i = 0; btn_i < btnm->btn_cnt; btn_i++, txt_i++) {
/*Search the next valid text in the map*/
while(strcmp(btnm->map_p[txt_i], "\n") == 0) {
txt_i++;
}
/*Skip hidden buttons*/
if(button_is_hidden(btnm->ctrl_bits[btn_i])) continue;
/*Get the state of the button*/
lv_state_t btn_state = LV_STATE_DEFAULT;
if(button_get_checked(btnm->ctrl_bits[btn_i])) btn_state |= LV_STATE_CHECKED;
if(button_is_inactive(btnm->ctrl_bits[btn_i])) btn_state |= LV_STATE_DISABLED;
else if(btn_i == btnm->btn_id_sel) {
if(state_ori & LV_STATE_PRESSED) btn_state |= LV_STATE_PRESSED;
if(state_ori & LV_STATE_FOCUSED) btn_state |= LV_STATE_FOCUSED;
if(state_ori & LV_STATE_FOCUS_KEY) btn_state |= LV_STATE_FOCUS_KEY;
if(state_ori & LV_STATE_EDITED) btn_state |= LV_STATE_EDITED;
}
/*Get the button's area*/
lv_area_copy(&btn_area, &btnm->button_areas[btn_i]);
btn_area.x1 += area_obj.x1;
btn_area.y1 += area_obj.y1;
btn_area.x2 += area_obj.x1;
btn_area.y2 += area_obj.y1;
/*Set up the draw descriptors*/
if(btn_state == LV_STATE_DEFAULT) {
lv_memcpy(&draw_rect_dsc_act, &draw_rect_dsc_def, sizeof(lv_draw_rect_dsc_t));
lv_memcpy(&draw_label_dsc_act, &draw_label_dsc_def, sizeof(lv_draw_label_dsc_t));
}
/*In other cases get the styles directly without caching them*/
else {
obj->state = btn_state;
obj->skip_trans = 1;
lv_draw_rect_dsc_init(&draw_rect_dsc_act);
lv_draw_label_dsc_init(&draw_label_dsc_act);
lv_obj_init_draw_rect_dsc(obj, LV_PART_ITEMS, &draw_rect_dsc_act);
lv_obj_init_draw_label_dsc(obj, LV_PART_ITEMS, &draw_label_dsc_act);
obj->state = state_ori;
obj->skip_trans = 0;
}
bool recolor = button_is_recolor(btnm->ctrl_bits[btn_i]);
if(recolor) draw_label_dsc_act.flag |= LV_TEXT_FLAG_RECOLOR;
else draw_label_dsc_act.flag &= ~LV_TEXT_FLAG_RECOLOR;
part_draw_dsc.draw_area = &btn_area;
part_draw_dsc.id = btn_i;
lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_draw_dsc);
/*Remove borders on the edges if `LV_BORDER_SIDE_INTERNAL`*/
if(draw_rect_dsc_act.border_side & LV_BORDER_SIDE_INTERNAL) {
draw_rect_dsc_act.border_side = LV_BORDER_SIDE_FULL;
if(btn_area.x1 == obj->coords.x1 + pleft) draw_rect_dsc_act.border_side &= ~LV_BORDER_SIDE_LEFT;
if(btn_area.x2 == obj->coords.x2 - pright) draw_rect_dsc_act.border_side &= ~LV_BORDER_SIDE_RIGHT;
if(btn_area.y1 == obj->coords.y1 + ptop) draw_rect_dsc_act.border_side &= ~LV_BORDER_SIDE_TOP;
if(btn_area.y2 == obj->coords.y2 - pbottom) draw_rect_dsc_act.border_side &= ~LV_BORDER_SIDE_BOTTOM;
}
lv_coord_t btn_height = lv_area_get_height(&btn_area);
if ((btn_state & LV_STATE_PRESSED) && (btnm->ctrl_bits[btn_i] & LV_BTNMATRIX_CTRL_POPOVER)) {
/*Push up the upper boundary of the btn area to create the popover*/
btn_area.y1 -= btn_height;
}
/*Draw the background*/
lv_draw_rect(&btn_area, clip_area, &draw_rect_dsc_act);
/*Calculate the size of the text*/
const lv_font_t * font = draw_label_dsc_act.font;
lv_coord_t letter_space = draw_label_dsc_act.letter_space;
lv_coord_t line_space = draw_label_dsc_act.line_space;
const char * txt = btnm->map_p[txt_i];
#if LV_USE_ARABIC_PERSIAN_CHARS
/*Get the size of the Arabic text and process it*/
size_t len_ap = _lv_txt_ap_calc_bytes_cnt(txt);
if(len_ap < txt_ap_size) {
_lv_txt_ap_proc(txt, txt_ap);
txt = txt_ap;
}
#endif
lv_point_t txt_size;
lv_txt_get_size(&txt_size, txt, font, letter_space,
line_space, lv_area_get_width(&area_obj), draw_label_dsc_act.flag);
btn_area.x1 += (lv_area_get_width(&btn_area) - txt_size.x) / 2;
btn_area.y1 += (lv_area_get_height(&btn_area) - txt_size.y) / 2;
btn_area.x2 = btn_area.x1 + txt_size.x;
btn_area.y2 = btn_area.y1 + txt_size.y;
if ((btn_state & LV_STATE_PRESSED) && (btnm->ctrl_bits[btn_i] & LV_BTNMATRIX_CTRL_POPOVER)) {
/*Push up the button text into the popover*/
btn_area.y1 -= btn_height / 2;
btn_area.y2 -= btn_height / 2;
}
/*Draw the text*/
lv_draw_label(&btn_area, clip_area, &draw_label_dsc_act, txt, NULL);
lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_draw_dsc);
}
obj->skip_trans = 0;
#if LV_USE_ARABIC_PERSIAN_CHARS
lv_mem_buf_release(txt_ap);
#endif
}
/**
* Create the required number of buttons and control bytes according to a map
* @param obj pointer to button matrix object
* @param map_p pointer to a string array
*/
static void allocate_btn_areas_and_controls(const lv_obj_t * obj, const char ** map)
{
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;
btnm->row_cnt = 1;
/*Count the buttons in the map*/
uint16_t btn_cnt = 0;
uint16_t i = 0;
while(map[i] && map[i][0] != '\0') {
if(strcmp(map[i], "\n") != 0) { /*Do not count line breaks*/
btn_cnt++;
} else {
btnm->row_cnt++;
}
i++;
}
/*Do not allocate memory for the same amount of buttons*/
if(btn_cnt == btnm->btn_cnt) return;
if(btnm->button_areas != NULL) {
lv_mem_free(btnm->button_areas);
btnm->button_areas = NULL;
}
if(btnm->ctrl_bits != NULL) {
lv_mem_free(btnm->ctrl_bits);
btnm->ctrl_bits = NULL;
}
btnm->button_areas = lv_mem_alloc(sizeof(lv_area_t) * btn_cnt);
LV_ASSERT_MALLOC(btnm->button_areas);
btnm->ctrl_bits = lv_mem_alloc(sizeof(lv_btnmatrix_ctrl_t) * btn_cnt);
LV_ASSERT_MALLOC(btnm->ctrl_bits);
if(btnm->button_areas == NULL || btnm->ctrl_bits == NULL) btn_cnt = 0;
lv_memset_00(btnm->ctrl_bits, sizeof(lv_btnmatrix_ctrl_t) * btn_cnt);
btnm->btn_cnt = btn_cnt;
}
/**
* Get the width of a button in units (default is 1).
* @param ctrl_bits least significant 3 bits used (1..7 valid values)
* @return the width of the button in units
*/
static uint8_t get_button_width(lv_btnmatrix_ctrl_t ctrl_bits)
{
uint8_t w = ctrl_bits & LV_BTNMATRIX_WIDTH_MASK;
return w != 0 ? w : 1;
}
static bool button_is_hidden(lv_btnmatrix_ctrl_t ctrl_bits)
{
return (ctrl_bits & LV_BTNMATRIX_CTRL_HIDDEN) ? true : false;
}
static bool button_is_checked(lv_btnmatrix_ctrl_t ctrl_bits)
{
return (ctrl_bits & LV_BTNMATRIX_CTRL_CHECKED) ? true : false;
}
static bool button_is_repeat_disabled(lv_btnmatrix_ctrl_t ctrl_bits)
{
return (ctrl_bits & LV_BTNMATRIX_CTRL_NO_REPEAT) ? true : false;
}
static bool button_is_inactive(lv_btnmatrix_ctrl_t ctrl_bits)
{
return (ctrl_bits & LV_BTNMATRIX_CTRL_DISABLED) ? true : false;
}
static bool button_is_click_trig(lv_btnmatrix_ctrl_t ctrl_bits)
{
return (ctrl_bits & LV_BTNMATRIX_CTRL_CLICK_TRIG) ? true : false;
}
static bool button_is_popover(lv_btnmatrix_ctrl_t ctrl_bits)
{
return (ctrl_bits & LV_BTNMATRIX_CTRL_POPOVER) ? true : false;
}
static bool button_is_checkable(lv_btnmatrix_ctrl_t ctrl_bits)
{
return (ctrl_bits & LV_BTNMATRIX_CTRL_CHECKABLE) ? true : false;
}
static bool button_get_checked(lv_btnmatrix_ctrl_t ctrl_bits)
{
return (ctrl_bits & LV_BTNMATRIX_CTRL_CHECKED) ? true : false;
}
static bool button_is_recolor(lv_btnmatrix_ctrl_t ctrl_bits)
{
return (ctrl_bits & LV_BTNMATRIX_CTRL_RECOLOR) ? true : false;
}
/**
* Gives the button id of a button under a given point
* @param obj pointer to a button matrix object
* @param p a point with absolute coordinates
* @return the id of the button or LV_BTNMATRIX_BTN_NONE.
*/
static uint16_t get_button_from_point(lv_obj_t * obj, lv_point_t * p)
{
lv_area_t obj_cords;
lv_area_t btn_area;
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;;
uint16_t i;
lv_obj_get_coords(obj, &obj_cords);
lv_coord_t w = lv_obj_get_width(obj);
lv_coord_t h = lv_obj_get_height(obj);
lv_coord_t pleft = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t pright = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
lv_coord_t ptop = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_coord_t pbottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
lv_coord_t prow = lv_obj_get_style_pad_row(obj, LV_PART_MAIN);
lv_coord_t pcol = lv_obj_get_style_pad_column(obj, LV_PART_MAIN);
/*Get the half gap. Button look larger with this value. (+1 for rounding error)*/
prow = (prow / 2) + 1 + (prow & 1);
pcol = (pcol / 2) + 1 + (pcol & 1);
prow = LV_MIN(prow, BTN_EXTRA_CLICK_AREA_MAX);
pcol = LV_MIN(pcol, BTN_EXTRA_CLICK_AREA_MAX);
pright = LV_MIN(pright, BTN_EXTRA_CLICK_AREA_MAX);
ptop = LV_MIN(ptop, BTN_EXTRA_CLICK_AREA_MAX);
pbottom = LV_MIN(pbottom, BTN_EXTRA_CLICK_AREA_MAX);
for(i = 0; i < btnm->btn_cnt; i++) {
lv_area_copy(&btn_area, &btnm->button_areas[i]);
if(btn_area.x1 <= pleft) btn_area.x1 += obj_cords.x1 - LV_MIN(pleft, BTN_EXTRA_CLICK_AREA_MAX);
else btn_area.x1 += obj_cords.x1 - pcol;
if(btn_area.y1 <= ptop) btn_area.y1 += obj_cords.y1 - LV_MIN(ptop, BTN_EXTRA_CLICK_AREA_MAX);
else btn_area.y1 += obj_cords.y1 - prow;
if(btn_area.x2 >= w - pright - 2) btn_area.x2 += obj_cords.x1 + LV_MIN(pright,
BTN_EXTRA_CLICK_AREA_MAX); /*-2 for rounding error*/
else btn_area.x2 += obj_cords.x1 + pcol;
if(btn_area.y2 >= h - pbottom - 2) btn_area.y2 += obj_cords.y1 + LV_MIN(pbottom,
BTN_EXTRA_CLICK_AREA_MAX); /*-2 for rounding error*/
else btn_area.y2 += obj_cords.y1 + prow;
if(_lv_area_is_point_on(&btn_area, p, 0) != false) {
break;
}
}
if(i == btnm->btn_cnt) i = LV_BTNMATRIX_BTN_NONE;
return i;
}
static void invalidate_button_area(const lv_obj_t * obj, uint16_t btn_idx)
{
if(btn_idx == LV_BTNMATRIX_BTN_NONE) return;
lv_area_t btn_area;
lv_area_t obj_area;
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;;
lv_area_copy(&btn_area, &btnm->button_areas[btn_idx]);
lv_obj_get_coords(obj, &obj_area);
/*The buttons might have outline and shadow so make the invalidation larger with the gaps between the buttons.
*It assumes that the outline or shadow is smaller than the gaps*/
lv_coord_t row_gap = lv_obj_get_style_pad_row(obj, LV_PART_MAIN);
lv_coord_t col_gap = lv_obj_get_style_pad_column(obj, LV_PART_MAIN);
/*Be sure to have a minimal extra space if row/col_gap is small*/
lv_coord_t dpi = lv_disp_get_dpi(lv_obj_get_disp(obj));
row_gap = LV_MAX(row_gap, dpi / 10);
col_gap = LV_MAX(col_gap, dpi / 10);
/*Convert relative coordinates to absolute*/
btn_area.x1 += obj_area.x1 - row_gap;
btn_area.y1 += obj_area.y1 - col_gap;
btn_area.x2 += obj_area.x1 + row_gap;
btn_area.y2 += obj_area.y1 + col_gap;
if ((btn_idx == btnm->btn_id_sel) && (btnm->ctrl_bits[btn_idx] & LV_BTNMATRIX_CTRL_POPOVER)) {
/*Push up the upper boundary of the btn area to also invalidate the popover*/
btn_area.y1 -= lv_area_get_height(&btn_area);
}
lv_obj_invalidate_area(obj, &btn_area);
}
/**
* Enforces a single button being toggled on the button matrix.
* It simply clears the toggle flag on other buttons.
* @param obj Button matrix object
* @param btn_idx Button that should remain toggled
*/
static void make_one_button_checked(lv_obj_t * obj, uint16_t btn_idx)
{
/*Save whether the button was toggled*/
bool was_toggled = lv_btnmatrix_has_btn_ctrl(obj, btn_idx, LV_BTNMATRIX_CTRL_CHECKED);
lv_btnmatrix_clear_btn_ctrl_all(obj, LV_BTNMATRIX_CTRL_CHECKED);
if(was_toggled) lv_btnmatrix_set_btn_ctrl(obj, btn_idx, LV_BTNMATRIX_CTRL_CHECKED);
}
/**
* Check if any of the buttons in the first row has the LV_BTNMATRIX_CTRL_POPOVER control flag set.
* @param obj Button matrix object
* @return true if at least one button has the flag, false otherwise
*/
static bool has_popovers_in_top_row(lv_obj_t * obj)
{
lv_btnmatrix_t * btnm = (lv_btnmatrix_t *)obj;
if (btnm->row_cnt <= 0) {
return false;
}
const char ** map_row = btnm->map_p;
uint16_t btn_cnt = 0;
while (map_row[btn_cnt] && strcmp(map_row[btn_cnt], "\n") != 0 && map_row[btn_cnt][0] != '\0') {
if (button_is_popover(btnm->ctrl_bits[btn_cnt])) {
return true;
}
btn_cnt++;
}
return false;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_btnmatrix.c | C | apache-2.0 | 38,344 |
/**
* @file lv_btnm.h
*
*/
#ifndef LV_BTNMATRIX_H
#define LV_BTNMATRIX_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_BTNMATRIX != 0
#include "../core/lv_obj.h"
/*********************
* DEFINES
*********************/
#define LV_BTNMATRIX_BTN_NONE 0xFFFF
LV_EXPORT_CONST_INT(LV_BTNMATRIX_BTN_NONE);
/**********************
* TYPEDEFS
**********************/
/** Type to store button control bits (disabled, hidden etc.)
* The first 3 bits are used to store the width*/
enum {
_LV_BTNMATRIX_WIDTH = 0x0007, /**< Reserved to stire the size units*/
LV_BTNMATRIX_CTRL_HIDDEN = 0x0008, /**< Button hidden*/
LV_BTNMATRIX_CTRL_NO_REPEAT = 0x0010, /**< Do not repeat press this button.*/
LV_BTNMATRIX_CTRL_DISABLED = 0x0020, /**< Disable this button.*/
LV_BTNMATRIX_CTRL_CHECKABLE = 0x0040, /**< The button can be toggled.*/
LV_BTNMATRIX_CTRL_CHECKED = 0x0080, /**< Button is currently toggled (e.g. checked).*/
LV_BTNMATRIX_CTRL_CLICK_TRIG = 0x0100, /**< 1: Send LV_EVENT_VALUE_CHANGE on CLICK, 0: Send LV_EVENT_VALUE_CHANGE on PRESS*/
LV_BTNMATRIX_CTRL_POPOVER = 0x0200, /**< Show a popover when pressing this key*/
LV_BTNMATRIX_CTRL_RECOLOR = 0x1000, /**< Enable text recoloring with `#color`*/
_LV_BTNMATRIX_CTRL_RESERVED = 0x2000, /**< Reserved for later use*/
LV_BTNMATRIX_CTRL_CUSTOM_1 = 0x4000, /**< Custom free to use flag*/
LV_BTNMATRIX_CTRL_CUSTOM_2 = 0x8000, /**< Custom free to use flag*/
};
typedef uint16_t lv_btnmatrix_ctrl_t;
typedef bool (*lv_btnmatrix_btn_draw_cb_t)(lv_obj_t * btnm, uint32_t btn_id, const lv_area_t * draw_area,
const lv_area_t * clip_area);
/*Data of button matrix*/
typedef struct {
lv_obj_t obj;
const char ** map_p; /*Pointer to the current map*/
lv_area_t * button_areas; /*Array of areas of buttons*/
lv_btnmatrix_ctrl_t * ctrl_bits; /*Array of control bytes*/
uint16_t btn_cnt; /*Number of button in 'map_p'(Handled by the library)*/
uint16_t row_cnt; /*Number of rows in 'map_p'(Handled by the library)*/
uint16_t btn_id_sel; /*Index of the active button (being pressed/released etc) or LV_BTNMATRIX_BTN_NONE*/
uint8_t one_check : 1; /*Single button toggled at once*/
} lv_btnmatrix_t;
extern const lv_obj_class_t lv_btnmatrix_class;
/**
* `type` field in `lv_obj_draw_part_dsc_t` if `class_p = lv_btnmatrix_class`
* Used in `LV_EVENT_DRAW_PART_BEGIN` and `LV_EVENT_DRAW_PART_END`
*/
typedef enum {
LV_BTNMATRIX_DRAW_PART_BTN, /**< The rectangle and label of buttons*/
} lv_btnmatrix_draw_part_type_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a button matrix objects
* @param parent pointer to an object, it will be the parent of the new button matrix
* @return pointer to the created button matrix
*/
lv_obj_t * lv_btnmatrix_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set a new map. Buttons will be created/deleted according to the map. The
* button matrix keeps a reference to the map and so the string array must not
* be deallocated during the life of the matrix.
* @param obj pointer to a button matrix object
* @param map pointer a string array. The last string has to be: "". Use "\n" to make a line break.
*/
void lv_btnmatrix_set_map(lv_obj_t * obj, const char * map[]);
/**
* Set the button control map (hidden, disabled etc.) for a button matrix.
* The control map array will be copied and so may be deallocated after this
* function returns.
* @param obj pointer to a button matrix object
* @param ctrl_map pointer to an array of `lv_btn_ctrl_t` control bytes. The
* length of the array and position of the elements must match
* the number and order of the individual buttons (i.e. excludes
* newline entries).
* An element of the map should look like e.g.:
* `ctrl_map[0] = width | LV_BTNMATRIX_CTRL_NO_REPEAT | LV_BTNMATRIX_CTRL_TGL_ENABLE`
*/
void lv_btnmatrix_set_ctrl_map(lv_obj_t * obj, const lv_btnmatrix_ctrl_t ctrl_map[]);
/**
* Set the selected buttons
* @param obj pointer to button matrix object
* @param btn_id 0 based index of the button to modify. (Not counting new lines)
*/
void lv_btnmatrix_set_selected_btn(lv_obj_t * obj, uint16_t btn_id);
/**
* Set the attributes of a button of the button matrix
* @param obj pointer to button matrix object
* @param btn_id 0 based index of the button to modify. (Not counting new lines)
* @param ctrl OR-ed attributs. E.g. `LV_BTNMATRIX_CTRL_NO_REPEAT | LV_BTNMATRIX_CTRL_CHECKABLE`
*/
void lv_btnmatrix_set_btn_ctrl(lv_obj_t * obj, uint16_t btn_id, lv_btnmatrix_ctrl_t ctrl);
/**
* Clear the attributes of a button of the button matrix
* @param obj pointer to button matrix object
* @param btn_id 0 based index of the button to modify. (Not counting new lines)
* @param ctrl OR-ed attributs. E.g. `LV_BTNMATRIX_CTRL_NO_REPEAT | LV_BTNMATRIX_CTRL_CHECKABLE`
*/
void lv_btnmatrix_clear_btn_ctrl(lv_obj_t * obj, uint16_t btn_id, lv_btnmatrix_ctrl_t ctrl);
/**
* Set attributes of all buttons of a button matrix
* @param obj pointer to a button matrix object
* @param ctrl attribute(s) to set from `lv_btnmatrix_ctrl_t`. Values can be ORed.
*/
void lv_btnmatrix_set_btn_ctrl_all(lv_obj_t * obj, lv_btnmatrix_ctrl_t ctrl);
/**
* Clear the attributes of all buttons of a button matrix
* @param obj pointer to a button matrix object
* @param ctrl attribute(s) to set from `lv_btnmatrix_ctrl_t`. Values can be ORed.
* @param en true: set the attributes; false: clear the attributes
*/
void lv_btnmatrix_clear_btn_ctrl_all(lv_obj_t * obj, lv_btnmatrix_ctrl_t ctrl);
/**
* Set a single button's relative width.
* This method will cause the matrix be regenerated and is a relatively
* expensive operation. It is recommended that initial width be specified using
* `lv_btnmatrix_set_ctrl_map` and this method only be used for dynamic changes.
* @param obj pointer to button matrix object
* @param btn_id 0 based index of the button to modify.
* @param width relative width compared to the buttons in the same row. [1..7]
*/
void lv_btnmatrix_set_btn_width(lv_obj_t * obj, uint16_t btn_id, uint8_t width);
/**
* Make the button matrix like a selector widget (only one button may be checked at a time).
* `LV_BTNMATRIX_CTRL_CHECKABLE` must be enabled on the buttons to be selected using
* `lv_btnmatrix_set_ctrl()` or `lv_btnmatrix_set_btn_ctrl_all()`.
* @param obj pointer to a button matrix object
* @param en whether "one check" mode is enabled
*/
void lv_btnmatrix_set_one_checked(lv_obj_t * obj, bool en);
/*=====================
* Getter functions
*====================*/
/**
* Get the current map of a button matrix
* @param obj pointer to a button matrix object
* @return the current map
*/
const char ** lv_btnmatrix_get_map(const lv_obj_t * obj);
/**
* Get the index of the lastly "activated" button by the user (pressed, released, focused etc)
* Useful in the the `event_cb` to get the text of the button, check if hidden etc.
* @param obj pointer to button matrix object
* @return index of the last released button (LV_BTNMATRIX_BTN_NONE: if unset)
*/
uint16_t lv_btnmatrix_get_selected_btn(const lv_obj_t * obj);
/**
* Get the button's text
* @param obj pointer to button matrix object
* @param btn_id the index a button not counting new line characters.
* @return text of btn_index` button
*/
const char * lv_btnmatrix_get_btn_text(const lv_obj_t * obj, uint16_t btn_id);
/**
* Get the whether a control value is enabled or disabled for button of a button matrix
* @param obj pointer to a button matrix object
* @param btn_id the index of a button not counting new line characters.
* @param ctrl control values to check (ORed value can be used)
* @return true: the control attribute is enabled false: disabled
*/
bool lv_btnmatrix_has_btn_ctrl(lv_obj_t * obj, uint16_t btn_id, lv_btnmatrix_ctrl_t ctrl);
/**
* Tell whether "one check" mode is enabled or not.
* @param obj Button matrix object
* @return true: "one check" mode is enabled; false: disabled
*/
bool lv_btnmatrix_get_one_checked(const lv_obj_t * obj);
/**********************
* MACROS
**********************/
#endif /*LV_USE_BTNMATRIX*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_BTNMATRIX_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_btnmatrix.h | C | apache-2.0 | 8,928 |
/**
* @file lv_canvas.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_canvas.h"
#include "../misc/lv_assert.h"
#include "../misc/lv_math.h"
#include "../draw/lv_draw.h"
#include "../core/lv_refr.h"
#if LV_USE_CANVAS != 0
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_canvas_class
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_canvas_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_canvas_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_canvas_class = {
.constructor_cb = lv_canvas_constructor,
.destructor_cb = lv_canvas_destructor,
.instance_size = sizeof(lv_canvas_t),
.base_class = &lv_img_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_canvas_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*=====================
* Setter functions
*====================*/
void lv_canvas_set_buffer(lv_obj_t * obj, void * buf, lv_coord_t w, lv_coord_t h, lv_img_cf_t cf)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(buf);
lv_canvas_t * canvas = (lv_canvas_t *)obj;
canvas->dsc.header.cf = cf;
canvas->dsc.header.w = w;
canvas->dsc.header.h = h;
canvas->dsc.data = buf;
lv_img_set_src(obj, &canvas->dsc);
}
void lv_canvas_set_px_color(lv_obj_t * obj, lv_coord_t x, lv_coord_t y, lv_color_t c)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_canvas_t * canvas = (lv_canvas_t *)obj;
lv_img_buf_set_px_color(&canvas->dsc, x, y, c);
lv_obj_invalidate(obj);
}
void lv_canvas_set_px_opa(lv_obj_t * obj, lv_coord_t x, lv_coord_t y, lv_opa_t opa)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_canvas_t * canvas = (lv_canvas_t *)obj;
lv_img_buf_set_px_alpha(&canvas->dsc, x, y, opa);
lv_obj_invalidate(obj);
}
void lv_canvas_set_palette(lv_obj_t * obj, uint8_t id, lv_color_t c)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_canvas_t * canvas = (lv_canvas_t *)obj;
lv_img_buf_set_palette(&canvas->dsc, id, c);
lv_obj_invalidate(obj);
}
/*=====================
* Getter functions
*====================*/
lv_color_t lv_canvas_get_px(lv_obj_t * obj, lv_coord_t x, lv_coord_t y)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_canvas_t * canvas = (lv_canvas_t *)obj;
lv_color_t color = lv_obj_get_style_img_recolor(obj, LV_PART_MAIN);
return lv_img_buf_get_px_color(&canvas->dsc, x, y, color);
}
lv_img_dsc_t * lv_canvas_get_img(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_canvas_t * canvas = (lv_canvas_t *)obj;
return &canvas->dsc;
}
/*=====================
* Other functions
*====================*/
void lv_canvas_copy_buf(lv_obj_t * obj, const void * to_copy, lv_coord_t x, lv_coord_t y, lv_coord_t w, lv_coord_t h)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(to_copy);
lv_canvas_t * canvas = (lv_canvas_t *)obj;
if(x + w >= (lv_coord_t)canvas->dsc.header.w || y + h >= (lv_coord_t)canvas->dsc.header.h) {
LV_LOG_WARN("lv_canvas_copy_buf: x or y out of the canvas");
return;
}
uint32_t px_size = lv_img_cf_get_px_size(canvas->dsc.header.cf) >> 3;
uint32_t px = canvas->dsc.header.w * y * px_size + x * px_size;
uint8_t * to_copy8 = (uint8_t *)to_copy;
lv_coord_t i;
for(i = 0; i < h; i++) {
lv_memcpy((void *)&canvas->dsc.data[px], to_copy8, w * px_size);
px += canvas->dsc.header.w * px_size;
to_copy8 += w * px_size;
}
}
void lv_canvas_transform(lv_obj_t * obj, lv_img_dsc_t * img, int16_t angle, uint16_t zoom, lv_coord_t offset_x,
lv_coord_t offset_y,
int32_t pivot_x, int32_t pivot_y, bool antialias)
{
#if LV_DRAW_COMPLEX
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(img);
lv_canvas_t * canvas = (lv_canvas_t *)obj;
lv_color_t color = lv_obj_get_style_img_recolor(obj, LV_PART_MAIN);
int32_t dest_width = canvas->dsc.header.w;
int32_t dest_height = canvas->dsc.header.h;
int32_t x;
int32_t y;
bool ret;
lv_img_transform_dsc_t dsc;
dsc.cfg.angle = angle;
dsc.cfg.zoom = zoom;
dsc.cfg.src = img->data;
dsc.cfg.src_w = img->header.w;
dsc.cfg.src_h = img->header.h;
dsc.cfg.cf = img->header.cf;
dsc.cfg.pivot_x = pivot_x;
dsc.cfg.pivot_y = pivot_y;
dsc.cfg.color = color;
dsc.cfg.antialias = antialias;
_lv_img_buf_transform_init(&dsc);
for(y = -offset_y; y < dest_height - offset_y; y++) {
for(x = -offset_x; x < dest_width - offset_x; x++) {
ret = _lv_img_buf_transform(&dsc, x, y);
if(ret == false) continue;
if(x + offset_x >= 0 && x + offset_x < dest_width && y + offset_y >= 0 && y + offset_y < dest_height) {
/*If the image has no alpha channel just simple set the result color on the canvas*/
if(lv_img_cf_has_alpha(img->header.cf) == false) {
lv_img_buf_set_px_color(&canvas->dsc, x + offset_x, y + offset_y, dsc.res.color);
}
else {
lv_color_t bg_color = lv_img_buf_get_px_color(&canvas->dsc, x + offset_x, y + offset_y, dsc.cfg.color);
/*If the canvas has no alpha but the image has mix the image's color with
* canvas*/
if(lv_img_cf_has_alpha(canvas->dsc.header.cf) == false) {
if(dsc.res.opa < LV_OPA_MAX) dsc.res.color = lv_color_mix(dsc.res.color, bg_color, dsc.res.opa);
lv_img_buf_set_px_color(&canvas->dsc, x + offset_x, y + offset_y, dsc.res.color);
}
/*Both the image and canvas has alpha channel. Some extra calculation is
required*/
else {
lv_opa_t bg_opa = lv_img_buf_get_px_alpha(&canvas->dsc, x + offset_x, y + offset_y);
/*Pick the foreground if it's fully opaque or the Background is fully
*transparent*/
if(dsc.res.opa >= LV_OPA_MAX || bg_opa <= LV_OPA_MIN) {
lv_img_buf_set_px_color(&canvas->dsc, x + offset_x, y + offset_y, dsc.res.color);
lv_img_buf_set_px_alpha(&canvas->dsc, x + offset_x, y + offset_y, dsc.res.opa);
}
/*Opaque background: use simple mix*/
else if(bg_opa >= LV_OPA_MAX) {
lv_img_buf_set_px_color(&canvas->dsc, x + offset_x, y + offset_y,
lv_color_mix(dsc.res.color, bg_color, dsc.res.opa));
}
/*Both colors have alpha. Expensive calculation need to be applied*/
else {
/*Info:
* https://en.wikipedia.org/wiki/Alpha_compositing#Analytical_derivation_of_the_over_operator*/
lv_opa_t opa_res_2 = 255 - ((uint16_t)((uint16_t)(255 - dsc.res.opa) * (255 - bg_opa)) >> 8);
if(opa_res_2 == 0) {
opa_res_2 = 1; /*never happens, just to be sure*/
}
lv_opa_t ratio = (uint16_t)((uint16_t)dsc.res.opa * 255) / opa_res_2;
lv_img_buf_set_px_color(&canvas->dsc, x + offset_x, y + offset_y,
lv_color_mix(dsc.res.color, bg_color, ratio));
lv_img_buf_set_px_alpha(&canvas->dsc, x + offset_x, y + offset_y, opa_res_2);
}
}
}
}
}
}
lv_obj_invalidate(obj);
#else
LV_UNUSED(obj);
LV_UNUSED(img);
LV_UNUSED(angle);
LV_UNUSED(zoom);
LV_UNUSED(offset_x);
LV_UNUSED(offset_y);
LV_UNUSED(pivot_x);
LV_UNUSED(pivot_y);
LV_UNUSED(antialias);
LV_LOG_WARN("Can't transform canvas with LV_DRAW_COMPLEX == 0");
#endif
}
void lv_canvas_blur_hor(lv_obj_t * obj, const lv_area_t * area, uint16_t r)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
if(r == 0) return;
lv_canvas_t * canvas = (lv_canvas_t *)obj;
lv_area_t a;
if(area) {
lv_area_copy(&a, area);
if(a.x1 < 0) a.x1 = 0;
if(a.y1 < 0) a.y1 = 0;
if(a.x2 > canvas->dsc.header.w - 1) a.x2 = canvas->dsc.header.w - 1;
if(a.y2 > canvas->dsc.header.h - 1) a.y2 = canvas->dsc.header.h - 1;
}
else {
a.x1 = 0;
a.y1 = 0;
a.x2 = canvas->dsc.header.w - 1;
a.y2 = canvas->dsc.header.h - 1;
}
lv_color_t color = lv_obj_get_style_img_recolor(obj, LV_PART_MAIN);
uint16_t r_back = r / 2;
uint16_t r_front = r / 2;
if((r & 0x1) == 0) r_back--;
bool has_alpha = lv_img_cf_has_alpha(canvas->dsc.header.cf);
lv_coord_t line_w = lv_img_buf_get_img_size(canvas->dsc.header.w, 1, canvas->dsc.header.cf);
uint8_t * line_buf = lv_mem_buf_get(line_w);
lv_img_dsc_t line_img;
line_img.data = line_buf;
line_img.header.always_zero = 0;
line_img.header.w = canvas->dsc.header.w;
line_img.header.h = 1;
line_img.header.cf = canvas->dsc.header.cf;
lv_coord_t x;
lv_coord_t y;
lv_coord_t x_safe;
for(y = a.y1; y <= a.y2; y++) {
uint32_t asum = 0;
uint32_t rsum = 0;
uint32_t gsum = 0;
uint32_t bsum = 0;
lv_color_t c;
lv_opa_t opa = LV_OPA_TRANSP;
lv_memcpy(line_buf, &canvas->dsc.data[y * line_w], line_w);
for(x = a.x1 - r_back; x <= a.x1 + r_front; x++) {
x_safe = x < 0 ? 0 : x;
x_safe = x_safe > canvas->dsc.header.w - 1 ? canvas->dsc.header.w - 1 : x_safe;
c = lv_img_buf_get_px_color(&line_img, x_safe, 0, color);
if(has_alpha) opa = lv_img_buf_get_px_alpha(&line_img, x_safe, 0);
rsum += c.ch.red;
#if LV_COLOR_DEPTH == 16 && LV_COLOR_16_SWAP
gsum += (c.ch.green_h << 3) + c.ch.green_l;
#else
gsum += c.ch.green;
#endif
bsum += c.ch.blue;
if(has_alpha) asum += opa;
}
/*Just to indicate that the px is visible*/
if(has_alpha == false) asum = LV_OPA_COVER;
for(x = a.x1; x <= a.x2; x++) {
if(asum) {
c.ch.red = rsum / r;
#if LV_COLOR_DEPTH == 16 && LV_COLOR_16_SWAP
uint8_t gtmp = gsum / r;
c.ch.green_h = gtmp >> 3;
c.ch.green_l = gtmp & 0x7;
#else
c.ch.green = gsum / r;
#endif
c.ch.blue = bsum / r;
if(has_alpha) opa = asum / r;
lv_img_buf_set_px_color(&canvas->dsc, x, y, c);
}
if(has_alpha) lv_img_buf_set_px_alpha(&canvas->dsc, x, y, opa);
x_safe = x - r_back;
x_safe = x_safe < 0 ? 0 : x_safe;
c = lv_img_buf_get_px_color(&line_img, x_safe, 0, color);
if(has_alpha) opa = lv_img_buf_get_px_alpha(&line_img, x_safe, 0);
rsum -= c.ch.red;
#if LV_COLOR_DEPTH == 16 && LV_COLOR_16_SWAP
gsum -= (c.ch.green_h << 3) + c.ch.green_l;
#else
gsum -= c.ch.green;
#endif
bsum -= c.ch.blue;
if(has_alpha) asum -= opa;
x_safe = x + 1 + r_front;
x_safe = x_safe > canvas->dsc.header.w - 1 ? canvas->dsc.header.w - 1 : x_safe;
c = lv_img_buf_get_px_color(&line_img, x_safe, 0, lv_color_white());
if(has_alpha) opa = lv_img_buf_get_px_alpha(&line_img, x_safe, 0);
rsum += c.ch.red;
#if LV_COLOR_DEPTH == 16 && LV_COLOR_16_SWAP
gsum += (c.ch.green_h << 3) + c.ch.green_l;
#else
gsum += c.ch.green;
#endif
bsum += c.ch.blue;
if(has_alpha) asum += opa;
}
}
lv_obj_invalidate(obj);
lv_mem_buf_release(line_buf);
}
void lv_canvas_blur_ver(lv_obj_t * obj, const lv_area_t * area, uint16_t r)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
if(r == 0) return;
lv_canvas_t * canvas = (lv_canvas_t *)obj;
lv_area_t a;
if(area) {
lv_area_copy(&a, area);
if(a.x1 < 0) a.x1 = 0;
if(a.y1 < 0) a.y1 = 0;
if(a.x2 > canvas->dsc.header.w - 1) a.x2 = canvas->dsc.header.w - 1;
if(a.y2 > canvas->dsc.header.h - 1) a.y2 = canvas->dsc.header.h - 1;
}
else {
a.x1 = 0;
a.y1 = 0;
a.x2 = canvas->dsc.header.w - 1;
a.y2 = canvas->dsc.header.h - 1;
}
lv_color_t color = lv_obj_get_style_img_recolor(obj, LV_PART_MAIN);
uint16_t r_back = r / 2;
uint16_t r_front = r / 2;
if((r & 0x1) == 0) r_back--;
bool has_alpha = lv_img_cf_has_alpha(canvas->dsc.header.cf);
lv_coord_t col_w = lv_img_buf_get_img_size(1, canvas->dsc.header.h, canvas->dsc.header.cf);
uint8_t * col_buf = lv_mem_buf_get(col_w);
lv_img_dsc_t line_img;
line_img.data = col_buf;
line_img.header.always_zero = 0;
line_img.header.w = 1;
line_img.header.h = canvas->dsc.header.h;
line_img.header.cf = canvas->dsc.header.cf;
lv_coord_t x;
lv_coord_t y;
lv_coord_t y_safe;
for(x = a.x1; x <= a.x2; x++) {
uint32_t asum = 0;
uint32_t rsum = 0;
uint32_t gsum = 0;
uint32_t bsum = 0;
lv_color_t c;
lv_opa_t opa = LV_OPA_COVER;
for(y = a.y1 - r_back; y <= a.y1 + r_front; y++) {
y_safe = y < 0 ? 0 : y;
y_safe = y_safe > canvas->dsc.header.h - 1 ? canvas->dsc.header.h - 1 : y_safe;
c = lv_img_buf_get_px_color(&canvas->dsc, x, y_safe, color);
if(has_alpha) opa = lv_img_buf_get_px_alpha(&canvas->dsc, x, y_safe);
lv_img_buf_set_px_color(&line_img, 0, y_safe, c);
if(has_alpha) lv_img_buf_set_px_alpha(&line_img, 0, y_safe, opa);
rsum += c.ch.red;
#if LV_COLOR_DEPTH == 16 && LV_COLOR_16_SWAP
gsum += (c.ch.green_h << 3) + c.ch.green_l;
#else
gsum += c.ch.green;
#endif
bsum += c.ch.blue;
if(has_alpha) asum += opa;
}
/*Just to indicate that the px is visible*/
if(has_alpha == false) asum = LV_OPA_COVER;
for(y = a.y1; y <= a.y2; y++) {
if(asum) {
c.ch.red = rsum / r;
#if LV_COLOR_DEPTH == 16 && LV_COLOR_16_SWAP
uint8_t gtmp = gsum / r;
c.ch.green_h = gtmp >> 3;
c.ch.green_l = gtmp & 0x7;
#else
c.ch.green = gsum / r;
#endif
c.ch.blue = bsum / r;
if(has_alpha) opa = asum / r;
lv_img_buf_set_px_color(&canvas->dsc, x, y, c);
}
if(has_alpha) lv_img_buf_set_px_alpha(&canvas->dsc, x, y, opa);
y_safe = y - r_back;
y_safe = y_safe < 0 ? 0 : y_safe;
c = lv_img_buf_get_px_color(&line_img, 0, y_safe, color);
if(has_alpha) opa = lv_img_buf_get_px_alpha(&line_img, 0, y_safe);
rsum -= c.ch.red;
#if LV_COLOR_DEPTH == 16 && LV_COLOR_16_SWAP
gsum -= (c.ch.green_h << 3) + c.ch.green_l;
#else
gsum -= c.ch.green;
#endif
bsum -= c.ch.blue;
if(has_alpha) asum -= opa;
y_safe = y + 1 + r_front;
y_safe = y_safe > canvas->dsc.header.h - 1 ? canvas->dsc.header.h - 1 : y_safe;
c = lv_img_buf_get_px_color(&canvas->dsc, x, y_safe, color);
if(has_alpha) opa = lv_img_buf_get_px_alpha(&canvas->dsc, x, y_safe);
lv_img_buf_set_px_color(&line_img, 0, y_safe, c);
if(has_alpha) lv_img_buf_set_px_alpha(&line_img, 0, y_safe, opa);
rsum += c.ch.red;
#if LV_COLOR_DEPTH == 16 && LV_COLOR_16_SWAP
gsum += (c.ch.green_h << 3) + c.ch.green_l;
#else
gsum += c.ch.green;
#endif
bsum += c.ch.blue;
if(has_alpha) asum += opa;
}
}
lv_obj_invalidate(obj);
lv_mem_buf_release(col_buf);
}
void lv_canvas_fill_bg(lv_obj_t * canvas, lv_color_t color, lv_opa_t opa)
{
LV_ASSERT_OBJ(canvas, MY_CLASS);
lv_img_dsc_t * dsc = lv_canvas_get_img(canvas);
if(dsc->header.cf == LV_IMG_CF_INDEXED_1BIT) {
uint32_t row_byte_cnt = (dsc->header.w + 7) >> 3;
/*+8 skip the palette*/
lv_memset((uint8_t *)dsc->data + 8, color.full ? 0xff : 0x00, row_byte_cnt * dsc->header.h);
}
else if(dsc->header.cf == LV_IMG_CF_ALPHA_1BIT) {
uint32_t row_byte_cnt = (dsc->header.w + 7) >> 3;
lv_memset((uint8_t *)dsc->data, opa > LV_OPA_50 ? 0xff : 0x00, row_byte_cnt * dsc->header.h);
}
else {
uint32_t x;
uint32_t y;
for(y = 0; y < dsc->header.h; y++) {
for(x = 0; x < dsc->header.w; x++) {
lv_img_buf_set_px_color(dsc, x, y, color);
lv_img_buf_set_px_alpha(dsc, x, y, opa);
}
}
}
lv_obj_invalidate(canvas);
}
void lv_canvas_draw_rect(lv_obj_t * canvas, lv_coord_t x, lv_coord_t y, lv_coord_t w, lv_coord_t h,
const lv_draw_rect_dsc_t * draw_dsc)
{
LV_ASSERT_OBJ(canvas, MY_CLASS);
lv_img_dsc_t * dsc = lv_canvas_get_img(canvas);
if(dsc->header.cf >= LV_IMG_CF_INDEXED_1BIT && dsc->header.cf <= LV_IMG_CF_INDEXED_8BIT) {
LV_LOG_WARN("lv_canvas_draw_rect: can't draw to LV_IMG_CF_INDEXED canvas");
return;
}
/*Create a dummy display to fool the lv_draw function.
*It will think it draws to real screen.*/
lv_area_t mask;
mask.x1 = 0;
mask.x2 = dsc->header.w - 1;
mask.y1 = 0;
mask.y2 = dsc->header.h - 1;
lv_area_t coords;
coords.x1 = x;
coords.y1 = y;
coords.x2 = x + w - 1;
coords.y2 = y + h - 1;
lv_disp_t disp;
/*Allocate the fake driver on the stack as the entire display doesn't outlive this function*/
lv_disp_drv_t driver;
lv_memset_00(&disp, sizeof(lv_disp_t));
disp.driver = &driver;
lv_disp_draw_buf_t draw_buf;
lv_disp_draw_buf_init(&draw_buf, (void *)dsc->data, NULL, dsc->header.w * dsc->header.h);
lv_area_copy(&draw_buf.area, &mask);
lv_disp_drv_init(disp.driver);
disp.driver->draw_buf = &draw_buf;
disp.driver->hor_res = dsc->header.w;
disp.driver->ver_res = dsc->header.h;
lv_disp_drv_use_generic_set_px_cb(disp.driver, dsc->header.cf);
/*Disable anti-aliasing if drawing with transparent color to chroma keyed canvas*/
lv_color_t ctransp = LV_COLOR_CHROMA_KEY;
if(dsc->header.cf == LV_IMG_CF_TRUE_COLOR_CHROMA_KEYED &&
draw_dsc->bg_color.full == ctransp.full) {
disp.driver->antialiasing = 0;
}
lv_disp_t * refr_ori = _lv_refr_get_disp_refreshing();
_lv_refr_set_disp_refreshing(&disp);
lv_draw_rect(&coords, &mask, draw_dsc);
_lv_refr_set_disp_refreshing(refr_ori);
lv_obj_invalidate(canvas);
}
void lv_canvas_draw_text(lv_obj_t * canvas, lv_coord_t x, lv_coord_t y, lv_coord_t max_w,
lv_draw_label_dsc_t * draw_dsc, const char * txt)
{
LV_ASSERT_OBJ(canvas, MY_CLASS);
lv_img_dsc_t * dsc = lv_canvas_get_img(canvas);
if(dsc->header.cf >= LV_IMG_CF_INDEXED_1BIT && dsc->header.cf <= LV_IMG_CF_INDEXED_8BIT) {
LV_LOG_WARN("lv_canvas_draw_text: can't draw to LV_IMG_CF_INDEXED canvas");
return;
}
/*Create a dummy display to fool the lv_draw function.
*It will think it draws to real screen.*/
lv_area_t mask;
mask.x1 = 0;
mask.x2 = dsc->header.w - 1;
mask.y1 = 0;
mask.y2 = dsc->header.h - 1;
lv_area_t coords;
coords.x1 = x;
coords.y1 = y;
coords.x2 = x + max_w - 1;
coords.y2 = dsc->header.h - 1;
lv_disp_t disp;
/*Allocate the fake driver on the stack as the entire display doesn't outlive this function*/
lv_disp_drv_t driver;
lv_memset_00(&disp, sizeof(lv_disp_t));
disp.driver = &driver;
lv_disp_draw_buf_t draw_buf;
lv_disp_draw_buf_init(&draw_buf, (void *)dsc->data, NULL, dsc->header.w * dsc->header.h);
lv_area_copy(&draw_buf.area, &mask);
lv_disp_drv_init(disp.driver);
disp.driver->draw_buf = &draw_buf;
disp.driver->hor_res = dsc->header.w;
disp.driver->ver_res = dsc->header.h;
lv_disp_drv_use_generic_set_px_cb(disp.driver, dsc->header.cf);
lv_disp_t * refr_ori = _lv_refr_get_disp_refreshing();
_lv_refr_set_disp_refreshing(&disp);
lv_draw_label(&coords, &mask, draw_dsc, txt, NULL);
_lv_refr_set_disp_refreshing(refr_ori);
lv_obj_invalidate(canvas);
}
void lv_canvas_draw_img(lv_obj_t * canvas, lv_coord_t x, lv_coord_t y, const void * src,
const lv_draw_img_dsc_t * draw_dsc)
{
LV_ASSERT_OBJ(canvas, MY_CLASS);
lv_img_dsc_t * dsc = lv_canvas_get_img(canvas);
if(dsc->header.cf >= LV_IMG_CF_INDEXED_1BIT && dsc->header.cf <= LV_IMG_CF_INDEXED_8BIT) {
LV_LOG_WARN("lv_canvas_draw_img: can't draw to LV_IMG_CF_INDEXED canvas");
return;
}
/*Create a dummy display to fool the lv_draw function.
*It will think it draws to real screen.*/
lv_area_t mask;
mask.x1 = 0;
mask.x2 = dsc->header.w - 1;
mask.y1 = 0;
mask.y2 = dsc->header.h - 1;
lv_img_header_t header;
lv_res_t res = lv_img_decoder_get_info(src, &header);
if(res != LV_RES_OK) {
LV_LOG_WARN("lv_canvas_draw_img: Couldn't get the image data.");
return;
}
lv_area_t coords;
coords.x1 = x;
coords.y1 = y;
coords.x2 = x + header.w - 1;
coords.y2 = y + header.h - 1;
lv_disp_t disp;
/*Allocate the fake driver on the stack as the entire display doesn't outlive this function*/
lv_disp_drv_t driver;
lv_memset_00(&disp, sizeof(lv_disp_t));
disp.driver = &driver;
lv_disp_draw_buf_t draw_buf;
lv_disp_draw_buf_init(&draw_buf, (void *)dsc->data, NULL, dsc->header.w * dsc->header.h);
lv_area_copy(&draw_buf.area, &mask);
lv_disp_drv_init(disp.driver);
disp.driver->draw_buf = &draw_buf;
disp.driver->hor_res = dsc->header.w;
disp.driver->ver_res = dsc->header.h;
lv_disp_drv_use_generic_set_px_cb(disp.driver, dsc->header.cf);
lv_disp_t * refr_ori = _lv_refr_get_disp_refreshing();
_lv_refr_set_disp_refreshing(&disp);
lv_draw_img(&coords, &mask, src, draw_dsc);
_lv_refr_set_disp_refreshing(refr_ori);
lv_obj_invalidate(canvas);
}
void lv_canvas_draw_line(lv_obj_t * canvas, const lv_point_t points[], uint32_t point_cnt,
const lv_draw_line_dsc_t * draw_dsc)
{
LV_ASSERT_OBJ(canvas, MY_CLASS);
lv_img_dsc_t * dsc = lv_canvas_get_img(canvas);
if(dsc->header.cf >= LV_IMG_CF_INDEXED_1BIT && dsc->header.cf <= LV_IMG_CF_INDEXED_8BIT) {
LV_LOG_WARN("lv_canvas_draw_line: can't draw to LV_IMG_CF_INDEXED canvas");
return;
}
/*Create a dummy display to fool the lv_draw function.
*It will think it draws to real screen.*/
lv_area_t mask;
mask.x1 = 0;
mask.x2 = dsc->header.w - 1;
mask.y1 = 0;
mask.y2 = dsc->header.h - 1;
lv_disp_t disp;
/*Allocate the fake driver on the stack as the entire display doesn't outlive this function*/
lv_disp_drv_t driver;
lv_memset_00(&disp, sizeof(lv_disp_t));
disp.driver = &driver;
lv_disp_draw_buf_t draw_buf;
lv_disp_draw_buf_init(&draw_buf, (void *)dsc->data, NULL, dsc->header.w * dsc->header.h);
lv_area_copy(&draw_buf.area, &mask);
lv_disp_drv_init(disp.driver);
disp.driver->draw_buf = &draw_buf;
disp.driver->hor_res = dsc->header.w;
disp.driver->ver_res = dsc->header.h;
lv_disp_drv_use_generic_set_px_cb(disp.driver, dsc->header.cf);
/*Disable anti-aliasing if drawing with transparent color to chroma keyed canvas*/
lv_color_t ctransp = LV_COLOR_CHROMA_KEY;
if(dsc->header.cf == LV_IMG_CF_TRUE_COLOR_CHROMA_KEYED &&
draw_dsc->color.full == ctransp.full) {
disp.driver->antialiasing = 0;
}
lv_disp_t * refr_ori = _lv_refr_get_disp_refreshing();
_lv_refr_set_disp_refreshing(&disp);
uint32_t i;
for(i = 0; i < point_cnt - 1; i++) {
lv_draw_line(&points[i], &points[i + 1], &mask, draw_dsc);
}
_lv_refr_set_disp_refreshing(refr_ori);
lv_obj_invalidate(canvas);
}
void lv_canvas_draw_polygon(lv_obj_t * canvas, const lv_point_t points[], uint32_t point_cnt,
const lv_draw_rect_dsc_t * draw_dsc)
{
LV_ASSERT_OBJ(canvas, MY_CLASS);
lv_img_dsc_t * dsc = lv_canvas_get_img(canvas);
if(dsc->header.cf >= LV_IMG_CF_INDEXED_1BIT && dsc->header.cf <= LV_IMG_CF_INDEXED_8BIT) {
LV_LOG_WARN("lv_canvas_draw_polygon: can't draw to LV_IMG_CF_INDEXED canvas");
return;
}
/*Create a dummy display to fool the lv_draw function.
*It will think it draws to real screen.*/
lv_area_t mask;
mask.x1 = 0;
mask.x2 = dsc->header.w - 1;
mask.y1 = 0;
mask.y2 = dsc->header.h - 1;
lv_disp_t disp;
/*Allocate the fake driver on the stack as the entire display doesn't outlive this function*/
lv_disp_drv_t driver;
lv_memset_00(&disp, sizeof(lv_disp_t));
disp.driver = &driver;
lv_disp_draw_buf_t draw_buf;
lv_disp_draw_buf_init(&draw_buf, (void *)dsc->data, NULL, dsc->header.w * dsc->header.h);
lv_area_copy(&draw_buf.area, &mask);
lv_disp_drv_init(disp.driver);
disp.driver->draw_buf = &draw_buf;
disp.driver->hor_res = dsc->header.w;
disp.driver->ver_res = dsc->header.h;
lv_disp_drv_use_generic_set_px_cb(disp.driver, dsc->header.cf);
/*Disable anti-aliasing if drawing with transparent color to chroma keyed canvas*/
lv_color_t ctransp = LV_COLOR_CHROMA_KEY;
if(dsc->header.cf == LV_IMG_CF_TRUE_COLOR_CHROMA_KEYED &&
draw_dsc->bg_color.full == ctransp.full) {
disp.driver->antialiasing = 0;
}
lv_disp_t * refr_ori = _lv_refr_get_disp_refreshing();
_lv_refr_set_disp_refreshing(&disp);
lv_draw_polygon(points, point_cnt, &mask, draw_dsc);
_lv_refr_set_disp_refreshing(refr_ori);
lv_obj_invalidate(canvas);
}
void lv_canvas_draw_arc(lv_obj_t * canvas, lv_coord_t x, lv_coord_t y, lv_coord_t r, int32_t start_angle,
int32_t end_angle, const lv_draw_arc_dsc_t * draw_dsc)
{
#if LV_DRAW_COMPLEX
LV_ASSERT_OBJ(canvas, MY_CLASS);
lv_img_dsc_t * dsc = lv_canvas_get_img(canvas);
if(dsc->header.cf >= LV_IMG_CF_INDEXED_1BIT && dsc->header.cf <= LV_IMG_CF_INDEXED_8BIT) {
LV_LOG_WARN("lv_canvas_draw_arc: can't draw to LV_IMG_CF_INDEXED canvas");
return;
}
/*Create a dummy display to fool the lv_draw function.
*It will think it draws to real screen.*/
lv_area_t mask;
mask.x1 = 0;
mask.x2 = dsc->header.w - 1;
mask.y1 = 0;
mask.y2 = dsc->header.h - 1;
lv_disp_t disp;
/*Allocate the fake driver on the stack as the entire display doesn't outlive this function*/
lv_disp_drv_t driver;
lv_memset_00(&disp, sizeof(lv_disp_t));
disp.driver = &driver;
lv_disp_draw_buf_t draw_buf;
lv_disp_draw_buf_init(&draw_buf, (void *)dsc->data, NULL, dsc->header.w * dsc->header.h);
lv_area_copy(&draw_buf.area, &mask);
lv_disp_drv_init(disp.driver);
disp.driver->draw_buf = &draw_buf;
disp.driver->hor_res = dsc->header.w;
disp.driver->ver_res = dsc->header.h;
lv_disp_drv_use_generic_set_px_cb(disp.driver, dsc->header.cf);
/*Disable anti-aliasing if drawing with transparent color to chroma keyed canvas*/
lv_color_t ctransp = LV_COLOR_CHROMA_KEY;
if(dsc->header.cf == LV_IMG_CF_TRUE_COLOR_CHROMA_KEYED &&
draw_dsc->color.full == ctransp.full) {
disp.driver->antialiasing = 0;
}
lv_disp_t * refr_ori = _lv_refr_get_disp_refreshing();
_lv_refr_set_disp_refreshing(&disp);
lv_draw_arc(x, y, r, start_angle, end_angle, &mask, draw_dsc);
_lv_refr_set_disp_refreshing(refr_ori);
lv_obj_invalidate(canvas);
#else
LV_UNUSED(canvas);
LV_UNUSED(x);
LV_UNUSED(y);
LV_UNUSED(r);
LV_UNUSED(start_angle);
LV_UNUSED(end_angle);
LV_UNUSED(draw_dsc);
LV_LOG_WARN("Can't draw arc with LV_DRAW_COMPLEX == 0");
#endif
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_canvas_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_canvas_t * canvas = (lv_canvas_t *)obj;
canvas->dsc.header.always_zero = 0;
canvas->dsc.header.cf = LV_IMG_CF_TRUE_COLOR;
canvas->dsc.header.h = 0;
canvas->dsc.header.w = 0;
canvas->dsc.data_size = 0;
canvas->dsc.data = NULL;
lv_img_set_src(obj, &canvas->dsc);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_canvas_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_canvas_t * canvas = (lv_canvas_t *)obj;
lv_img_cache_invalidate_src(&canvas->dsc);
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_canvas.c | C | apache-2.0 | 29,581 |
/**
* @file lv_canvas.h
*
*/
#ifndef LV_CANVAS_H
#define LV_CANVAS_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_CANVAS != 0
#include "../core/lv_obj.h"
#include "../widgets/lv_img.h"
#include "../draw/lv_draw_img.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
extern const lv_obj_class_t lv_canvas_class;
/*Data of canvas*/
typedef struct {
lv_img_t img;
lv_img_dsc_t dsc;
} lv_canvas_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a canvas object
* @param parent pointer to an object, it will be the parent of the new canvas
* @return pointer to the created canvas
*/
lv_obj_t * lv_canvas_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set a buffer for the canvas.
* @param buf a buffer where the content of the canvas will be.
* The required size is (lv_img_color_format_get_px_size(cf) * w) / 8 * h)
* It can be allocated with `lv_mem_alloc()` or
* it can be statically allocated array (e.g. static lv_color_t buf[100*50]) or
* it can be an address in RAM or external SRAM
* @param canvas pointer to a canvas object
* @param w width of the canvas
* @param h height of the canvas
* @param cf color format. `LV_IMG_CF_...`
*/
void lv_canvas_set_buffer(lv_obj_t * canvas, void * buf, lv_coord_t w, lv_coord_t h, lv_img_cf_t cf);
/**
* Set the color of a pixel on the canvas
* @param canvas
* @param x x coordinate of the point to set
* @param y x coordinate of the point to set
* @param c color of the pixel
*/
void lv_canvas_set_px_color(lv_obj_t * canvas, lv_coord_t x, lv_coord_t y, lv_color_t c);
/**
* DEPRECATED: added only for backward compatibility
*/
static inline void lv_canvas_set_px(lv_obj_t * canvas, lv_coord_t x, lv_coord_t y, lv_color_t c)
{
lv_canvas_set_px_color(canvas, x, y, c);
}
/**
* Set the opacity of a pixel on the canvas
* @param canvas
* @param x x coordinate of the point to set
* @param y x coordinate of the point to set
* @param opa opacity of the pixel (0..255)
*/
void lv_canvas_set_px_opa(lv_obj_t * canvas, lv_coord_t x, lv_coord_t y, lv_opa_t opa);
/**
* Set the palette color of a canvas with index format. Valid only for `LV_IMG_CF_INDEXED1/2/4/8`
* @param canvas pointer to canvas object
* @param id the palette color to set:
* - for `LV_IMG_CF_INDEXED1`: 0..1
* - for `LV_IMG_CF_INDEXED2`: 0..3
* - for `LV_IMG_CF_INDEXED4`: 0..15
* - for `LV_IMG_CF_INDEXED8`: 0..255
* @param c the color to set
*/
void lv_canvas_set_palette(lv_obj_t * canvas, uint8_t id, lv_color_t c);
/*=====================
* Getter functions
*====================*/
/**
* Get the color of a pixel on the canvas
* @param canvas
* @param x x coordinate of the point to set
* @param y x coordinate of the point to set
* @return color of the point
*/
lv_color_t lv_canvas_get_px(lv_obj_t * canvas, lv_coord_t x, lv_coord_t y);
/**
* Get the image of the canvas as a pointer to an `lv_img_dsc_t` variable.
* @param canvas pointer to a canvas object
* @return pointer to the image descriptor.
*/
lv_img_dsc_t * lv_canvas_get_img(lv_obj_t * canvas);
/*=====================
* Other functions
*====================*/
/**
* Copy a buffer to the canvas
* @param canvas pointer to a canvas object
* @param to_copy buffer to copy. The color format has to match with the canvas's buffer color
* format
* @param x left side of the destination position
* @param y top side of the destination position
* @param w width of the buffer to copy
* @param h height of the buffer to copy
*/
void lv_canvas_copy_buf(lv_obj_t * canvas, const void * to_copy, lv_coord_t x, lv_coord_t y, lv_coord_t w,
lv_coord_t h);
/**
* Transform and image and store the result on a canvas.
* @param canvas pointer to a canvas object to store the result of the transformation.
* @param img pointer to an image descriptor to transform.
* Can be the image descriptor of an other canvas too (`lv_canvas_get_img()`).
* @param angle the angle of rotation (0..3600), 0.1 deg resolution
* @param zoom zoom factor (256 no zoom);
* @param offset_x offset X to tell where to put the result data on destination canvas
* @param offset_y offset X to tell where to put the result data on destination canvas
* @param pivot_x pivot X of rotation. Relative to the source canvas
* Set to `source width / 2` to rotate around the center
* @param pivot_y pivot Y of rotation. Relative to the source canvas
* Set to `source height / 2` to rotate around the center
* @param antialias apply anti-aliasing during the transformation. Looks better but slower.
*/
void lv_canvas_transform(lv_obj_t * canvas, lv_img_dsc_t * img, int16_t angle, uint16_t zoom, lv_coord_t offset_x,
lv_coord_t offset_y,
int32_t pivot_x, int32_t pivot_y, bool antialias);
/**
* Apply horizontal blur on the canvas
* @param canvas pointer to a canvas object
* @param area the area to blur. If `NULL` the whole canvas will be blurred.
* @param r radius of the blur
*/
void lv_canvas_blur_hor(lv_obj_t * canvas, const lv_area_t * area, uint16_t r);
/**
* Apply vertical blur on the canvas
* @param canvas pointer to a canvas object
* @param area the area to blur. If `NULL` the whole canvas will be blurred.
* @param r radius of the blur
*/
void lv_canvas_blur_ver(lv_obj_t * canvas, const lv_area_t * area, uint16_t r);
/**
* Fill the canvas with color
* @param canvas pointer to a canvas
* @param color the background color
* @param opa the desired opacity
*/
void lv_canvas_fill_bg(lv_obj_t * canvas, lv_color_t color, lv_opa_t opa);
/**
* Draw a rectangle on the canvas
* @param canvas pointer to a canvas object
* @param x left coordinate of the rectangle
* @param y top coordinate of the rectangle
* @param w width of the rectangle
* @param h height of the rectangle
* @param draw_dsc descriptor of the rectangle
*/
void lv_canvas_draw_rect(lv_obj_t * canvas, lv_coord_t x, lv_coord_t y, lv_coord_t w, lv_coord_t h,
const lv_draw_rect_dsc_t * draw_dsc);
/**
* Draw a text on the canvas.
* @param canvas pointer to a canvas object
* @param x left coordinate of the text
* @param y top coordinate of the text
* @param max_w max width of the text. The text will be wrapped to fit into this size
* @param draw_dsc pointer to a valid label descriptor `lv_draw_label_dsc_t`
* @param txt text to display
*/
void lv_canvas_draw_text(lv_obj_t * canvas, lv_coord_t x, lv_coord_t y, lv_coord_t max_w,
lv_draw_label_dsc_t * draw_dsc, const char * txt);
/**
* Draw an image on the canvas
* @param canvas pointer to a canvas object
* @param x left coordinate of the image
* @param y top coordinate of the image
* @param src image source. Can be a pointer an `lv_img_dsc_t` variable or a path an image.
* @param draw_dsc pointer to a valid label descriptor `lv_draw_img_dsc_t`
*/
void lv_canvas_draw_img(lv_obj_t * canvas, lv_coord_t x, lv_coord_t y, const void * src,
const lv_draw_img_dsc_t * draw_dsc);
/**
* Draw a line on the canvas
* @param canvas pointer to a canvas object
* @param points point of the line
* @param point_cnt number of points
* @param draw_dsc pointer to an initialized `lv_draw_line_dsc_t` variable
*/
void lv_canvas_draw_line(lv_obj_t * canvas, const lv_point_t points[], uint32_t point_cnt,
const lv_draw_line_dsc_t * draw_dsc);
/**
* Draw a polygon on the canvas
* @param canvas pointer to a canvas object
* @param points point of the polygon
* @param point_cnt number of points
* @param draw_dsc pointer to an initialized `lv_draw_rect_dsc_t` variable
*/
void lv_canvas_draw_polygon(lv_obj_t * canvas, const lv_point_t points[], uint32_t point_cnt,
const lv_draw_rect_dsc_t * draw_dsc);
/**
* Draw an arc on the canvas
* @param canvas pointer to a canvas object
* @param x origo x of the arc
* @param y origo y of the arc
* @param r radius of the arc
* @param start_angle start angle in degrees
* @param end_angle end angle in degrees
* @param draw_dsc pointer to an initialized `lv_draw_line_dsc_t` variable
*/
void lv_canvas_draw_arc(lv_obj_t * canvas, lv_coord_t x, lv_coord_t y, lv_coord_t r, int32_t start_angle,
int32_t end_angle, const lv_draw_arc_dsc_t * draw_dsc);
/**********************
* MACROS
**********************/
#define LV_CANVAS_BUF_SIZE_TRUE_COLOR(w, h) LV_IMG_BUF_SIZE_TRUE_COLOR(w, h)
#define LV_CANVAS_BUF_SIZE_TRUE_COLOR_CHROMA_KEYED(w, h) LV_IMG_BUF_SIZE_TRUE_COLOR_CHROMA_KEYED(w, h)
#define LV_CANVAS_BUF_SIZE_TRUE_COLOR_ALPHA(w, h) LV_IMG_BUF_SIZE_TRUE_COLOR_ALPHA(w, h)
/*+ 1: to be sure no fractional row*/
#define LV_CANVAS_BUF_SIZE_ALPHA_1BIT(w, h) LV_IMG_BUF_SIZE_ALPHA_1BIT(w, h)
#define LV_CANVAS_BUF_SIZE_ALPHA_2BIT(w, h) LV_IMG_BUF_SIZE_ALPHA_2BIT(w, h)
#define LV_CANVAS_BUF_SIZE_ALPHA_4BIT(w, h) LV_IMG_BUF_SIZE_ALPHA_4BIT(w, h)
#define LV_CANVAS_BUF_SIZE_ALPHA_8BIT(w, h) LV_IMG_BUF_SIZE_ALPHA_8BIT(w, h)
/*4 * X: for palette*/
#define LV_CANVAS_BUF_SIZE_INDEXED_1BIT(w, h) LV_IMG_BUF_SIZE_INDEXED_1BIT(w, h)
#define LV_CANVAS_BUF_SIZE_INDEXED_2BIT(w, h) LV_IMG_BUF_SIZE_INDEXED_2BIT(w, h)
#define LV_CANVAS_BUF_SIZE_INDEXED_4BIT(w, h) LV_IMG_BUF_SIZE_INDEXED_4BIT(w, h)
#define LV_CANVAS_BUF_SIZE_INDEXED_8BIT(w, h) LV_IMG_BUF_SIZE_INDEXED_8BIT(w, h)
#endif /*LV_USE_CANVAS*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_CANVAS_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_canvas.h | C | apache-2.0 | 9,907 |
/**
* @file lv_cb.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_checkbox.h"
#if LV_USE_CHECKBOX != 0
#include "../misc/lv_assert.h"
#include "../misc/lv_txt_ap.h"
#include "../core/lv_group.h"
#include "../draw/lv_draw.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_checkbox_class
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_checkbox_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_checkbox_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_checkbox_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void lv_checkbox_draw(lv_event_t * e);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_checkbox_class = {
.constructor_cb = lv_checkbox_constructor,
.destructor_cb = lv_checkbox_destructor,
.event_cb = lv_checkbox_event,
.width_def = LV_SIZE_CONTENT,
.height_def = LV_SIZE_CONTENT,
.group_def = LV_OBJ_CLASS_GROUP_DEF_TRUE,
.instance_size = sizeof(lv_checkbox_t),
.base_class = &lv_obj_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_checkbox_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*=====================
* Setter functions
*====================*/
void lv_checkbox_set_text(lv_obj_t * obj, const char * txt)
{
lv_checkbox_t * cb = (lv_checkbox_t *)obj;
#if LV_USE_ARABIC_PERSIAN_CHARS
size_t len = _lv_txt_ap_calc_bytes_cnt(txt);
#else
size_t len = strlen(txt);
#endif
if(!cb->static_txt) cb->txt = lv_mem_realloc(cb->txt, len + 1);
else cb->txt = lv_mem_alloc(len + 1);
#if LV_USE_ARABIC_PERSIAN_CHARS
_lv_txt_ap_proc(txt, cb->txt);
#else
strcpy(cb->txt, txt);
#endif
cb->static_txt = 0;
lv_obj_refresh_self_size(obj);
lv_obj_invalidate(obj);
}
void lv_checkbox_set_text_static(lv_obj_t * obj, const char * txt)
{
lv_checkbox_t * cb = (lv_checkbox_t *)obj;
if(!cb->static_txt) lv_mem_free(cb->txt);
cb->txt = (char *)txt;
cb->static_txt = 1;
lv_obj_refresh_self_size(obj);
lv_obj_invalidate(obj);
}
/*=====================
* Getter functions
*====================*/
const char * lv_checkbox_get_text(const lv_obj_t * obj)
{
lv_checkbox_t * cb = (lv_checkbox_t *)obj;
return cb->txt;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_checkbox_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_checkbox_t * cb = (lv_checkbox_t *)obj;
cb->txt = "Check box";
cb->static_txt = 1;
lv_obj_add_flag(obj, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_flag(obj, LV_OBJ_FLAG_CHECKABLE);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_checkbox_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_checkbox_t * cb = (lv_checkbox_t *)obj;
if(!cb->static_txt) {
lv_mem_free(cb->txt);
cb->txt = NULL;
}
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_checkbox_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
if(code == LV_EVENT_PRESSED || code == LV_EVENT_RELEASED) {
lv_obj_invalidate(obj);
}
else if(code == LV_EVENT_GET_SELF_SIZE) {
lv_point_t * p = lv_event_get_param(e);
lv_checkbox_t * cb = (lv_checkbox_t *)obj;
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t font_h = lv_font_get_line_height(font);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_coord_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_MAIN);
lv_point_t txt_size;
lv_txt_get_size(&txt_size, cb->txt, font, letter_space, line_space, LV_COORD_MAX, LV_TEXT_FLAG_NONE);
lv_coord_t bg_colp = lv_obj_get_style_pad_column(obj, LV_PART_MAIN);
lv_coord_t marker_leftp = lv_obj_get_style_pad_left(obj, LV_PART_INDICATOR);
lv_coord_t marker_rightp = lv_obj_get_style_pad_right(obj, LV_PART_INDICATOR);
lv_coord_t marker_topp = lv_obj_get_style_pad_top(obj, LV_PART_INDICATOR);
lv_coord_t marker_bottomp = lv_obj_get_style_pad_bottom(obj, LV_PART_INDICATOR);
lv_point_t marker_size;
marker_size.x = font_h + marker_leftp + marker_rightp;
marker_size.y = font_h + marker_topp + marker_bottomp;
p->x = marker_size.x + txt_size.x + bg_colp;
p->y = LV_MAX(marker_size.y, txt_size.y);
}
else if(code == LV_EVENT_REFR_EXT_DRAW_SIZE) {
lv_coord_t * s = lv_event_get_param(e);
lv_coord_t m = lv_obj_calculate_ext_draw_size(obj, LV_PART_INDICATOR);
*s = LV_MAX(*s, m);
}
else if(code == LV_EVENT_RELEASED) {
uint32_t v = lv_obj_get_state(obj) & LV_STATE_CHECKED ? 1 : 0;
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, &v);
if(res != LV_RES_OK) return;
lv_obj_invalidate(obj);
}
else if(code == LV_EVENT_DRAW_MAIN) {
lv_checkbox_draw(e);
}
}
static void lv_checkbox_draw(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_checkbox_t * cb = (lv_checkbox_t *)obj;
const lv_area_t * clip_area = lv_event_get_param(e);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t font_h = lv_font_get_line_height(font);
lv_coord_t bg_border = lv_obj_get_style_border_width(obj, LV_PART_MAIN);
lv_coord_t bg_topp = lv_obj_get_style_pad_top(obj, LV_PART_MAIN) + bg_border;
lv_coord_t bg_leftp = lv_obj_get_style_pad_left(obj, LV_PART_MAIN) + bg_border;
lv_coord_t bg_colp = lv_obj_get_style_pad_column(obj, LV_PART_MAIN);
lv_coord_t marker_leftp = lv_obj_get_style_pad_left(obj, LV_PART_INDICATOR);
lv_coord_t marker_rightp = lv_obj_get_style_pad_right(obj, LV_PART_INDICATOR);
lv_coord_t marker_topp = lv_obj_get_style_pad_top(obj, LV_PART_INDICATOR);
lv_coord_t marker_bottomp = lv_obj_get_style_pad_bottom(obj, LV_PART_INDICATOR);
lv_coord_t transf_w = lv_obj_get_style_transform_width(obj, LV_PART_INDICATOR);
lv_coord_t transf_h = lv_obj_get_style_transform_height(obj, LV_PART_INDICATOR);
lv_draw_rect_dsc_t indic_dsc;
lv_draw_rect_dsc_init(&indic_dsc);
lv_obj_init_draw_rect_dsc(obj, LV_PART_INDICATOR, &indic_dsc);
lv_area_t marker_area;
marker_area.x1 = obj->coords.x1 + bg_leftp;
marker_area.x2 = marker_area.x1 + font_h + marker_leftp + marker_rightp - 1;
marker_area.y1 = obj->coords.y1 + bg_topp;
marker_area.y2 = marker_area.y1 + font_h + marker_topp + marker_bottomp - 1;
lv_area_t marker_area_transf;
lv_area_copy(&marker_area_transf, &marker_area);
marker_area_transf.x1 -= transf_w;
marker_area_transf.x2 += transf_w;
marker_area_transf.y1 -= transf_h;
marker_area_transf.y2 += transf_h;
lv_obj_draw_part_dsc_t part_draw_dsc;
lv_obj_draw_dsc_init(&part_draw_dsc, clip_area);
part_draw_dsc.rect_dsc = &indic_dsc;
part_draw_dsc.class_p = MY_CLASS;
part_draw_dsc.type = LV_CHECKBOX_DRAW_PART_BOX;
part_draw_dsc.draw_area = &marker_area_transf;
part_draw_dsc.part = LV_PART_INDICATOR;
lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_draw_dsc);
lv_draw_rect(&marker_area_transf, clip_area, &indic_dsc);
lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_draw_dsc);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_coord_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_MAIN);
lv_point_t txt_size;
lv_txt_get_size(&txt_size, cb->txt, font, letter_space, line_space, LV_COORD_MAX, LV_TEXT_FLAG_NONE);
lv_draw_label_dsc_t txt_dsc;
lv_draw_label_dsc_init(&txt_dsc);
lv_obj_init_draw_label_dsc(obj, LV_PART_MAIN, &txt_dsc);
lv_coord_t y_ofs = (lv_area_get_height(&marker_area) - font_h) / 2;
lv_area_t txt_area;
txt_area.x1 = marker_area.x2 + bg_colp;
txt_area.x2 = txt_area.x1 + txt_size.x;
txt_area.y1 = obj->coords.y1 + bg_topp + y_ofs;
txt_area.y2 = txt_area.y1 + txt_size.y;
lv_draw_label(&txt_area, clip_area, &txt_dsc, cb->txt, NULL);
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_checkbox.c | C | apache-2.0 | 8,869 |
/**
* @file lv_cb.h
*
*/
#ifndef LV_CHECKBOX_H
#define LV_CHECKBOX_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#include "../core/lv_obj.h"
#if LV_USE_CHECKBOX != 0
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_obj_t obj;
char * txt;
uint32_t static_txt : 1;
} lv_checkbox_t;
extern const lv_obj_class_t lv_checkbox_class;
/**
* `type` field in `lv_obj_draw_part_dsc_t` if `class_p = lv_checkbox_class`
* Used in `LV_EVENT_DRAW_PART_BEGIN` and `LV_EVENT_DRAW_PART_END`
*/
typedef enum {
LV_CHECKBOX_DRAW_PART_BOX, /**< The tick box*/
} lv_checkbox_draw_part_type_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a check box object
* @param parent pointer to an object, it will be the parent of the new button
* @return pointer to the created check box
*/
lv_obj_t * lv_checkbox_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set the text of a check box. `txt` will be copied and may be deallocated
* after this function returns.
* @param cb pointer to a check box
* @param txt the text of the check box. NULL to refresh with the current text.
*/
void lv_checkbox_set_text(lv_obj_t * obj, const char * txt);
/**
* Set the text of a check box. `txt` must not be deallocated during the life
* of this checkbox.
* @param cb pointer to a check box
* @param txt the text of the check box.
*/
void lv_checkbox_set_text_static(lv_obj_t * obj, const char * txt);
/*=====================
* Getter functions
*====================*/
/**
* Get the text of a check box
* @param cb pointer to check box object
* @return pointer to the text of the check box
*/
const char * lv_checkbox_get_text(const lv_obj_t * obj);
/**********************
* MACROS
**********************/
#endif /*LV_USE_CHECKBOX*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_CHECKBOX_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_checkbox.h | C | apache-2.0 | 2,144 |
/**
* @file lv_dropdown.c
*
*/
/*********************
* INCLUDES
*********************/
#include "../core/lv_obj.h"
#include "lv_dropdown.h"
#if LV_USE_DROPDOWN != 0
#include "../misc/lv_assert.h"
#include "../draw/lv_draw.h"
#include "../core/lv_group.h"
#include "../core/lv_indev.h"
#include "../core/lv_disp.h"
#include "../font/lv_symbol_def.h"
#include "../misc/lv_anim.h"
#include "../misc/lv_math.h"
#include "../misc/lv_txt_ap.h"
#include <string.h>
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_dropdown_class
#define MY_CLASS_LIST &lv_dropdownlist_class
#define LV_DROPDOWN_PR_NONE 0xFFFF
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static lv_obj_t * lv_dropdown_list_create(lv_obj_t * parent);
static void lv_dropdown_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_dropdown_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_dropdown_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void draw_main(lv_event_t * e);
static void lv_dropdownlist_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_dropdownlist_destructor(const lv_obj_class_t * class_p, lv_obj_t * list_obj);
static void lv_dropdown_list_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void draw_list(lv_event_t * e);
static void draw_box(lv_obj_t * dropdown_obj, const lv_area_t * clip_area, uint16_t id, lv_state_t state);
static void draw_box_label(lv_obj_t * dropdown_obj, const lv_area_t * clip_area, uint16_t id, lv_state_t state);
static lv_res_t btn_release_handler(lv_obj_t * obj);
static lv_res_t list_release_handler(lv_obj_t * list_obj);
static void list_press_handler(lv_obj_t * page);
static uint16_t get_id_on_point(lv_obj_t * dropdown_obj, lv_coord_t y);
static void position_to_selected(lv_obj_t * obj);
static lv_obj_t * get_label(const lv_obj_t * obj);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_dropdown_class = {
.constructor_cb = lv_dropdown_constructor,
.destructor_cb = lv_dropdown_destructor,
.event_cb = lv_dropdown_event,
.width_def = LV_DPI_DEF,
.height_def = LV_SIZE_CONTENT,
.instance_size = sizeof(lv_dropdown_t),
.editable = LV_OBJ_CLASS_EDITABLE_TRUE,
.group_def = LV_OBJ_CLASS_GROUP_DEF_TRUE,
.base_class = &lv_obj_class
};
const lv_obj_class_t lv_dropdownlist_class = {
.constructor_cb = lv_dropdownlist_constructor,
.destructor_cb = lv_dropdownlist_destructor,
.event_cb = lv_dropdown_list_event,
.instance_size = sizeof(lv_dropdown_list_t),
.base_class = &lv_obj_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_dropdown_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(&lv_dropdown_class, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*=====================
* Setter functions
*====================*/
void lv_dropdown_set_text(lv_obj_t * obj, const char * txt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
if(dropdown->text == txt) return;
dropdown->text = txt;
lv_obj_invalidate(obj);
}
void lv_dropdown_set_options(lv_obj_t * obj, const char * options)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(options);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
/*Count the '\n'-s to determine the number of options*/
dropdown->option_cnt = 0;
uint32_t i;
for(i = 0; options[i] != '\0'; i++) {
if(options[i] == '\n') dropdown->option_cnt++;
}
dropdown->option_cnt++; /*Last option has no `\n`*/
dropdown->sel_opt_id = 0;
dropdown->sel_opt_id_orig = 0;
/*Allocate space for the new text*/
#if LV_USE_ARABIC_PERSIAN_CHARS == 0
size_t len = strlen(options) + 1;
#else
size_t len = _lv_txt_ap_calc_bytes_cnt(options) + 1;
#endif
if(dropdown->options != NULL && dropdown->static_txt == 0) {
lv_mem_free(dropdown->options);
dropdown->options = NULL;
}
dropdown->options = lv_mem_alloc(len);
LV_ASSERT_MALLOC(dropdown->options);
if(dropdown->options == NULL) return;
#if LV_USE_ARABIC_PERSIAN_CHARS == 0
strcpy(dropdown->options, options);
#else
_lv_txt_ap_proc(options, dropdown->options);
#endif
/*Now the text is dynamically allocated*/
dropdown->static_txt = 0;
lv_obj_invalidate(obj);
if(dropdown->list) lv_obj_invalidate(dropdown->list);
}
void lv_dropdown_set_options_static(lv_obj_t * obj, const char * options)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(options);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
/*Count the '\n'-s to determine the number of options*/
dropdown->option_cnt = 0;
uint32_t i;
for(i = 0; options[i] != '\0'; i++) {
if(options[i] == '\n') dropdown->option_cnt++;
}
dropdown->option_cnt++; /*Last option has no `\n`*/
dropdown->sel_opt_id = 0;
dropdown->sel_opt_id_orig = 0;
if(dropdown->static_txt == 0 && dropdown->options != NULL) {
lv_mem_free(dropdown->options);
dropdown->options = NULL;
}
dropdown->static_txt = 1;
dropdown->options = (char *)options;
lv_obj_invalidate(obj);
if(dropdown->list) lv_obj_invalidate(dropdown->list);
}
void lv_dropdown_add_option(lv_obj_t * obj, const char * option, uint32_t pos)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(option);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
/*Convert static options to dynamic*/
if(dropdown->static_txt != 0) {
char * static_options = dropdown->options;
size_t len = strlen(static_options) + 1;
dropdown->options = lv_mem_alloc(len);
LV_ASSERT_MALLOC(dropdown->options);
if(dropdown->options == NULL) return;
strcpy(dropdown->options, static_options);
dropdown->static_txt = 0;
}
/*Allocate space for the new option*/
size_t old_len = (dropdown->options == NULL) ? 0 : strlen(dropdown->options);
#if LV_USE_ARABIC_PERSIAN_CHARS == 0
size_t ins_len = strlen(option) + 1;
#else
size_t ins_len = _lv_txt_ap_calc_bytes_cnt(option) + 1;
#endif
size_t new_len = ins_len + old_len + 2; /*+2 for terminating NULL and possible \n*/
dropdown->options = lv_mem_realloc(dropdown->options, new_len + 1);
LV_ASSERT_MALLOC(dropdown->options);
if(dropdown->options == NULL) return;
dropdown->options[old_len] = '\0';
/*Find the insert character position*/
uint32_t insert_pos = old_len;
if(pos != LV_DROPDOWN_POS_LAST) {
uint32_t opcnt = 0;
for(insert_pos = 0; dropdown->options[insert_pos] != 0; insert_pos++) {
if(opcnt == pos)
break;
if(dropdown->options[insert_pos] == '\n')
opcnt++;
}
}
/*Add delimiter to existing options*/
if((insert_pos > 0) && (pos >= dropdown->option_cnt))
_lv_txt_ins(dropdown->options, _lv_txt_encoded_get_char_id(dropdown->options, insert_pos++), "\n");
/*Insert the new option, adding \n if necessary*/
char * ins_buf = lv_mem_buf_get(ins_len + 2); /*+ 2 for terminating NULL and possible \n*/
LV_ASSERT_MALLOC(ins_buf);
if(ins_buf == NULL) return;
#if LV_USE_ARABIC_PERSIAN_CHARS == 0
strcpy(ins_buf, option);
#else
_lv_txt_ap_proc(option, ins_buf);
#endif
if(pos < dropdown->option_cnt) strcat(ins_buf, "\n");
_lv_txt_ins(dropdown->options, _lv_txt_encoded_get_char_id(dropdown->options, insert_pos), ins_buf);
lv_mem_buf_release(ins_buf);
dropdown->option_cnt++;
lv_obj_invalidate(obj);
if(dropdown->list) lv_obj_invalidate(dropdown->list);
}
void lv_dropdown_clear_options(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
if(dropdown->options == NULL) return;
if(dropdown->static_txt == 0)
lv_mem_free(dropdown->options);
dropdown->options = NULL;
dropdown->static_txt = 0;
dropdown->option_cnt = 0;
lv_obj_invalidate(obj);
if(dropdown->list) lv_obj_invalidate(dropdown->list);
}
void lv_dropdown_set_selected(lv_obj_t * obj, uint16_t sel_opt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
if(dropdown->sel_opt_id == sel_opt) return;
dropdown->sel_opt_id = sel_opt < dropdown->option_cnt ? sel_opt : dropdown->option_cnt - 1;
dropdown->sel_opt_id_orig = dropdown->sel_opt_id;
lv_obj_invalidate(obj);
}
void lv_dropdown_set_dir(lv_obj_t * obj, lv_dir_t dir)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
if(dropdown->dir == dir) return;
dropdown->dir = dir;
lv_obj_invalidate(obj);
}
void lv_dropdown_set_symbol(lv_obj_t * obj, const void * symbol)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
dropdown->symbol = symbol;
lv_obj_invalidate(obj);
}
void lv_dropdown_set_selected_highlight(lv_obj_t * obj, bool en)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
dropdown->selected_highlight = en;
if(dropdown->list) lv_obj_invalidate(dropdown->list);
}
/*=====================
* Getter functions
*====================*/
lv_obj_t * lv_dropdown_get_list(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
return dropdown->list;
}
const char * lv_dropdown_get_text(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
return dropdown->text;
}
const char * lv_dropdown_get_options(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
return dropdown->options == NULL ? "" : dropdown->options;
}
uint16_t lv_dropdown_get_selected(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
return dropdown->sel_opt_id;
}
uint16_t lv_dropdown_get_option_cnt(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
return dropdown->option_cnt;
}
void lv_dropdown_get_selected_str(const lv_obj_t * obj, char * buf, uint32_t buf_size)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
uint32_t i;
uint32_t line = 0;
size_t txt_len = strlen(dropdown->options);
for(i = 0; i < txt_len && line != dropdown->sel_opt_id_orig; i++) {
if(dropdown->options[i] == '\n') line++;
}
uint32_t c;
for(c = 0; i < txt_len && dropdown->options[i] != '\n'; c++, i++) {
if(buf_size && c >= buf_size - 1) {
LV_LOG_WARN("lv_dropdown_get_selected_str: the buffer was too small");
break;
}
buf[c] = dropdown->options[i];
}
buf[c] = '\0';
}
const char * lv_dropdown_get_symbol(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
return dropdown->symbol;
}
bool lv_dropdown_get_selected_highlight(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
return dropdown->selected_highlight;
}
lv_dir_t lv_dropdown_get_dir(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
return dropdown->dir;
}
/*=====================
* Other functions
*====================*/
void lv_dropdown_open(lv_obj_t * dropdown_obj)
{
lv_dropdown_t * dropdown = (lv_dropdown_t *)dropdown_obj;
lv_obj_add_state(dropdown_obj, LV_STATE_CHECKED);
if(dropdown->list == NULL) {
lv_obj_t * list_obj = lv_dropdown_list_create(lv_obj_get_screen(dropdown_obj));
((lv_dropdown_list_t *) list_obj)->dropdown = dropdown_obj;
dropdown->list = list_obj;
lv_obj_clear_flag(dropdown->list, LV_OBJ_FLAG_CLICK_FOCUSABLE);
lv_obj_add_flag(dropdown->list, LV_OBJ_FLAG_IGNORE_LAYOUT);
lv_obj_update_layout(dropdown->list);
}
/*To allow styling the list*/
lv_event_send(dropdown_obj, LV_EVENT_READY, NULL);
lv_obj_t * label = get_label(dropdown_obj);
lv_label_set_text_static(label, dropdown->options);
lv_obj_set_width(dropdown->list, LV_SIZE_CONTENT);
lv_obj_update_layout(label);
/*Set smaller width to the width of the button*/
if(lv_obj_get_width(dropdown->list) <= lv_obj_get_width(dropdown_obj) &&
(dropdown->dir == LV_DIR_TOP || dropdown->dir == LV_DIR_BOTTOM)) {
lv_obj_set_width(dropdown->list, lv_obj_get_width(dropdown_obj));
}
lv_coord_t label_h = lv_obj_get_height(label);
lv_coord_t border_width = lv_obj_get_style_border_width(dropdown->list, LV_PART_MAIN);
lv_coord_t top = lv_obj_get_style_pad_top(dropdown->list, LV_PART_MAIN) + border_width;
lv_coord_t bottom = lv_obj_get_style_pad_bottom(dropdown->list, LV_PART_MAIN) + border_width;
lv_coord_t list_fit_h = label_h + top + bottom;
lv_coord_t list_h = list_fit_h;
lv_dir_t dir = dropdown->dir;
/*No space on the bottom? See if top is better.*/
if(dropdown->dir == LV_DIR_BOTTOM) {
if(dropdown_obj->coords.y2 + list_h > LV_VER_RES) {
if(dropdown_obj->coords.y1 > LV_VER_RES - dropdown_obj->coords.y2) {
/*There is more space on the top, so make it drop up*/
dir = LV_DIR_TOP;
list_h = dropdown_obj->coords.y1 - 1;
}
else {
list_h = LV_VER_RES - dropdown_obj->coords.y2 - 1 ;
}
}
}
/*No space on the top? See if bottom is better.*/
else if(dropdown->dir == LV_DIR_TOP) {
if(dropdown_obj->coords.y1 - list_h < 0) {
if(dropdown_obj->coords.y1 < LV_VER_RES - dropdown_obj->coords.y2) {
/*There is more space on the top, so make it drop up*/
dir = LV_DIR_BOTTOM;
list_h = LV_VER_RES - dropdown_obj->coords.y2;
}
else {
list_h = dropdown_obj->coords.y1;
}
}
}
if(list_h > list_fit_h) list_h = list_fit_h;
lv_obj_set_height(dropdown->list, list_h);
position_to_selected(dropdown_obj);
if(dir == LV_DIR_BOTTOM) lv_obj_align_to(dropdown->list, dropdown_obj, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 0);
else if(dir == LV_DIR_TOP) lv_obj_align_to(dropdown->list, dropdown_obj, LV_ALIGN_OUT_TOP_LEFT, 0, 0);
else if(dir == LV_DIR_LEFT) lv_obj_align_to(dropdown->list, dropdown_obj, LV_ALIGN_OUT_LEFT_TOP, 0, 0);
else if(dir == LV_DIR_RIGHT) lv_obj_align_to(dropdown->list, dropdown_obj, LV_ALIGN_OUT_RIGHT_TOP, 0, 0);
lv_obj_update_layout(dropdown->list);
if(dropdown->dir == LV_DIR_LEFT || dropdown->dir == LV_DIR_RIGHT) {
lv_coord_t y1 = lv_obj_get_y(dropdown->list);
lv_coord_t y2 = lv_obj_get_y2(dropdown->list);
if(y2 >= LV_VER_RES) {
lv_obj_set_y(dropdown->list, y1 - (y2 - LV_VER_RES) - 1);
}
}
lv_text_align_t align = lv_obj_calculate_style_text_align(label, LV_PART_MAIN, dropdown->options);
switch(align) {
default:
case LV_TEXT_ALIGN_LEFT:
lv_obj_align(label, LV_ALIGN_TOP_LEFT, 0, 0);
break;
case LV_TEXT_ALIGN_RIGHT:
lv_obj_align(label, LV_ALIGN_TOP_RIGHT, 0, 0);
break;
case LV_TEXT_ALIGN_CENTER:
lv_obj_align(label, LV_ALIGN_CENTER, 0, 0);
break;
}
}
void lv_dropdown_close(lv_obj_t * obj)
{
lv_obj_clear_state(obj, LV_STATE_CHECKED);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
dropdown->pr_opt_id = LV_DROPDOWN_PR_NONE;
if(dropdown->list) lv_obj_del(dropdown->list);
lv_event_send(obj, LV_EVENT_CANCEL, NULL);
}
/**********************
* STATIC FUNCTIONS
**********************/
static lv_obj_t * lv_dropdown_list_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(&lv_dropdownlist_class, parent);
lv_obj_class_init_obj(obj);
return obj;
}
static void lv_dropdown_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
/*Initialize the allocated 'ext'*/
dropdown->list = NULL;
dropdown->options = NULL;
dropdown->symbol = LV_SYMBOL_DOWN;
dropdown->text = NULL;
dropdown->static_txt = 1;
dropdown->selected_highlight = 1;
dropdown->sel_opt_id = 0;
dropdown->sel_opt_id_orig = 0;
dropdown->pr_opt_id = LV_DROPDOWN_PR_NONE;
dropdown->option_cnt = 0;
dropdown->dir = LV_DIR_BOTTOM;
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
lv_dropdown_set_options_static(obj, "Option 1\nOption 2\nOption 3");
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_dropdown_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
if(dropdown->list) {
lv_obj_del(dropdown->list);
dropdown->list = NULL;
}
if(!dropdown->static_txt) {
lv_mem_free(dropdown->options);
dropdown->options = NULL;
}
}
static void lv_dropdownlist_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
lv_label_create(obj);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_dropdownlist_destructor(const lv_obj_class_t * class_p, lv_obj_t * list_obj)
{
LV_UNUSED(class_p);
lv_dropdown_list_t * list = (lv_dropdown_list_t *)list_obj;
lv_obj_t * dropdown_obj = list->dropdown;
lv_dropdown_t * dropdown = (lv_dropdown_t *)dropdown_obj;
dropdown->list = NULL;
}
static void lv_dropdown_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
if(code == LV_EVENT_FOCUSED) {
lv_group_t * g = lv_obj_get_group(obj);
bool editing = lv_group_get_editing(g);
lv_indev_type_t indev_type = lv_indev_get_type(lv_indev_get_act());
/*Encoders need special handling*/
if(indev_type == LV_INDEV_TYPE_ENCODER) {
/*Open the list if editing*/
if(editing) {
lv_dropdown_open(obj);
}
/*Close the list if navigating*/
else {
dropdown->sel_opt_id = dropdown->sel_opt_id_orig;
lv_dropdown_close(obj);
}
}
}
else if(code == LV_EVENT_DEFOCUSED || code == LV_EVENT_LEAVE) {
lv_dropdown_close(obj);
}
else if(code == LV_EVENT_RELEASED) {
res = btn_release_handler(obj);
if(res != LV_RES_OK) return;
}
else if(code == LV_EVENT_STYLE_CHANGED) {
lv_obj_refresh_self_size(obj);
}
else if(code == LV_EVENT_SIZE_CHANGED) {
lv_obj_refresh_self_size(obj);
}
else if(code == LV_EVENT_GET_SELF_SIZE) {
lv_point_t * p = lv_event_get_param(e);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
p->y = lv_font_get_line_height(font);
}
else if(code == LV_EVENT_KEY) {
char c = *((char *)lv_event_get_param(e));
if(c == LV_KEY_RIGHT || c == LV_KEY_DOWN) {
if(dropdown->list == NULL) {
lv_dropdown_open(obj);
}
else if(dropdown->sel_opt_id + 1 < dropdown->option_cnt) {
dropdown->sel_opt_id++;
position_to_selected(obj);
}
}
else if(c == LV_KEY_LEFT || c == LV_KEY_UP) {
if(dropdown->list == NULL) {
lv_dropdown_open(obj);
}
else if(dropdown->sel_opt_id > 0) {
dropdown->sel_opt_id--;
position_to_selected(obj);
}
}
else if(c == LV_KEY_ESC) {
dropdown->sel_opt_id = dropdown->sel_opt_id_orig;
lv_dropdown_close(obj);
}
else if(c == LV_KEY_ENTER) {
/* Handle the ENTER key only if it was send by an other object.
* Do no process it if ENTER is sent by the dropdown becasue it's handled in LV_EVENT_RELEASED */
lv_obj_t * indev_obj = lv_indev_get_obj_act();
if(indev_obj != obj) {
res = btn_release_handler(obj);
if(res != LV_RES_OK) return;
}
}
}
else if(code == LV_EVENT_DRAW_MAIN) {
draw_main(e);
}
}
static void lv_dropdown_list_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
lv_event_code_t code = lv_event_get_code(e);
if(code != LV_EVENT_DRAW_POST) {
res = lv_obj_event_base(MY_CLASS_LIST, e);
if(res != LV_RES_OK) return;
}
lv_obj_t * list = lv_event_get_target(e);
lv_obj_t * dropdown_obj = ((lv_dropdown_list_t *)list)->dropdown;
lv_dropdown_t * dropdown = (lv_dropdown_t *)dropdown_obj;
if(code == LV_EVENT_RELEASED) {
if(lv_indev_get_scroll_obj(lv_indev_get_act()) == NULL) {
list_release_handler(list);
}
}
else if(code == LV_EVENT_PRESSED) {
list_press_handler(list);
}
else if(code == LV_EVENT_SCROLL_BEGIN) {
dropdown->pr_opt_id = LV_DROPDOWN_PR_NONE;
lv_obj_invalidate(list);
}
else if(code == LV_EVENT_DRAW_POST) {
draw_list(e);
res = lv_obj_event_base(MY_CLASS_LIST, e);
if(res != LV_RES_OK) return;
}
}
static void draw_main(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
const lv_area_t * clip_area = lv_event_get_param(e);
lv_coord_t border_width = lv_obj_get_style_border_width(obj, LV_PART_MAIN);
lv_coord_t left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN) + border_width;
lv_coord_t right = lv_obj_get_style_pad_right(obj, LV_PART_MAIN) + border_width;
lv_coord_t top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN) + border_width;
lv_draw_label_dsc_t symbol_dsc;
lv_draw_label_dsc_init(&symbol_dsc);
lv_obj_init_draw_label_dsc(obj, LV_PART_INDICATOR, &symbol_dsc);
/*If no text specified use the selected option*/
const char * opt_txt;
if(dropdown->text) opt_txt = dropdown->text;
else {
char * buf = lv_mem_buf_get(128);
lv_dropdown_get_selected_str(obj, buf, 128);
opt_txt = buf;
}
bool symbol_to_left = false;
if(dropdown->dir == LV_DIR_LEFT) symbol_to_left = true;
if(lv_obj_get_style_base_dir(obj, LV_PART_MAIN) == LV_BASE_DIR_RTL) symbol_to_left = true;
if(dropdown->symbol) {
lv_img_src_t symbol_type = lv_img_src_get_type(dropdown->symbol);
lv_coord_t symbol_w;
lv_coord_t symbol_h;
if(symbol_type == LV_IMG_SRC_SYMBOL) {
lv_point_t size;
lv_txt_get_size(&size, dropdown->symbol, symbol_dsc.font, symbol_dsc.letter_space, symbol_dsc.line_space, LV_COORD_MAX,
symbol_dsc.flag);
symbol_w = size.x;
symbol_h = size.y;
}
else {
lv_img_header_t header;
lv_res_t res = lv_img_decoder_get_info(dropdown->symbol, &header);
if(res == LV_RES_OK) {
symbol_w = header.w;
symbol_h = header.h;
}
else {
symbol_w = -1;
symbol_h = -1;
}
}
lv_area_t symbol_area;
if(symbol_to_left) {
symbol_area.x1 = obj->coords.x1 + left;
symbol_area.x2 = symbol_area.x1 + symbol_w - 1;
}
else {
symbol_area.x1 = obj->coords.x2 - right - symbol_w;
symbol_area.x2 = symbol_area.x1 + symbol_w - 1;
}
if(symbol_type == LV_IMG_SRC_SYMBOL) {
symbol_area.y1 = obj->coords.y1 + top;
symbol_area.y2 = symbol_area.y1 + symbol_h - 1;
lv_draw_label(&symbol_area, clip_area, &symbol_dsc, dropdown->symbol, NULL);
}
else {
symbol_area.y1 = obj->coords.y1 + (lv_obj_get_height(obj) - symbol_h) / 2;
symbol_area.y2 = symbol_area.y1 + symbol_h - 1;
lv_draw_img_dsc_t img_dsc;
lv_draw_img_dsc_init(&img_dsc);
lv_obj_init_draw_img_dsc(obj, LV_PART_INDICATOR, &img_dsc);
img_dsc.pivot.x = symbol_w / 2;
img_dsc.pivot.y = symbol_h / 2;
img_dsc.angle = lv_obj_get_style_transform_angle(obj, LV_PART_INDICATOR);
lv_draw_img(&symbol_area, clip_area, dropdown->symbol, &img_dsc);
}
}
lv_draw_label_dsc_t label_dsc;
lv_draw_label_dsc_init(&label_dsc);
lv_obj_init_draw_label_dsc(obj, LV_PART_MAIN, &label_dsc);
lv_point_t size;
lv_txt_get_size(&size, opt_txt, label_dsc.font, label_dsc.letter_space, label_dsc.line_space, LV_COORD_MAX,
label_dsc.flag);
lv_area_t txt_area;
txt_area.y1 = obj->coords.y1 + top;
txt_area.y2 = txt_area.y1 + size.y;
/*Center align the text if no symbol*/
if(dropdown->symbol == NULL) {
txt_area.x1 = obj->coords.x1 + (lv_obj_get_width(obj) - size.x) / 2;
txt_area.x2 = txt_area.x1 + size.x;
}
else {
/*Text to the right*/
if(symbol_to_left) {
txt_area.x1 = obj->coords.x2 - right - size.x;
txt_area.x2 = txt_area.x1 + size.x;
}
else {
txt_area.x1 = obj->coords.x1 + left;
txt_area.x2 = txt_area.x1 + size.x;
}
}
lv_draw_label(&txt_area, clip_area, &label_dsc, opt_txt, NULL);
if(dropdown->text == NULL) {
lv_mem_buf_release((char *)opt_txt);
}
}
static void draw_list(lv_event_t * e)
{
lv_obj_t * list_obj = lv_event_get_target(e);
lv_dropdown_list_t * list = (lv_dropdown_list_t *)list_obj;
lv_obj_t * dropdown_obj = list->dropdown;
lv_dropdown_t * dropdown = (lv_dropdown_t *)dropdown_obj;
const lv_area_t * clip_area = lv_event_get_param(e);
/*Draw the box labels if the list is not being deleted*/
if(dropdown->list) {
/* Clip area might be too large too to shadow but
* the selected option can be drawn on only the background*/
lv_area_t clip_area_core;
bool has_common;
has_common = _lv_area_intersect(&clip_area_core, clip_area, &dropdown->list->coords);
if(has_common) {
if(dropdown->selected_highlight) {
if(dropdown->pr_opt_id == dropdown->sel_opt_id) {
draw_box(dropdown_obj, &clip_area_core, dropdown->pr_opt_id, LV_STATE_CHECKED | LV_STATE_PRESSED);
draw_box_label(dropdown_obj, &clip_area_core, dropdown->pr_opt_id, LV_STATE_CHECKED | LV_STATE_PRESSED);
}
else {
draw_box(dropdown_obj, &clip_area_core, dropdown->pr_opt_id, LV_STATE_PRESSED);
draw_box_label(dropdown_obj, &clip_area_core, dropdown->pr_opt_id, LV_STATE_PRESSED);
draw_box(dropdown_obj, &clip_area_core, dropdown->sel_opt_id, LV_STATE_CHECKED);
draw_box_label(dropdown_obj, &clip_area_core, dropdown->sel_opt_id, LV_STATE_CHECKED);
}
}
else {
draw_box(dropdown_obj, &clip_area_core, dropdown->pr_opt_id, LV_STATE_PRESSED);
draw_box_label(dropdown_obj, &clip_area_core, dropdown->pr_opt_id, LV_STATE_PRESSED);
}
}
}
}
static void draw_box(lv_obj_t * dropdown_obj, const lv_area_t * clip_area, uint16_t id, lv_state_t state)
{
if(id == LV_DROPDOWN_PR_NONE) return;
lv_dropdown_t * dropdown = (lv_dropdown_t *)dropdown_obj;
lv_obj_t * list_obj = dropdown->list;
lv_state_t state_ori = list_obj->state;
if(state != list_obj->state) {
list_obj->state = state;
list_obj->skip_trans = 1;
}
/*Draw a rectangle under the selected item*/
const lv_font_t * font = lv_obj_get_style_text_font(list_obj, LV_PART_SELECTED);
lv_coord_t line_space = lv_obj_get_style_text_line_space(list_obj, LV_PART_SELECTED);
lv_coord_t font_h = lv_font_get_line_height(font);
/*Draw the selected*/
lv_obj_t * label = get_label(dropdown_obj);
lv_area_t rect_area;
rect_area.y1 = label->coords.y1;
rect_area.y1 += id * (font_h + line_space);
rect_area.y1 -= line_space / 2;
rect_area.y2 = rect_area.y1 + font_h + line_space - 1;
rect_area.x1 = dropdown->list->coords.x1;
rect_area.x2 = dropdown->list->coords.x2;
lv_draw_rect_dsc_t sel_rect;
lv_draw_rect_dsc_init(&sel_rect);
lv_obj_init_draw_rect_dsc(list_obj, LV_PART_SELECTED, &sel_rect);
lv_draw_rect(&rect_area, clip_area, &sel_rect);
list_obj->state = state_ori;
list_obj->skip_trans = 0;
}
static void draw_box_label(lv_obj_t * dropdown_obj, const lv_area_t * clip_area, uint16_t id, lv_state_t state)
{
if(id == LV_DROPDOWN_PR_NONE) return;
lv_dropdown_t * dropdown = (lv_dropdown_t *)dropdown_obj;
lv_obj_t * list_obj = dropdown->list;
lv_state_t state_orig = list_obj->state;
if(state != list_obj->state) {
list_obj->state = state;
list_obj->skip_trans = 1;
}
lv_draw_label_dsc_t label_dsc;
lv_draw_label_dsc_init(&label_dsc);
lv_obj_init_draw_label_dsc(list_obj, LV_PART_SELECTED, &label_dsc);
label_dsc.line_space = lv_obj_get_style_text_line_space(list_obj,
LV_PART_SELECTED); /*Line space should come from the list*/
lv_obj_t * label = get_label(dropdown_obj);
if(label == NULL) return;
lv_coord_t font_h = lv_font_get_line_height(label_dsc.font);
lv_area_t area_sel;
area_sel.y1 = label->coords.y1;
area_sel.y1 += id * (font_h + label_dsc.line_space);
area_sel.y1 -= label_dsc.line_space / 2;
area_sel.y2 = area_sel.y1 + font_h + label_dsc.line_space - 1;
area_sel.x1 = list_obj->coords.x1;
area_sel.x2 = list_obj->coords.x2;
lv_area_t mask_sel;
bool area_ok;
area_ok = _lv_area_intersect(&mask_sel, clip_area, &area_sel);
if(area_ok) {
lv_draw_label(&label->coords, &mask_sel, &label_dsc, lv_label_get_text(label), NULL);
}
list_obj->state = state_orig;
list_obj->skip_trans = 0;
}
static lv_res_t btn_release_handler(lv_obj_t * obj)
{
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
lv_indev_t * indev = lv_indev_get_act();
if(lv_indev_get_scroll_obj(indev) == NULL) {
if(dropdown->list) {
lv_dropdown_close(obj);
if(dropdown->sel_opt_id_orig != dropdown->sel_opt_id) {
dropdown->sel_opt_id_orig = dropdown->sel_opt_id;
lv_res_t res;
uint32_t id = dropdown->sel_opt_id; /*Just to use uint32_t in event data*/
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, &id);
if(res != LV_RES_OK) return res;
lv_obj_invalidate(obj);
}
lv_indev_type_t indev_type = lv_indev_get_type(indev);
if(indev_type == LV_INDEV_TYPE_ENCODER) {
lv_group_set_editing(lv_obj_get_group(obj), false);
}
}
else {
lv_dropdown_open(obj);
}
}
else {
dropdown->sel_opt_id = dropdown->sel_opt_id_orig;
lv_obj_invalidate(obj);
}
return LV_RES_OK;
}
/**
* Called when a drop down list is released to open it or set new option
* @param list pointer to the drop down list's list
* @return LV_RES_INV if the list is not being deleted in the user callback. Else LV_RES_OK
*/
static lv_res_t list_release_handler(lv_obj_t * list_obj)
{
lv_dropdown_list_t * list = (lv_dropdown_list_t *) list_obj;
lv_obj_t * dropdown_obj = list->dropdown;
lv_dropdown_t * dropdown = (lv_dropdown_t *)dropdown_obj;
lv_indev_t * indev = lv_indev_get_act();
/*Leave edit mode once a new item is selected*/
if(lv_indev_get_type(indev) == LV_INDEV_TYPE_ENCODER) {
dropdown->sel_opt_id_orig = dropdown->sel_opt_id;
lv_group_t * g = lv_obj_get_group(dropdown_obj);
if(lv_group_get_editing(g)) {
lv_group_set_editing(g, false);
}
}
/*Search the clicked option (For KEYPAD and ENCODER the new value should be already set)*/
if(lv_indev_get_type(indev) == LV_INDEV_TYPE_POINTER || lv_indev_get_type(indev) == LV_INDEV_TYPE_BUTTON) {
lv_point_t p;
lv_indev_get_point(indev, &p);
dropdown->sel_opt_id = get_id_on_point(dropdown_obj, p.y);
dropdown->sel_opt_id_orig = dropdown->sel_opt_id;
}
lv_dropdown_close(dropdown_obj);
/*Invalidate to refresh the text*/
if(dropdown->text == NULL) lv_obj_invalidate(dropdown_obj);
uint32_t id = dropdown->sel_opt_id; /*Just to use uint32_t in event data*/
lv_res_t res = lv_event_send(dropdown_obj, LV_EVENT_VALUE_CHANGED, &id);
if(res != LV_RES_OK) return res;
return LV_RES_OK;
}
static void list_press_handler(lv_obj_t * list_obj)
{
lv_dropdown_list_t * list = (lv_dropdown_list_t *) list_obj;
lv_obj_t * dropdown_obj = list->dropdown;
lv_dropdown_t * dropdown = (lv_dropdown_t *)dropdown_obj;
lv_indev_t * indev = lv_indev_get_act();
if(indev && (lv_indev_get_type(indev) == LV_INDEV_TYPE_POINTER || lv_indev_get_type(indev) == LV_INDEV_TYPE_BUTTON)) {
lv_point_t p;
lv_indev_get_point(indev, &p);
dropdown->pr_opt_id = get_id_on_point(dropdown_obj, p.y);
lv_obj_invalidate(list_obj);
}
}
static uint16_t get_id_on_point(lv_obj_t * dropdown_obj, lv_coord_t y)
{
lv_dropdown_t * dropdown = (lv_dropdown_t *)dropdown_obj;
lv_obj_t * label = get_label(dropdown_obj);
if(label == NULL) return 0;
y -= label->coords.y1;
const lv_font_t * font = lv_obj_get_style_text_font(label, LV_PART_MAIN);
lv_coord_t font_h = lv_font_get_line_height(font);
lv_coord_t line_space = lv_obj_get_style_text_line_space(label, LV_PART_MAIN);
y += line_space / 2;
lv_coord_t h = font_h + line_space;
uint16_t opt = y / h;
if(opt >= dropdown->option_cnt) opt = dropdown->option_cnt - 1;
return opt;
}
/**
* Set the position of list when it is closed to show the selected item
* @param ddlist pointer to a drop down list
*/
static void position_to_selected(lv_obj_t * dropdown_obj)
{
lv_dropdown_t * dropdown = (lv_dropdown_t *)dropdown_obj;
lv_obj_t * label = get_label(dropdown_obj);
if(label == NULL) return;
if(lv_obj_get_height(label) <= lv_obj_get_content_height(dropdown_obj)) return;
const lv_font_t * font = lv_obj_get_style_text_font(label, LV_PART_MAIN);
lv_coord_t font_h = lv_font_get_line_height(font);
lv_coord_t line_space = lv_obj_get_style_text_line_space(label, LV_PART_MAIN);
lv_coord_t unit_h = font_h + line_space;
lv_coord_t line_y1 = dropdown->sel_opt_id * unit_h;
/*Scroll to the selected option*/
lv_obj_scroll_to_y(dropdown->list, line_y1, LV_ANIM_OFF);
lv_obj_invalidate(dropdown->list);
}
static lv_obj_t * get_label(const lv_obj_t * obj)
{
lv_dropdown_t * dropdown = (lv_dropdown_t *)obj;
if(dropdown->list == NULL) return NULL;
return lv_obj_get_child(dropdown->list, 0);
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_dropdown.c | C | apache-2.0 | 36,234 |
/**
* @file lv_dropdown.h
*
*/
#ifndef LV_DROPDOWN_H
#define LV_DROPDOWN_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_DROPDOWN != 0
/*Testing of dependencies*/
#if LV_USE_LABEL == 0
#error "lv_dropdown: lv_label is required. Enable it in lv_conf.h (LV_USE_LABEL 1)"
#endif
#include "../widgets/lv_label.h"
/*********************
* DEFINES
*********************/
#define LV_DROPDOWN_POS_LAST 0xFFFF
LV_EXPORT_CONST_INT(LV_DROPDOWN_POS_LAST);
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_obj_t obj;
lv_obj_t * list; /**< The dropped down list*/
const char * text; /**< Text to display on the dropdown's button*/
const void * symbol; /**< Arrow or other icon when the drop-down list is closed*/
char * options; /**< Options in a a '\n' separated list*/
uint16_t option_cnt; /**< Number of options*/
uint16_t sel_opt_id; /**< Index of the currently selected option*/
uint16_t sel_opt_id_orig; /**< Store the original index on focus*/
uint16_t pr_opt_id; /**< Index of the currently pressed option*/
lv_dir_t dir : 4; /**< Direction in which the list should open*/
uint8_t static_txt : 1; /**< 1: Only a pointer is saved in `options`*/
uint8_t selected_highlight: 1; /**< 1: Make the selected option highlighted in the list*/
} lv_dropdown_t;
typedef struct {
lv_obj_t obj;
lv_obj_t * dropdown;
} lv_dropdown_list_t;
extern const lv_obj_class_t lv_dropdown_class;
extern const lv_obj_class_t lv_dropdownlist_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a drop-down list objects
* @param parent pointer to an object, it will be the parent of the new drop-down list
* @return pointer to the created drop-down list
*/
lv_obj_t * lv_dropdown_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set text of the drop-down list's button.
* If set to `NULL` the selected option's text will be displayed on the button.
* If set to a specific text then that text will be shown regardless the selected option.
* @param obj pointer to a drop-down list object
* @param txt the text as a string (Only its pointer is saved)
*/
void lv_dropdown_set_text(lv_obj_t * obj, const char * txt);
/**
* Set the options in a drop-down list from a string.
* The options will be copied and saved in the object so the `options` can be destroyed after calling this function
* @param obj pointer to drop-down list object
* @param options a string with '\n' separated options. E.g. "One\nTwo\nThree"
*/
void lv_dropdown_set_options(lv_obj_t * obj, const char * options);
/**
* Set the options in a drop-down list from a static string (global, static or dynamically allocated).
* Only the pointer of the option string will be saved.
* @param obj pointer to drop-down list object
* @param options a static string with '\n' separated options. E.g. "One\nTwo\nThree"
*/
void lv_dropdown_set_options_static(lv_obj_t * obj, const char * options);
/**
* Add an options to a drop-down list from a string. Only works for non-static options.
* @param obj pointer to drop-down list object
* @param option a string without '\n'. E.g. "Four"
* @param pos the insert position, indexed from 0, LV_DROPDOWN_POS_LAST = end of string
*/
void lv_dropdown_add_option(lv_obj_t * obj, const char * option, uint32_t pos);
/**
* Clear all options in a drop-down list. Works with both static and dynamic optins.
* @param obj pointer to drop-down list object
*/
void lv_dropdown_clear_options(lv_obj_t * obj);
/**
* Set the selected option
* @param obj pointer to drop-down list object
* @param sel_opt id of the selected option (0 ... number of option - 1);
*/
void lv_dropdown_set_selected(lv_obj_t * obj, uint16_t sel_opt);
/**
* Set the direction of the a drop-down list
* @param obj pointer to a drop-down list object
* @param dir LV_DIR_LEFT/RIGHT/TOP/BOTTOM
*/
void lv_dropdown_set_dir(lv_obj_t * obj, lv_dir_t dir);
/**
* Set an arrow or other symbol to display when on drop-down list's button. Typically a down caret or arrow.
* @param obj pointer to drop-down list object
* @param symbol a text like `LV_SYMBOL_DOWN`, an image (pointer or path) or NULL to not draw symbol icon
* @note angle and zoom transformation can be applied if the symbol is an image.
* E.g. when drop down is checked (opened) rotate the symbol by 180 degree
*/
void lv_dropdown_set_symbol(lv_obj_t * obj, const void * symbol);
/**
* Set whether the selected option in the list should be highlighted or not
* @param obj pointer to drop-down list object
* @param en true: highlight enabled; false: disabled
*/
void lv_dropdown_set_selected_highlight(lv_obj_t * obj, bool en);
/*=====================
* Getter functions
*====================*/
/**
* Get the list of a drop-down to allow styling or other modifications
* @param obj pointer to a drop-down list object
* @return pointer to the list of the drop-down
*/
lv_obj_t * lv_dropdown_get_list(lv_obj_t * obj);
/**
* Get text of the drop-down list's button.
* @param obj pointer to a drop-down list object
* @return the text as string, `NULL` if no text
*/
const char * lv_dropdown_get_text(lv_obj_t * obj);
/**
* Get the options of a drop-down list
* @param obj pointer to drop-down list object
* @return the options separated by '\n'-s (E.g. "Option1\nOption2\nOption3")
*/
const char * lv_dropdown_get_options(const lv_obj_t * obj);
/**
* Get the index of the selected option
* @param obj pointer to drop-down list object
* @return index of the selected option (0 ... number of option - 1);
*/
uint16_t lv_dropdown_get_selected(const lv_obj_t * obj);
/**
* Get the total number of options
* @param obj pointer to drop-down list object
* @return the total number of options in the list
*/
uint16_t lv_dropdown_get_option_cnt(const lv_obj_t * obj);
/**
* Get the current selected option as a string
* @param obj pointer to drop-down object
* @param buf pointer to an array to store the string
* @param buf_size size of `buf` in bytes. 0: to ignore it.
*/
void lv_dropdown_get_selected_str(const lv_obj_t * obj, char * buf, uint32_t buf_size);
/**
* Get the symbol on the drop-down list. Typically a down caret or arrow.
* @param obj pointer to drop-down list object
* @return the symbol or NULL if not enabled
*/
const char * lv_dropdown_get_symbol(lv_obj_t * obj);
/**
* Get whether the selected option in the list should be highlighted or not
* @param obj pointer to drop-down list object
* @return true: highlight enabled; false: disabled
*/
bool lv_dropdown_get_selected_highlight(lv_obj_t * obj);
/**
* Get the direction of the drop-down list
* @param obj pointer to a drop-down list object
* @return LV_DIR_LEF/RIGHT/TOP/BOTTOM
*/
lv_dir_t lv_dropdown_get_dir(const lv_obj_t * obj);
/*=====================
* Other functions
*====================*/
/**
* Open the drop.down list
* @param obj pointer to drop-down list object
*/
void lv_dropdown_open(lv_obj_t * dropdown_obj);
/**
* Close (Collapse) the drop-down list
* @param obj pointer to drop-down list object
*/
void lv_dropdown_close(lv_obj_t * obj);
/**********************
* MACROS
**********************/
#endif /*LV_USE_DROPDOWN*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_DROPDOWN_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_dropdown.h | C | apache-2.0 | 7,837 |
/**
* @file lv_img.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_img.h"
#if LV_USE_IMG != 0
#include "../misc/lv_assert.h"
#include "../draw/lv_img_decoder.h"
#include "../misc/lv_fs.h"
#include "../misc/lv_txt.h"
#include "../misc/lv_math.h"
#include "../misc/lv_log.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_img_class
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_img_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_img_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_img_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void draw_img(lv_event_t * e);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_img_class = {
.constructor_cb = lv_img_constructor,
.destructor_cb = lv_img_destructor,
.event_cb = lv_img_event,
.width_def = LV_SIZE_CONTENT,
.height_def = LV_SIZE_CONTENT,
.instance_size = sizeof(lv_img_t),
.base_class = &lv_obj_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_img_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*=====================
* Setter functions
*====================*/
void lv_img_set_src(lv_obj_t * obj, const void * src)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_obj_invalidate(obj);
lv_img_src_t src_type = lv_img_src_get_type(src);
lv_img_t * img = (lv_img_t *)obj;
#if LV_USE_LOG && LV_LOG_LEVEL >= LV_LOG_LEVEL_INFO
switch(src_type) {
case LV_IMG_SRC_FILE:
LV_LOG_TRACE("lv_img_set_src: `LV_IMG_SRC_FILE` type found");
break;
case LV_IMG_SRC_VARIABLE:
LV_LOG_TRACE("lv_img_set_src: `LV_IMG_SRC_VARIABLE` type found");
break;
case LV_IMG_SRC_SYMBOL:
LV_LOG_TRACE("lv_img_set_src: `LV_IMG_SRC_SYMBOL` type found");
break;
default:
LV_LOG_WARN("lv_img_set_src: unknown type");
}
#endif
/*If the new source type is unknown free the memories of the old source*/
if(src_type == LV_IMG_SRC_UNKNOWN) {
LV_LOG_WARN("lv_img_set_src: unknown image type");
if(img->src_type == LV_IMG_SRC_SYMBOL || img->src_type == LV_IMG_SRC_FILE) {
lv_mem_free((void *)img->src);
}
img->src = NULL;
img->src_type = LV_IMG_SRC_UNKNOWN;
return;
}
lv_img_header_t header;
lv_img_decoder_get_info(src, &header);
/*Save the source*/
if(src_type == LV_IMG_SRC_VARIABLE) {
/*If memory was allocated because of the previous `src_type` then free it*/
if(img->src_type == LV_IMG_SRC_FILE || img->src_type == LV_IMG_SRC_SYMBOL) {
lv_mem_free((void *)img->src);
}
img->src = src;
}
else if(src_type == LV_IMG_SRC_FILE || src_type == LV_IMG_SRC_SYMBOL) {
/*If the new and the old src are the same then it was only a refresh.*/
if(img->src != src) {
const void * old_src = NULL;
/*If memory was allocated because of the previous `src_type` then save its pointer and free after allocation.
*It's important to allocate first to be sure the new data will be on a new address.
*Else `img_cache` wouldn't see the change in source.*/
if(img->src_type == LV_IMG_SRC_FILE || img->src_type == LV_IMG_SRC_SYMBOL) {
old_src = img->src;
}
char * new_str = lv_mem_alloc(strlen(src) + 1);
LV_ASSERT_MALLOC(new_str);
if(new_str == NULL) return;
strcpy(new_str, src);
img->src = new_str;
if(old_src) lv_mem_free((void *)old_src);
}
}
if(src_type == LV_IMG_SRC_SYMBOL) {
/*`lv_img_dsc_get_info` couldn't set the with and height of a font so set it here*/
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_MAIN);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_point_t size;
lv_txt_get_size(&size, src, font, letter_space, line_space, LV_COORD_MAX, LV_TEXT_FLAG_NONE);
header.w = size.x;
header.h = size.y;
}
img->src_type = src_type;
img->w = header.w;
img->h = header.h;
img->cf = header.cf;
img->pivot.x = header.w / 2;
img->pivot.y = header.h / 2;
lv_obj_refresh_self_size(obj);
/*Provide enough room for the rotated corners*/
if(img->angle || img->zoom != LV_IMG_ZOOM_NONE) lv_obj_refresh_ext_draw_size(obj);
lv_obj_invalidate(obj);
}
void lv_img_set_offset_x(lv_obj_t * obj, lv_coord_t x)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_img_t * img = (lv_img_t *)obj;
x = x % img->w;
img->offset.x = x;
lv_obj_invalidate(obj);
}
void lv_img_set_offset_y(lv_obj_t * obj, lv_coord_t y)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_img_t * img = (lv_img_t *)obj;
y = y % img->h;
img->offset.y = y;
lv_obj_invalidate(obj);
}
void lv_img_set_angle(lv_obj_t * obj, int16_t angle)
{
if(angle < 0 || angle >= 3600) angle = angle % 3600;
lv_img_t * img = (lv_img_t *)obj;
if(angle == img->angle) return;
lv_coord_t transf_zoom = lv_obj_get_style_transform_zoom(obj, LV_PART_MAIN);
transf_zoom = ((int32_t)transf_zoom * img->zoom) >> 8;
lv_coord_t transf_angle = lv_obj_get_style_transform_angle(obj, LV_PART_MAIN);
lv_coord_t w = lv_obj_get_width(obj);
lv_coord_t h = lv_obj_get_height(obj);
lv_area_t a;
_lv_img_buf_get_transformed_area(&a, w, h, transf_angle + img->angle, transf_zoom, &img->pivot);
a.x1 += obj->coords.x1;
a.y1 += obj->coords.y1;
a.x2 += obj->coords.x1;
a.y2 += obj->coords.y1;
lv_obj_invalidate_area(obj, &a);
img->angle = angle;
lv_obj_refresh_ext_draw_size(obj);
_lv_img_buf_get_transformed_area(&a, w, h, transf_angle + img->angle, transf_zoom, &img->pivot);
a.x1 += obj->coords.x1;
a.y1 += obj->coords.y1;
a.x2 += obj->coords.x1;
a.y2 += obj->coords.y1;
lv_obj_invalidate_area(obj, &a);
}
void lv_img_set_pivot(lv_obj_t * obj, lv_coord_t x, lv_coord_t y)
{
lv_img_t * img = (lv_img_t *)obj;
if(img->pivot.x == x && img->pivot.y == y) return;
lv_coord_t transf_zoom = lv_obj_get_style_transform_zoom(obj, LV_PART_MAIN);
transf_zoom = ((int32_t)transf_zoom * img->zoom) >> 8;
lv_coord_t transf_angle = lv_obj_get_style_transform_angle(obj, LV_PART_MAIN);
transf_angle += img->angle;
lv_coord_t w = lv_obj_get_width(obj);
lv_coord_t h = lv_obj_get_height(obj);
lv_area_t a;
_lv_img_buf_get_transformed_area(&a, w, h, transf_angle, transf_zoom, &img->pivot);
a.x1 += obj->coords.x1;
a.y1 += obj->coords.y1;
a.x2 += obj->coords.x1;
a.y2 += obj->coords.y1;
lv_obj_invalidate_area(obj, &a);
img->pivot.x = x;
img->pivot.y = y;
lv_obj_refresh_ext_draw_size(obj);
_lv_img_buf_get_transformed_area(&a, w, h, transf_angle, transf_zoom, &img->pivot);
a.x1 += obj->coords.x1;
a.y1 += obj->coords.y1;
a.x2 += obj->coords.x1;
a.y2 += obj->coords.y1;
lv_obj_invalidate_area(obj, &a);
}
void lv_img_set_zoom(lv_obj_t * obj, uint16_t zoom)
{
lv_img_t * img = (lv_img_t *)obj;
if(zoom == img->zoom) return;
if(zoom == 0) zoom = 1;
lv_coord_t transf_zoom = lv_obj_get_style_transform_zoom(obj, LV_PART_MAIN);
lv_coord_t transf_angle = lv_obj_get_style_transform_angle(obj, LV_PART_MAIN);
transf_angle += img->angle;
lv_coord_t w = lv_obj_get_width(obj);
lv_coord_t h = lv_obj_get_height(obj);
lv_area_t a;
_lv_img_buf_get_transformed_area(&a, w, h, transf_angle, ((int32_t)transf_zoom * img->zoom) >> 8, &img->pivot);
a.x1 += obj->coords.x1 - 1;
a.y1 += obj->coords.y1 - 1;
a.x2 += obj->coords.x1 + 1;
a.y2 += obj->coords.y1 + 1;
lv_obj_invalidate_area(obj, &a);
img->zoom = zoom;
lv_obj_refresh_ext_draw_size(obj);
_lv_img_buf_get_transformed_area(&a, w, h, transf_angle, ((int32_t)transf_zoom * img->zoom) >> 8, &img->pivot);
a.x1 += obj->coords.x1 - 1;
a.y1 += obj->coords.y1 - 1;
a.x2 += obj->coords.x1 + 1;
a.y2 += obj->coords.y1 + 1;
lv_obj_invalidate_area(obj, &a);
}
void lv_img_set_antialias(lv_obj_t * obj, bool antialias)
{
lv_img_t * img = (lv_img_t *)obj;
if(antialias == img->antialias) return;
img->antialias = antialias;
lv_obj_invalidate(obj);
}
void lv_img_set_size_mode(lv_obj_t * obj, lv_img_size_mode_t mode)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_img_t * img = (lv_img_t *)obj;
if(mode == img->obj_size_mode) return;
img->obj_size_mode = mode;
lv_obj_invalidate(obj);
}
/*=====================
* Getter functions
*====================*/
const void * lv_img_get_src(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_img_t * img = (lv_img_t *)obj;
return img->src;
}
lv_coord_t lv_img_get_offset_x(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_img_t * img = (lv_img_t *)obj;
return img->offset.x;
}
lv_coord_t lv_img_get_offset_y(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_img_t * img = (lv_img_t *)obj;
return img->offset.y;
}
uint16_t lv_img_get_angle(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_img_t * img = (lv_img_t *)obj;
return img->angle;
}
void lv_img_get_pivot(lv_obj_t * obj, lv_point_t * pivot)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_img_t * img = (lv_img_t *)obj;
*pivot = img->pivot;
}
uint16_t lv_img_get_zoom(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_img_t * img = (lv_img_t *)obj;
return img->zoom;
}
bool lv_img_get_antialias(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_img_t * img = (lv_img_t *)obj;
return img->antialias ? true : false;
}
lv_img_size_mode_t lv_img_get_size_mode(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_img_t * img = (lv_img_t *)obj;
return img->obj_size_mode;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_img_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_img_t * img = (lv_img_t *)obj;
img->src = NULL;
img->src_type = LV_IMG_SRC_UNKNOWN;
img->cf = LV_IMG_CF_UNKNOWN;
img->w = lv_obj_get_width(obj);
img->h = lv_obj_get_height(obj);
img->angle = 0;
img->zoom = LV_IMG_ZOOM_NONE;
img->antialias = LV_COLOR_DEPTH > 8 ? 1 : 0;
img->offset.x = 0;
img->offset.y = 0;
img->pivot.x = 0;
img->pivot.y = 0;
img->obj_size_mode = LV_IMG_SIZE_MODE_VIRTUAL;
lv_obj_clear_flag(obj, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_flag(obj, LV_OBJ_FLAG_ADV_HITTEST);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_img_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_img_t * img = (lv_img_t *)obj;
if(img->src_type == LV_IMG_SRC_FILE || img->src_type == LV_IMG_SRC_SYMBOL) {
lv_mem_free((void *)img->src);
img->src = NULL;
img->src_type = LV_IMG_SRC_UNKNOWN;
}
}
static lv_point_t lv_img_get_transformed_size(lv_obj_t * obj)
{
lv_img_t * img = (lv_img_t *)obj;
int32_t zoom_final = lv_obj_get_style_transform_zoom(obj, LV_PART_MAIN);
zoom_final = (zoom_final * img->zoom) >> 8;
int32_t angle_final = lv_obj_get_style_transform_angle(obj, LV_PART_MAIN);
angle_final += img->angle;
lv_area_t area_transform;
_lv_img_buf_get_transformed_area(&area_transform, img->w, img->h,
angle_final, zoom_final, &img->pivot);
return (lv_point_t) {
lv_area_get_width(&area_transform), lv_area_get_height(&area_transform)
};
}
static void lv_img_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_event_code_t code = lv_event_get_code(e);
/*Ancestor events will be called during drawing*/
if(code != LV_EVENT_DRAW_MAIN && code != LV_EVENT_DRAW_POST) {
/*Call the ancestor's event handler*/
lv_res_t res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
}
lv_obj_t * obj = lv_event_get_target(e);
lv_img_t * img = (lv_img_t *)obj;
if(code == LV_EVENT_STYLE_CHANGED) {
/*Refresh the file name to refresh the symbol text size*/
if(img->src_type == LV_IMG_SRC_SYMBOL) {
lv_img_set_src(obj, img->src);
}
else {
/*With transformation it might change*/
lv_obj_refresh_ext_draw_size(obj);
}
}
else if(code == LV_EVENT_REFR_EXT_DRAW_SIZE) {
lv_coord_t * s = lv_event_get_param(e);
lv_coord_t transf_zoom = lv_obj_get_style_transform_zoom(obj, LV_PART_MAIN);
transf_zoom = ((int32_t)transf_zoom * img->zoom) >> 8;
lv_coord_t transf_angle = lv_obj_get_style_transform_angle(obj, LV_PART_MAIN);
transf_angle += img->angle;
/*If the image has angle provide enough room for the rotated corners*/
if(transf_angle || transf_zoom != LV_IMG_ZOOM_NONE) {
lv_area_t a;
lv_coord_t w = lv_obj_get_width(obj);
lv_coord_t h = lv_obj_get_height(obj);
_lv_img_buf_get_transformed_area(&a, w, h, transf_angle, transf_zoom, &img->pivot);
lv_coord_t pad_ori = *s;
*s = LV_MAX(*s, pad_ori - a.x1);
*s = LV_MAX(*s, pad_ori - a.y1);
*s = LV_MAX(*s, pad_ori + a.x2 - w);
*s = LV_MAX(*s, pad_ori + a.y2 - h);
}
}
else if(code == LV_EVENT_HIT_TEST) {
lv_hit_test_info_t * info = lv_event_get_param(e);
lv_coord_t zoom = lv_obj_get_style_transform_zoom(obj, LV_PART_MAIN);
zoom = (zoom * img->zoom) >> 8;
lv_coord_t angle = lv_obj_get_style_transform_angle(obj, LV_PART_MAIN);
angle += img->angle;
/*If the object is exactly image sized (not cropped, not mosaic) and transformed
*perform hit test on its transformed area*/
if(img->w == lv_obj_get_width(obj) && img->h == lv_obj_get_height(obj) &&
(zoom != LV_IMG_ZOOM_NONE || angle != 0 || img->pivot.x != img->w / 2 || img->pivot.y != img->h / 2)) {
lv_coord_t w = lv_obj_get_width(obj);
lv_coord_t h = lv_obj_get_height(obj);
lv_area_t coords;
_lv_img_buf_get_transformed_area(&coords, w, h, angle, zoom, &img->pivot);
coords.x1 += obj->coords.x1;
coords.y1 += obj->coords.y1;
coords.x2 += obj->coords.x1;
coords.y2 += obj->coords.y1;
info->res = _lv_area_is_point_on(&coords, info->point, 0);
}
else {
lv_area_t a;
lv_obj_get_click_area(obj, &a);
info->res = _lv_area_is_point_on(&a, info->point, 0);
}
}
else if(code == LV_EVENT_GET_SELF_SIZE) {
lv_point_t * p = lv_event_get_param(e);
if(img->obj_size_mode == LV_IMG_SIZE_MODE_REAL) {
*p = lv_img_get_transformed_size(obj);
}
else {
p->x = img->w;
p->y = img->h;
}
}
else if(code == LV_EVENT_DRAW_MAIN || code == LV_EVENT_DRAW_POST || code == LV_EVENT_COVER_CHECK) {
draw_img(e);
}
}
static void draw_img(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
lv_img_t * img = (lv_img_t *)obj;
if(code == LV_EVENT_COVER_CHECK) {
lv_cover_check_info_t * info = lv_event_get_param(e);
if(info->res == LV_COVER_RES_MASKED) return;
if(img->src_type == LV_IMG_SRC_UNKNOWN || img->src_type == LV_IMG_SRC_SYMBOL) {
info->res = LV_COVER_RES_NOT_COVER;
return;
}
/*Non true color format might have "holes"*/
if(img->cf != LV_IMG_CF_TRUE_COLOR && img->cf != LV_IMG_CF_RAW) {
info->res = LV_COVER_RES_NOT_COVER;
return;
}
/*With not LV_OPA_COVER images can't cover an area */
if(lv_obj_get_style_img_opa(obj, LV_PART_MAIN) != LV_OPA_COVER) {
info->res = LV_COVER_RES_NOT_COVER;
return;
}
int32_t angle_final = lv_obj_get_style_transform_angle(obj, LV_PART_MAIN);
angle_final += img->angle;
if(angle_final != 0) {
info->res = LV_COVER_RES_NOT_COVER;
return;
}
int32_t zoom_final = lv_obj_get_style_transform_zoom(obj, LV_PART_MAIN);
zoom_final = (zoom_final * img->zoom) >> 8;
const lv_area_t * clip_area = lv_event_get_param(e);
if(zoom_final == LV_IMG_ZOOM_NONE) {
if(_lv_area_is_in(clip_area, &obj->coords, 0) == false) {
info->res = LV_COVER_RES_NOT_COVER;
return;
}
}
else {
lv_area_t a;
_lv_img_buf_get_transformed_area(&a, lv_obj_get_width(obj), lv_obj_get_height(obj), 0, zoom_final, &img->pivot);
a.x1 += obj->coords.x1;
a.y1 += obj->coords.y1;
a.x2 += obj->coords.x1;
a.y2 += obj->coords.y1;
if(_lv_area_is_in(clip_area, &a, 0) == false) {
info->res = LV_COVER_RES_NOT_COVER;
return;
}
}
}
else if(code == LV_EVENT_DRAW_MAIN || code == LV_EVENT_DRAW_POST) {
int32_t zoom_final = lv_obj_get_style_transform_zoom(obj, LV_PART_MAIN);
zoom_final = (zoom_final * img->zoom) >> 8;
int32_t angle_final = lv_obj_get_style_transform_angle(obj, LV_PART_MAIN);
angle_final += img->angle;
lv_coord_t obj_w = lv_obj_get_width(obj);
lv_coord_t obj_h = lv_obj_get_height(obj);
lv_coord_t border_width = lv_obj_get_style_border_width(obj, LV_PART_MAIN);
lv_coord_t pleft = lv_obj_get_style_pad_left(obj, LV_PART_MAIN) + border_width;
lv_coord_t pright = lv_obj_get_style_pad_right(obj, LV_PART_MAIN) + border_width;
lv_coord_t ptop = lv_obj_get_style_pad_top(obj, LV_PART_MAIN) + border_width;
lv_coord_t pbottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN) + border_width;
lv_point_t bg_pivot;
bg_pivot.x = img->pivot.x + pleft;
bg_pivot.y = img->pivot.y + ptop;
lv_area_t bg_coords;
if(img->obj_size_mode == LV_IMG_SIZE_MODE_REAL) {
/*Object size equals to transformed image size*/
lv_obj_get_coords(obj, &bg_coords);
}
else {
_lv_img_buf_get_transformed_area(&bg_coords, obj_w, obj_h,
angle_final, zoom_final, &bg_pivot);
/*Modify the coordinates to draw the background for the rotated and scaled coordinates*/
bg_coords.x1 += obj->coords.x1;
bg_coords.y1 += obj->coords.y1;
bg_coords.x2 += obj->coords.x1;
bg_coords.y2 += obj->coords.y1;
}
lv_area_t ori_coords;
lv_area_copy(&ori_coords, &obj->coords);
lv_area_copy(&obj->coords, &bg_coords);
lv_res_t res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_area_copy(&obj->coords, &ori_coords);
if(code == LV_EVENT_DRAW_MAIN) {
if(img->h == 0 || img->w == 0) return;
if(zoom_final == 0) return;
const lv_area_t * clip_area = lv_event_get_param(e);
lv_area_t img_max_area;
lv_area_copy(&img_max_area, &obj->coords);
lv_point_t img_size_final = lv_img_get_transformed_size(obj);
if(img->obj_size_mode == LV_IMG_SIZE_MODE_REAL) {
img_max_area.x1 -= ((img->w - img_size_final.x) + 1) / 2;
img_max_area.x2 -= ((img->w - img_size_final.x) + 1) / 2;
img_max_area.y1 -= ((img->h - img_size_final.y) + 1) / 2;
img_max_area.y2 -= ((img->h - img_size_final.y) + 1) / 2;
}
else {
img_max_area.x2 = img_max_area.x1 + lv_area_get_width(&bg_coords) - 1;
img_max_area.y2 = img_max_area.y1 + lv_area_get_height(&bg_coords) - 1;
}
img_max_area.x1 += pleft;
img_max_area.y1 += ptop;
img_max_area.x2 -= pright;
img_max_area.y2 -= pbottom;
if(img->src_type == LV_IMG_SRC_FILE || img->src_type == LV_IMG_SRC_VARIABLE) {
lv_draw_img_dsc_t img_dsc;
lv_draw_img_dsc_init(&img_dsc);
lv_obj_init_draw_img_dsc(obj, LV_PART_MAIN, &img_dsc);
img_dsc.zoom = zoom_final;
img_dsc.angle = angle_final;
img_dsc.pivot.x = img->pivot.x;
img_dsc.pivot.y = img->pivot.y;
img_dsc.antialias = img->antialias;
lv_area_t img_clip_area;
img_clip_area.x1 = bg_coords.x1 + pleft;
img_clip_area.y1 = bg_coords.y1 + ptop;
img_clip_area.x2 = bg_coords.x2 - pright;
img_clip_area.y2 = bg_coords.y2 - pbottom;
_lv_area_intersect(&img_clip_area, clip_area, &img_clip_area);
lv_area_t coords_tmp;
coords_tmp.y1 = img_max_area.y1 + img->offset.y;
if(coords_tmp.y1 > img_max_area.y1) coords_tmp.y1 -= img->h;
coords_tmp.y2 = coords_tmp.y1 + img->h - 1;
for(; coords_tmp.y1 < img_max_area.y2; coords_tmp.y1 += img_size_final.y, coords_tmp.y2 += img_size_final.y) {
coords_tmp.x1 = img_max_area.x1 + img->offset.x;
if(coords_tmp.x1 > img_max_area.x1) coords_tmp.x1 -= img->w;
coords_tmp.x2 = coords_tmp.x1 + img->w - 1;
for(; coords_tmp.x1 < img_max_area.x2; coords_tmp.x1 += img_size_final.x, coords_tmp.x2 += img_size_final.x) {
lv_draw_img(&coords_tmp, &img_clip_area, img->src, &img_dsc);
}
}
}
else if(img->src_type == LV_IMG_SRC_SYMBOL) {
lv_draw_label_dsc_t label_dsc;
lv_draw_label_dsc_init(&label_dsc);
lv_obj_init_draw_label_dsc(obj, LV_PART_MAIN, &label_dsc);
lv_draw_label(&obj->coords, clip_area, &label_dsc, img->src, NULL);
}
else {
/*Trigger the error handler of image draw*/
LV_LOG_WARN("draw_img: image source type is unknown");
lv_draw_img(&obj->coords, clip_area, NULL, NULL);
}
}
}
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_img.c | C | apache-2.0 | 23,139 |
/**
* @file lv_img.h
*
*/
#ifndef LV_IMG_H
#define LV_IMG_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_IMG != 0
#include "../core/lv_obj.h"
#include "../misc/lv_fs.h"
#include "../draw/lv_draw.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**
* Data of image
*/
typedef struct {
lv_obj_t obj;
const void * src; /*Image source: Pointer to an array or a file or a symbol*/
lv_point_t offset;
lv_coord_t w; /*Width of the image (Handled by the library)*/
lv_coord_t h; /*Height of the image (Handled by the library)*/
uint16_t angle; /*rotation angle of the image*/
lv_point_t pivot; /*rotation center of the image*/
uint16_t zoom; /*256 means no zoom, 512 double size, 128 half size*/
uint8_t src_type : 2; /*See: lv_img_src_t*/
uint8_t cf : 5; /*Color format from `lv_img_color_format_t`*/
uint8_t antialias : 1; /*Apply anti-aliasing in transformations (rotate, zoom)*/
uint8_t obj_size_mode: 2; /*Image size mode when image size and object size is different.*/
} lv_img_t;
extern const lv_obj_class_t lv_img_class;
/**
* Image size mode, when image size and object size is different
*/
enum {
/** Zoom doesn't affect the coordinates of the object,
* however if zoomed in the image is drawn out of the its coordinates.
* The layout's won't change on zoom */
LV_IMG_SIZE_MODE_VIRTUAL = 0,
/** If the object size is set to SIZE_CONTENT, then object size equals zoomed image size.
* It causes layout recalculation.
* If the object size is set explicitly the the image will be cropped if zoomed in.*/
LV_IMG_SIZE_MODE_REAL,
};
typedef uint8_t lv_img_size_mode_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a image objects
* @param parent pointer to an object, it will be the parent of the new image
* @return pointer to the created image
*/
lv_obj_t * lv_img_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set the image data to display on the the object
* @param obj pointer to an image object
* @param src_img 1) pointer to an ::lv_img_dsc_t descriptor (converted by LVGL's image converter) (e.g. &my_img) or
* 2) path to an image file (e.g. "S:/dir/img.bin")or
* 3) a SYMBOL (e.g. LV_SYMBOL_OK)
*/
void lv_img_set_src(lv_obj_t * obj, const void * src);
/**
* Set an offset for the source of an image so the image will be displayed from the new origin.
* @param obj pointer to an image
* @param x the new offset along x axis.
*/
void lv_img_set_offset_x(lv_obj_t * obj, lv_coord_t x);
/**
* Set an offset for the source of an image.
* so the image will be displayed from the new origin.
* @param obj pointer to an image
* @param y the new offset along y axis.
*/
void lv_img_set_offset_y(lv_obj_t * obj, lv_coord_t y);
/**
* Set the rotation angle of the image.
* The image will be rotated around the set pivot set by `lv_img_set_pivot()`
* @param obj pointer to an image object
* @param angle rotation angle in degree with 0.1 degree resolution (0..3600: clock wise)
*/
void lv_img_set_angle(lv_obj_t * obj, int16_t angle);
/**
* Set the rotation center of the image.
* The image will be rotated around this point
* @param obj pointer to an image object
* @param x rotation center x of the image
* @param y rotation center y of the image
*/
void lv_img_set_pivot(lv_obj_t * obj, lv_coord_t x, lv_coord_t y);
/**
* Set the zoom factor of the image.
* @param img pointer to an image object
* @param zoom the zoom factor.
* @example 256 or LV_ZOOM_IMG_NONE for no zoom
* @example <256: scale down
* @example >256 scale up
* @example 128 half size
* @example 512 double size
*/
void lv_img_set_zoom(lv_obj_t * obj, uint16_t zoom);
/**
* Enable/disable anti-aliasing for the transformations (rotate, zoom) or not.
* The quality is better with anti-aliasing looks better but slower.
* @param obj pointer to an image object
* @param antialias true: anti-aliased; false: not anti-aliased
*/
void lv_img_set_antialias(lv_obj_t * obj, bool antialias);
/**
* Set the image object size mode.
*
* @param obj pointer to an image object
* @param mode the new size mode.
*/
void lv_img_set_size_mode(lv_obj_t * obj, lv_img_size_mode_t mode);
/*=====================
* Getter functions
*====================*/
/**
* Get the source of the image
* @param obj pointer to an image object
* @return the image source (symbol, file name or ::lv-img_dsc_t for C arrays)
*/
const void * lv_img_get_src(lv_obj_t * obj);
/**
* Get the offset's x attribute of the image object.
* @param img pointer to an image
* @return offset X value.
*/
lv_coord_t lv_img_get_offset_x(lv_obj_t * obj);
/**
* Get the offset's y attribute of the image object.
* @param obj pointer to an image
* @return offset Y value.
*/
lv_coord_t lv_img_get_offset_y(lv_obj_t * obj);
/**
* Get the rotation angle of the image.
* @param obj pointer to an image object
* @return rotation angle in 0.1 degrees (0..3600)
*/
uint16_t lv_img_get_angle(lv_obj_t * obj);
/**
* Get the pivot (rotation center) of the image.
* @param img pointer to an image object
* @param pivot store the rotation center here
*/
void lv_img_get_pivot(lv_obj_t * obj, lv_point_t * pivot);
/**
* Get the zoom factor of the image.
* @param obj pointer to an image object
* @return zoom factor (256: no zoom)
*/
uint16_t lv_img_get_zoom(lv_obj_t * obj);
/**
* Get whether the transformations (rotate, zoom) are anti-aliased or not
* @param obj pointer to an image object
* @return true: anti-aliased; false: not anti-aliased
*/
bool lv_img_get_antialias(lv_obj_t * obj);
/**
* Get the size mode of the image
* @param obj pointer to an image object
* @return element of @ref lv_img_size_mode_t
*/
lv_img_size_mode_t lv_img_get_size_mode(lv_obj_t * obj);
/**********************
* MACROS
**********************/
/** Use this macro to declare an image in a C file*/
#define LV_IMG_DECLARE(var_name) extern const lv_img_dsc_t var_name;
#endif /*LV_USE_IMG*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_IMG_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_img.h | C | apache-2.0 | 6,617 |
/**
* @file lv_label.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_label.h"
#if LV_USE_LABEL != 0
#include "../core/lv_obj.h"
#include "../misc/lv_assert.h"
#include "../core/lv_group.h"
#include "../draw/lv_draw.h"
#include "../misc/lv_color.h"
#include "../misc/lv_math.h"
#include "../misc/lv_bidi.h"
#include "../misc/lv_txt_ap.h"
#include "../misc/lv_printf.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_label_class
#define LV_LABEL_DEF_SCROLL_SPEED (lv_disp_get_dpi(lv_obj_get_disp(obj)) / 3)
#define LV_LABEL_SCROLL_DELAY 300
#define LV_LABEL_DOT_END_INV 0xFFFFFFFF
#define LV_LABEL_HINT_HEIGHT_LIMIT 1024 /*Enable "hint" to buffer info about labels larger than this. (Speed up drawing)*/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_label_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_label_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_label_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void draw_main(lv_event_t * e);
static void lv_label_refr_text(lv_obj_t * obj);
static void lv_label_revert_dots(lv_obj_t * label);
static bool lv_label_set_dot_tmp(lv_obj_t * label, char * data, uint32_t len);
static char * lv_label_get_dot_tmp(lv_obj_t * label);
static void lv_label_dot_tmp_free(lv_obj_t * label);
static void set_ofs_x_anim(void * obj, int32_t v);
static void set_ofs_y_anim(void * obj, int32_t v);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_label_class = {
.constructor_cb = lv_label_constructor,
.destructor_cb = lv_label_destructor,
.event_cb = lv_label_event,
.width_def = LV_SIZE_CONTENT,
.height_def = LV_SIZE_CONTENT,
.instance_size = sizeof(lv_label_t),
.base_class = &lv_obj_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_label_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*=====================
* Setter functions
*====================*/
void lv_label_set_text(lv_obj_t * obj, const char * text)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_label_t * label = (lv_label_t *)obj;
lv_obj_invalidate(obj);
/*If text is NULL then just refresh with the current text*/
if(text == NULL) text = label->text;
if(label->text == text && label->static_txt == 0) {
/*If set its own text then reallocate it (maybe its size changed)*/
#if LV_USE_ARABIC_PERSIAN_CHARS
/*Get the size of the text and process it*/
size_t len = _lv_txt_ap_calc_bytes_cnt(text);
label->text = lv_mem_realloc(label->text, len);
LV_ASSERT_MALLOC(label->text);
if(label->text == NULL) return;
_lv_txt_ap_proc(label->text, label->text);
#else
label->text = lv_mem_realloc(label->text, strlen(label->text) + 1);
#endif
LV_ASSERT_MALLOC(label->text);
if(label->text == NULL) return;
}
else {
/*Free the old text*/
if(label->text != NULL && label->static_txt == 0) {
lv_mem_free(label->text);
label->text = NULL;
}
#if LV_USE_ARABIC_PERSIAN_CHARS
/*Get the size of the text and process it*/
size_t len = _lv_txt_ap_calc_bytes_cnt(text);
label->text = lv_mem_alloc(len);
LV_ASSERT_MALLOC(label->text);
if(label->text == NULL) return;
_lv_txt_ap_proc(text, label->text);
#else
/*Get the size of the text*/
size_t len = strlen(text) + 1;
/*Allocate space for the new text*/
label->text = lv_mem_alloc(len);
LV_ASSERT_MALLOC(label->text);
if(label->text == NULL) return;
strcpy(label->text, text);
#endif
/*Now the text is dynamically allocated*/
label->static_txt = 0;
}
lv_label_refr_text(obj);
}
void lv_label_set_text_fmt(lv_obj_t * obj, const char * fmt, ...)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(fmt);
lv_obj_invalidate(obj);
lv_label_t * label = (lv_label_t *)obj;
/*If text is NULL then refresh*/
if(fmt == NULL) {
lv_label_refr_text(obj);
return;
}
if(label->text != NULL && label->static_txt == 0) {
lv_mem_free(label->text);
label->text = NULL;
}
va_list args;
va_start(args, fmt);
label->text = _lv_txt_set_text_vfmt(fmt, args);
va_end(args);
label->static_txt = 0; /*Now the text is dynamically allocated*/
lv_label_refr_text(obj);
}
void lv_label_set_text_static(lv_obj_t * obj, const char * text)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_label_t * label = (lv_label_t *)obj;
if(label->static_txt == 0 && label->text != NULL) {
lv_mem_free(label->text);
label->text = NULL;
}
if(text != NULL) {
label->static_txt = 1;
label->text = (char *)text;
}
lv_label_refr_text(obj);
}
void lv_label_set_long_mode(lv_obj_t * obj, lv_label_long_mode_t long_mode)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_label_t * label = (lv_label_t *)obj;
/*Delete the old animation (if exists)*/
lv_anim_del(obj, set_ofs_x_anim);
lv_anim_del(obj, set_ofs_y_anim);
label->offset.x = 0;
label->offset.y = 0;
if(long_mode == LV_LABEL_LONG_SCROLL || long_mode == LV_LABEL_LONG_SCROLL_CIRCULAR || long_mode == LV_LABEL_LONG_CLIP)
label->expand = 1;
else
label->expand = 0;
/*Restore the character under the dots*/
if(label->long_mode == LV_LABEL_LONG_DOT && label->dot_end != LV_LABEL_DOT_END_INV) {
lv_label_revert_dots(obj);
}
label->long_mode = long_mode;
lv_label_refr_text(obj);
}
void lv_label_set_recolor(lv_obj_t * obj, bool en)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_label_t * label = (lv_label_t *)obj;
if(label->recolor == en) return;
label->recolor = en == false ? 0 : 1;
/*Refresh the text because the potential color codes in text needs to be hidden or revealed*/
lv_label_refr_text(obj);
}
void lv_label_set_text_sel_start(lv_obj_t * obj, uint32_t index)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
#if LV_LABEL_TEXT_SELECTION
lv_label_t * label = (lv_label_t *)obj;
label->sel_start = index;
lv_obj_invalidate(obj);
#else
LV_UNUSED(obj); /*Unused*/
LV_UNUSED(index); /*Unused*/
#endif
}
void lv_label_set_text_sel_end(lv_obj_t * obj, uint32_t index)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
#if LV_LABEL_TEXT_SELECTION
lv_label_t * label = (lv_label_t *)obj;
label->sel_end = index;
lv_obj_invalidate(obj);
#else
LV_UNUSED(obj); /*Unused*/
LV_UNUSED(index); /*Unused*/
#endif
}
/*=====================
* Getter functions
*====================*/
char * lv_label_get_text(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_label_t * label = (lv_label_t *)obj;
return label->text;
}
lv_label_long_mode_t lv_label_get_long_mode(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_label_t * label = (lv_label_t *)obj;
return label->long_mode;
}
bool lv_label_get_recolor(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_label_t * label = (lv_label_t *)obj;
return label->recolor == 0 ? false : true;
}
void lv_label_get_letter_pos(const lv_obj_t * obj, uint32_t char_id, lv_point_t * pos)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(pos);
lv_label_t * label = (lv_label_t *)obj;
const char * txt = lv_label_get_text(obj);
lv_text_align_t align = lv_obj_calculate_style_text_align(obj, LV_PART_MAIN, txt);
if(txt[0] == '\0') {
pos->y = 0;
switch(align) {
case LV_TEXT_ALIGN_LEFT:
pos->x = 0;
break;
case LV_TEXT_ALIGN_RIGHT:
pos->x = lv_obj_get_content_width(obj);
break;
case LV_TEXT_ALIGN_CENTER:
pos->x = lv_obj_get_content_width(obj) / 2;
break;
}
return;
}
lv_area_t txt_coords;
lv_obj_get_content_coords(obj, &txt_coords);
uint32_t line_start = 0;
uint32_t new_line_start = 0;
lv_coord_t max_w = lv_area_get_width(&txt_coords);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_coord_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_MAIN);
lv_coord_t letter_height = lv_font_get_line_height(font);
lv_coord_t y = 0;
lv_text_flag_t flag = LV_TEXT_FLAG_NONE;
if(label->recolor != 0) flag |= LV_TEXT_FLAG_RECOLOR;
if(label->expand != 0) flag |= LV_TEXT_FLAG_EXPAND;
if(lv_obj_get_style_width(obj, LV_PART_MAIN) == LV_SIZE_CONTENT && !obj->w_layout) flag |= LV_TEXT_FLAG_FIT;
uint32_t byte_id = _lv_txt_encoded_get_byte_id(txt, char_id);
/*Search the line of the index letter*/;
while(txt[new_line_start] != '\0') {
new_line_start += _lv_txt_get_next_line(&txt[line_start], font, letter_space, max_w, flag);
if(byte_id < new_line_start || txt[new_line_start] == '\0')
break; /*The line of 'index' letter begins at 'line_start'*/
y += letter_height + line_space;
line_start = new_line_start;
}
/*If the last character is line break then go to the next line*/
if(byte_id > 0) {
if((txt[byte_id - 1] == '\n' || txt[byte_id - 1] == '\r') && txt[byte_id] == '\0') {
y += letter_height + line_space;
line_start = byte_id;
}
}
const char * bidi_txt;
uint32_t visual_byte_pos;
#if LV_USE_BIDI
lv_base_dir_t base_dir = lv_obj_get_style_base_dir(obj, LV_PART_MAIN);
if(base_dir == LV_BASE_DIR_AUTO) base_dir = _lv_bidi_detect_base_dir(txt);
char * mutable_bidi_txt = NULL;
/*Handle Bidi*/
if(new_line_start == byte_id) {
visual_byte_pos = base_dir == LV_BASE_DIR_RTL ? 0 : byte_id - line_start;
bidi_txt = &txt[line_start];
}
else {
uint32_t line_char_id = _lv_txt_encoded_get_char_id(&txt[line_start], byte_id - line_start);
bool is_rtl;
uint32_t visual_char_pos = _lv_bidi_get_visual_pos(&txt[line_start], &mutable_bidi_txt, new_line_start - line_start,
base_dir, line_char_id, &is_rtl);
bidi_txt = mutable_bidi_txt;
if(is_rtl) visual_char_pos++;
visual_byte_pos = _lv_txt_encoded_get_byte_id(bidi_txt, visual_char_pos);
}
#else
bidi_txt = &txt[line_start];
visual_byte_pos = byte_id - line_start;
#endif
/*Calculate the x coordinate*/
lv_coord_t x = lv_txt_get_width(bidi_txt, visual_byte_pos, font, letter_space, flag);
if(char_id != line_start) x += letter_space;
if(align == LV_TEXT_ALIGN_CENTER) {
lv_coord_t line_w;
line_w = lv_txt_get_width(bidi_txt, new_line_start - line_start, font, letter_space, flag);
x += lv_area_get_width(&txt_coords) / 2 - line_w / 2;
}
else if(align == LV_TEXT_ALIGN_RIGHT) {
lv_coord_t line_w;
line_w = lv_txt_get_width(bidi_txt, new_line_start - line_start, font, letter_space, flag);
x += lv_area_get_width(&txt_coords) - line_w;
}
pos->x = x;
pos->y = y;
#if LV_USE_BIDI
if(mutable_bidi_txt) lv_mem_buf_release(mutable_bidi_txt);
#endif
}
uint32_t lv_label_get_letter_on(const lv_obj_t * obj, lv_point_t * pos_in)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(pos_in);
lv_label_t * label = (lv_label_t *)obj;
lv_point_t pos;
pos.x = pos_in->x - lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
pos.y = pos_in->y - lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_area_t txt_coords;
lv_obj_get_content_coords(obj, &txt_coords);
const char * txt = lv_label_get_text(obj);
uint32_t line_start = 0;
uint32_t new_line_start = 0;
lv_coord_t max_w = lv_area_get_width(&txt_coords);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_coord_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_MAIN);
lv_coord_t letter_height = lv_font_get_line_height(font);
lv_coord_t y = 0;
lv_text_flag_t flag = LV_TEXT_FLAG_NONE;
uint32_t logical_pos;
char * bidi_txt;
if(label->recolor != 0) flag |= LV_TEXT_FLAG_RECOLOR;
if(label->expand != 0) flag |= LV_TEXT_FLAG_EXPAND;
if(lv_obj_get_style_width(obj, LV_PART_MAIN) == LV_SIZE_CONTENT && !obj->w_layout) flag |= LV_TEXT_FLAG_FIT;
lv_text_align_t align = lv_obj_calculate_style_text_align(obj, LV_PART_MAIN, label->text);
/*Search the line of the index letter*/;
while(txt[line_start] != '\0') {
new_line_start += _lv_txt_get_next_line(&txt[line_start], font, letter_space, max_w, flag);
if(pos.y <= y + letter_height) {
/*The line is found (stored in 'line_start')*/
/*Include the NULL terminator in the last line*/
uint32_t tmp = new_line_start;
uint32_t letter;
letter = _lv_txt_encoded_prev(txt, &tmp);
if(letter != '\n' && txt[new_line_start] == '\0') new_line_start++;
break;
}
y += letter_height + line_space;
line_start = new_line_start;
}
#if LV_USE_BIDI
bidi_txt = lv_mem_buf_get(new_line_start - line_start + 1);
uint32_t txt_len = new_line_start - line_start;
if(new_line_start > 0 && txt[new_line_start - 1] == '\0' && txt_len > 0) txt_len--;
_lv_bidi_process_paragraph(txt + line_start, bidi_txt, txt_len, lv_obj_get_style_base_dir(obj, LV_PART_MAIN), NULL, 0);
#else
bidi_txt = (char *)txt + line_start;
#endif
/*Calculate the x coordinate*/
lv_coord_t x = 0;
if(align == LV_TEXT_ALIGN_CENTER) {
lv_coord_t line_w;
line_w = lv_txt_get_width(bidi_txt, new_line_start - line_start, font, letter_space, flag);
x += lv_area_get_width(&txt_coords) / 2 - line_w / 2;
}
else if(align == LV_TEXT_ALIGN_RIGHT) {
lv_coord_t line_w;
line_w = lv_txt_get_width(bidi_txt, new_line_start - line_start, font, letter_space, flag);
x += lv_area_get_width(&txt_coords) - line_w;
}
lv_text_cmd_state_t cmd_state = LV_TEXT_CMD_STATE_WAIT;
uint32_t i = 0;
uint32_t i_act = i;
if(new_line_start > 0) {
while(i + line_start < new_line_start) {
/*Get the current letter and the next letter for kerning*/
/*Be careful 'i' already points to the next character*/
uint32_t letter;
uint32_t letter_next;
_lv_txt_encoded_letter_next_2(bidi_txt, &letter, &letter_next, &i);
/*Handle the recolor command*/
if((flag & LV_TEXT_FLAG_RECOLOR) != 0) {
if(_lv_txt_is_cmd(&cmd_state, bidi_txt[i]) != false) {
continue; /*Skip the letter if it is part of a command*/
}
}
lv_coord_t gw = lv_font_get_glyph_width(font, letter, letter_next);
/*Finish if the x position or the last char of the next line is reached*/
if(pos.x < x + gw || i + line_start == new_line_start || txt[i_act + line_start] == '\0') {
i = i_act;
break;
}
x += gw;
x += letter_space;
i_act = i;
}
}
#if LV_USE_BIDI
/*Handle Bidi*/
uint32_t cid = _lv_txt_encoded_get_char_id(bidi_txt, i);
if(txt[line_start + i] == '\0') {
logical_pos = i;
}
else {
bool is_rtl;
logical_pos = _lv_bidi_get_logical_pos(&txt[line_start], NULL,
txt_len, lv_obj_get_style_base_dir(obj, LV_PART_MAIN), cid, &is_rtl);
if(is_rtl) logical_pos++;
}
lv_mem_buf_release(bidi_txt);
#else
logical_pos = _lv_txt_encoded_get_char_id(bidi_txt, i);
#endif
return logical_pos + _lv_txt_encoded_get_char_id(txt, line_start);
}
bool lv_label_is_char_under_pos(const lv_obj_t * obj, lv_point_t * pos)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(pos);
lv_area_t txt_coords;
lv_obj_get_content_coords(obj, &txt_coords);
const char * txt = lv_label_get_text(obj);
lv_label_t * label = (lv_label_t *)obj;
uint32_t line_start = 0;
uint32_t new_line_start = 0;
lv_coord_t max_w = lv_area_get_width(&txt_coords);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_coord_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_MAIN);
lv_coord_t letter_height = lv_font_get_line_height(font);
lv_text_align_t align = lv_obj_calculate_style_text_align(obj, LV_PART_MAIN, label->text);
lv_coord_t y = 0;
lv_text_flag_t flag = LV_TEXT_FLAG_NONE;
if(label->recolor != 0) flag |= LV_TEXT_FLAG_RECOLOR;
if(label->expand != 0) flag |= LV_TEXT_FLAG_EXPAND;
if(lv_obj_get_style_width(obj, LV_PART_MAIN) == LV_SIZE_CONTENT && !obj->w_layout) flag |= LV_TEXT_FLAG_FIT;
/*Search the line of the index letter*/;
while(txt[line_start] != '\0') {
new_line_start += _lv_txt_get_next_line(&txt[line_start], font, letter_space, max_w, flag);
if(pos->y <= y + letter_height) break; /*The line is found (stored in 'line_start')*/
y += letter_height + line_space;
line_start = new_line_start;
}
/*Calculate the x coordinate*/
lv_coord_t x = 0;
lv_coord_t last_x = 0;
if(align == LV_TEXT_ALIGN_CENTER) {
lv_coord_t line_w;
line_w = lv_txt_get_width(&txt[line_start], new_line_start - line_start, font, letter_space, flag);
x += lv_area_get_width(&txt_coords) / 2 - line_w / 2;
}
else if(align == LV_TEXT_ALIGN_RIGHT) {
lv_coord_t line_w;
line_w = lv_txt_get_width(&txt[line_start], new_line_start - line_start, font, letter_space, flag);
x += lv_area_get_width(&txt_coords) - line_w;
}
lv_text_cmd_state_t cmd_state = LV_TEXT_CMD_STATE_WAIT;
uint32_t i = line_start;
uint32_t i_current = i;
uint32_t letter = '\0';
uint32_t letter_next = '\0';
if(new_line_start > 0) {
while(i <= new_line_start - 1) {
/*Get the current letter and the next letter for kerning*/
/*Be careful 'i' already points to the next character*/
_lv_txt_encoded_letter_next_2(txt, &letter, &letter_next, &i);
/*Handle the recolor command*/
if((flag & LV_TEXT_FLAG_RECOLOR) != 0) {
if(_lv_txt_is_cmd(&cmd_state, txt[i]) != false) {
continue; /*Skip the letter if it is part of a command*/
}
}
last_x = x;
x += lv_font_get_glyph_width(font, letter, letter_next);
if(pos->x < x) {
i = i_current;
break;
}
x += letter_space;
i_current = i;
}
}
int32_t max_diff = lv_font_get_glyph_width(font, letter, letter_next) + letter_space + 1;
return (pos->x >= (last_x - letter_space) && pos->x <= (last_x + max_diff));
}
uint32_t lv_label_get_text_selection_start(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
#if LV_LABEL_TEXT_SELECTION
lv_label_t * label = (lv_label_t *)obj;
return label->sel_start;
#else
LV_UNUSED(obj); /*Unused*/
return LV_LABEL_TEXT_SELECTION_OFF;
#endif
}
uint32_t lv_label_get_text_selection_end(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
#if LV_LABEL_TEXT_SELECTION
lv_label_t * label = (lv_label_t *)obj;
return label->sel_end;
#else
LV_UNUSED(obj); /*Unused*/
return LV_LABEL_TEXT_SELECTION_OFF;
#endif
}
/*=====================
* Other functions
*====================*/
void lv_label_ins_text(lv_obj_t * obj, uint32_t pos, const char * txt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(txt);
lv_label_t * label = (lv_label_t *)obj;
/*Can not append to static text*/
if(label->static_txt != 0) return;
lv_obj_invalidate(obj);
/*Allocate space for the new text*/
size_t old_len = strlen(label->text);
size_t ins_len = strlen(txt);
size_t new_len = ins_len + old_len;
label->text = lv_mem_realloc(label->text, new_len + 1);
LV_ASSERT_MALLOC(label->text);
if(label->text == NULL) return;
if(pos == LV_LABEL_POS_LAST) {
pos = _lv_txt_get_encoded_length(label->text);
}
_lv_txt_ins(label->text, pos, txt);
lv_label_set_text(obj, NULL);
}
void lv_label_cut_text(lv_obj_t * obj, uint32_t pos, uint32_t cnt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_label_t * label = (lv_label_t *)obj;
/*Can not append to static text*/
if(label->static_txt != 0) return;
lv_obj_invalidate(obj);
char * label_txt = lv_label_get_text(obj);
/*Delete the characters*/
_lv_txt_cut(label_txt, pos, cnt);
/*Refresh the label*/
lv_label_refr_text(obj);
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_label_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_label_t * label = (lv_label_t *)obj;
label->text = NULL;
label->static_txt = 0;
label->recolor = 0;
label->dot_end = LV_LABEL_DOT_END_INV;
label->long_mode = LV_LABEL_LONG_WRAP;
label->offset.x = 0;
label->offset.y = 0;
#if LV_LABEL_LONG_TXT_HINT
label->hint.line_start = -1;
label->hint.coord_y = 0;
label->hint.y = 0;
#endif
#if LV_LABEL_TEXT_SELECTION
label->sel_start = LV_DRAW_LABEL_NO_TXT_SEL;
label->sel_end = LV_DRAW_LABEL_NO_TXT_SEL;
#endif
label->dot.tmp_ptr = NULL;
label->dot_tmp_alloc = 0;
lv_obj_clear_flag(obj, LV_OBJ_FLAG_CLICKABLE);
lv_label_set_long_mode(obj, LV_LABEL_LONG_WRAP);
lv_label_set_text(obj, "Text");
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_label_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_label_t * label = (lv_label_t *)obj;
lv_label_dot_tmp_free(obj);
if(!label->static_txt) lv_mem_free(label->text);
label->text = NULL;
}
static void lv_label_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
if(code == LV_EVENT_STYLE_CHANGED) {
/*Revert dots for proper refresh*/
lv_label_revert_dots(obj);
lv_label_refr_text(obj);
}
else if(code == LV_EVENT_REFR_EXT_DRAW_SIZE) {
/* Italic or other non-typical letters can be drawn of out of the object.
* It happens if box_w + ofs_x > adw_w in the glyph.
* To avoid this add some extra draw area.
* font_h / 4 is an empirical value. */
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t font_h = lv_font_get_line_height(font);
lv_event_set_ext_draw_size(e, font_h / 4);
}
else if(code == LV_EVENT_SIZE_CHANGED) {
lv_label_revert_dots(obj);
lv_label_refr_text(obj);
}
else if(code == LV_EVENT_GET_SELF_SIZE) {
lv_point_t size;
lv_label_t * label = (lv_label_t *)obj;
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_MAIN);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_text_flag_t flag = LV_TEXT_FLAG_NONE;
if(label->recolor != 0) flag |= LV_TEXT_FLAG_RECOLOR;
if(label->expand != 0) flag |= LV_TEXT_FLAG_EXPAND;
lv_coord_t w = lv_obj_get_content_width(obj);
if(lv_obj_get_style_width(obj, LV_PART_MAIN) == LV_SIZE_CONTENT && !obj->w_layout) w = LV_COORD_MAX;
else w = lv_obj_get_content_width(obj);
lv_txt_get_size(&size, label->text, font, letter_space, line_space, w, flag);
lv_point_t * self_size = lv_event_get_param(e);
self_size->x = LV_MAX(self_size->x, size.x);
self_size->y = LV_MAX(self_size->y, size.y);
}
else if(code == LV_EVENT_DRAW_MAIN) {
draw_main(e);
}
}
static void draw_main(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_label_t * label = (lv_label_t *)obj;
const lv_area_t * clip_area = lv_event_get_param(e);
lv_area_t txt_coords;
lv_obj_get_content_coords(obj, &txt_coords);
lv_text_flag_t flag = LV_TEXT_FLAG_NONE;
if(label->recolor != 0) flag |= LV_TEXT_FLAG_RECOLOR;
if(label->expand != 0) flag |= LV_TEXT_FLAG_EXPAND;
if(lv_obj_get_style_width(obj, LV_PART_MAIN) == LV_SIZE_CONTENT && !obj->w_layout) flag |= LV_TEXT_FLAG_FIT;
lv_draw_label_dsc_t label_draw_dsc;
lv_draw_label_dsc_init(&label_draw_dsc);
label_draw_dsc.ofs_x = label->offset.x;
label_draw_dsc.ofs_y = label->offset.y;
label_draw_dsc.flag = flag;
lv_obj_init_draw_label_dsc(obj, LV_PART_MAIN, &label_draw_dsc);
lv_bidi_calculate_align(&label_draw_dsc.align, &label_draw_dsc.bidi_dir, label->text);
label_draw_dsc.sel_start = lv_label_get_text_selection_start(obj);
label_draw_dsc.sel_end = lv_label_get_text_selection_end(obj);
if(label_draw_dsc.sel_start != LV_DRAW_LABEL_NO_TXT_SEL && label_draw_dsc.sel_end != LV_DRAW_LABEL_NO_TXT_SEL) {
label_draw_dsc.sel_color = lv_obj_get_style_text_color_filtered(obj, LV_PART_SELECTED);
label_draw_dsc.sel_bg_color = lv_obj_get_style_bg_color(obj, LV_PART_SELECTED);
}
/* In SROLL and SROLL_CIRC mode the CENTER and RIGHT are pointless so remove them.
* (In addition they will result misalignment is this case)*/
if((label->long_mode == LV_LABEL_LONG_SCROLL || label->long_mode == LV_LABEL_LONG_SCROLL_CIRCULAR) &&
(label_draw_dsc.align == LV_TEXT_ALIGN_CENTER || label_draw_dsc.align == LV_TEXT_ALIGN_RIGHT)) {
lv_point_t size;
lv_txt_get_size(&size, label->text, label_draw_dsc.font, label_draw_dsc.letter_space, label_draw_dsc.line_space,
LV_COORD_MAX, flag);
if(size.x > lv_area_get_width(&txt_coords)) {
label_draw_dsc.align = LV_TEXT_ALIGN_LEFT;
}
}
#if LV_LABEL_LONG_TXT_HINT
lv_draw_label_hint_t * hint = &label->hint;
if(label->long_mode == LV_LABEL_LONG_SCROLL_CIRCULAR || lv_area_get_height(&txt_coords) < LV_LABEL_HINT_HEIGHT_LIMIT)
hint = NULL;
#else
/*Just for compatibility*/
lv_draw_label_hint_t * hint = NULL;
#endif
lv_area_t txt_clip;
bool is_common = _lv_area_intersect(&txt_clip, &txt_coords, clip_area);
if(!is_common) return;
if(label->long_mode == LV_LABEL_LONG_WRAP) {
lv_coord_t s = lv_obj_get_scroll_top(obj);
lv_area_move(&txt_coords, 0, -s);
txt_coords.y2 = obj->coords.y2;
}
if(label->long_mode == LV_LABEL_LONG_SCROLL || label->long_mode == LV_LABEL_LONG_SCROLL_CIRCULAR) {
lv_draw_label(&txt_coords, &txt_clip, &label_draw_dsc, label->text, hint);
} else {
lv_draw_label(&txt_coords, clip_area, &label_draw_dsc, label->text, hint);
}
if(label->long_mode == LV_LABEL_LONG_SCROLL_CIRCULAR) {
lv_point_t size;
lv_txt_get_size(&size, label->text, label_draw_dsc.font, label_draw_dsc.letter_space, label_draw_dsc.line_space,
LV_COORD_MAX, flag);
/*Draw the text again on label to the original to make a circular effect */
if(size.x > lv_area_get_width(&txt_coords)) {
label_draw_dsc.ofs_x = label->offset.x + size.x +
lv_font_get_glyph_width(label_draw_dsc.font, ' ', ' ') * LV_LABEL_WAIT_CHAR_COUNT;
label_draw_dsc.ofs_y = label->offset.y;
lv_draw_label(&txt_coords, &txt_clip, &label_draw_dsc, label->text, hint);
}
/*Draw the text again below the original to make a circular effect */
if(size.y > lv_area_get_height(&txt_coords)) {
label_draw_dsc.ofs_x = label->offset.x;
label_draw_dsc.ofs_y = label->offset.y + size.y + lv_font_get_line_height(label_draw_dsc.font);
lv_draw_label(&txt_coords, &txt_clip, &label_draw_dsc, label->text, hint);
}
}
}
/**
* Refresh the label with its text stored in its extended data
* @param label pointer to a label object
*/
static void lv_label_refr_text(lv_obj_t * obj)
{
lv_label_t * label = (lv_label_t *)obj;
if(label->text == NULL) return;
#if LV_LABEL_LONG_TXT_HINT
label->hint.line_start = -1; /*The hint is invalid if the text changes*/
#endif
lv_area_t txt_coords;
lv_obj_get_content_coords(obj, &txt_coords);
lv_coord_t max_w = lv_area_get_width(&txt_coords);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_coord_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_MAIN);
/*Calc. the height and longest line*/
lv_point_t size;
lv_text_flag_t flag = LV_TEXT_FLAG_NONE;
if(label->recolor != 0) flag |= LV_TEXT_FLAG_RECOLOR;
if(label->expand != 0) flag |= LV_TEXT_FLAG_EXPAND;
if(lv_obj_get_style_width(obj, LV_PART_MAIN) == LV_SIZE_CONTENT && !obj->w_layout) flag |= LV_TEXT_FLAG_FIT;
lv_txt_get_size(&size, label->text, font, letter_space, line_space, max_w, flag);
lv_obj_refresh_self_size(obj);
/*In scroll mode start an offset animations*/
if(label->long_mode == LV_LABEL_LONG_SCROLL) {
uint16_t anim_speed = lv_obj_get_style_anim_speed(obj, LV_PART_MAIN);
if(anim_speed == 0) anim_speed = LV_LABEL_DEF_SCROLL_SPEED;
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, obj);
lv_anim_set_repeat_count(&a, LV_ANIM_REPEAT_INFINITE);
lv_anim_set_playback_delay(&a, LV_LABEL_SCROLL_DELAY);
lv_anim_set_repeat_delay(&a, a.playback_delay);
bool hor_anim = false;
if(size.x > lv_area_get_width(&txt_coords)) {
#if LV_USE_BIDI
int32_t start, end;
lv_base_dir_t base_dir = lv_obj_get_style_base_dir(obj, LV_PART_MAIN);
if(base_dir == LV_BASE_DIR_AUTO)
base_dir = _lv_bidi_detect_base_dir(label->text);
if(base_dir == LV_BASE_DIR_RTL) {
start = lv_area_get_width(&txt_coords) - size.x;
end = 0;
}
else {
start = 0;
end = lv_area_get_width(&txt_coords) - size.x;
}
lv_anim_set_values(&a, start, end);
#else
lv_anim_set_values(&a, 0, lv_area_get_width(&txt_coords) - size.x);
lv_anim_set_exec_cb(&a, set_ofs_x_anim);
#endif
lv_anim_set_exec_cb(&a, set_ofs_x_anim);
lv_anim_t * anim_cur = lv_anim_get(obj, set_ofs_x_anim);
int32_t act_time = 0;
bool playback_now = false;
if(anim_cur) {
act_time = anim_cur->act_time;
playback_now = anim_cur->playback_now;
}
if(act_time < a.time) {
a.act_time = act_time; /*To keep the old position*/
a.early_apply = 0;
if(playback_now) {
a.playback_now = 1;
/*Swap the start and end values*/
int32_t tmp;
tmp = a.start_value;
a.start_value = a.end_value;
a.end_value = tmp;
}
}
lv_anim_set_time(&a, lv_anim_speed_to_time(anim_speed, a.start_value, a.end_value));
lv_anim_set_playback_time(&a, a.time);
lv_anim_start(&a);
hor_anim = true;
}
else {
/*Delete the offset animation if not required*/
lv_anim_del(obj, set_ofs_x_anim);
label->offset.x = 0;
}
if(size.y > lv_area_get_height(&txt_coords) && hor_anim == false) {
lv_anim_set_values(&a, 0, lv_area_get_height(&txt_coords) - size.y - (lv_font_get_line_height(font)));
lv_anim_set_exec_cb(&a, set_ofs_y_anim);
lv_anim_t * anim_cur = lv_anim_get(obj, set_ofs_y_anim);
int32_t act_time = 0;
bool playback_now = false;
if(anim_cur) {
act_time = anim_cur->act_time;
playback_now = anim_cur->playback_now;
}
if(act_time < a.time) {
a.act_time = act_time; /*To keep the old position*/
a.early_apply = 0;
if(playback_now) {
a.playback_now = 1;
/*Swap the start and end values*/
int32_t tmp;
tmp = a.start_value;
a.start_value = a.end_value;
a.end_value = tmp;
}
}
lv_anim_set_time(&a, lv_anim_speed_to_time(anim_speed, a.start_value, a.end_value));
lv_anim_set_playback_time(&a, a.time);
lv_anim_start(&a);
}
else {
/*Delete the offset animation if not required*/
lv_anim_del(obj, set_ofs_y_anim);
label->offset.y = 0;
}
}
/*In roll inf. mode keep the size but start offset animations*/
else if(label->long_mode == LV_LABEL_LONG_SCROLL_CIRCULAR) {
uint16_t anim_speed = lv_obj_get_style_anim_speed(obj, LV_PART_MAIN);
if(anim_speed == 0) anim_speed = LV_LABEL_DEF_SCROLL_SPEED;
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, obj);
lv_anim_set_repeat_count(&a, LV_ANIM_REPEAT_INFINITE);
bool hor_anim = false;
if(size.x > lv_area_get_width(&txt_coords)) {
#if LV_USE_BIDI
int32_t start, end;
lv_base_dir_t base_dir = lv_obj_get_style_base_dir(obj, LV_PART_MAIN);
if(base_dir == LV_BASE_DIR_AUTO)
base_dir = _lv_bidi_detect_base_dir(label->text);
if(base_dir == LV_BASE_DIR_RTL) {
start = -size.x - lv_font_get_glyph_width(font, ' ', ' ') * LV_LABEL_WAIT_CHAR_COUNT;
end = 0;
}
else {
start = 0;
end = -size.x - lv_font_get_glyph_width(font, ' ', ' ') * LV_LABEL_WAIT_CHAR_COUNT;
}
lv_anim_set_values(&a, start, end);
#else
lv_anim_set_values(&a, 0, -size.x - lv_font_get_glyph_width(font, ' ', ' ') * LV_LABEL_WAIT_CHAR_COUNT);
#endif
lv_anim_set_exec_cb(&a, set_ofs_x_anim);
lv_anim_set_time(&a, lv_anim_speed_to_time(anim_speed, a.start_value, a.end_value));
lv_anim_t * anim_cur = lv_anim_get(obj, set_ofs_x_anim);
int32_t act_time = anim_cur ? anim_cur->act_time : 0;
if(act_time < a.time) {
a.act_time = act_time; /*To keep the old position*/
a.early_apply = 0;
}
lv_anim_start(&a);
hor_anim = true;
}
else {
/*Delete the offset animation if not required*/
lv_anim_del(obj, set_ofs_x_anim);
label->offset.x = 0;
}
if(size.y > lv_area_get_height(&txt_coords) && hor_anim == false) {
lv_anim_set_values(&a, 0, -size.y - (lv_font_get_line_height(font)));
lv_anim_set_exec_cb(&a, set_ofs_y_anim);
lv_anim_set_time(&a, lv_anim_speed_to_time(anim_speed, a.start_value, a.end_value));
lv_anim_t * anim_cur = lv_anim_get(obj, set_ofs_y_anim);
int32_t act_time = anim_cur ? anim_cur->act_time : 0;
if(act_time < a.time) {
a.act_time = act_time; /*To keep the old position*/
a.early_apply = 0;
}
lv_anim_start(&a);
}
else {
/*Delete the offset animation if not required*/
lv_anim_del(obj, set_ofs_y_anim);
label->offset.y = 0;
}
}
else if(label->long_mode == LV_LABEL_LONG_DOT) {
if(size.y <= lv_area_get_height(&txt_coords)) { /*No dots are required, the text is short enough*/
label->dot_end = LV_LABEL_DOT_END_INV;
}
else if(_lv_txt_get_encoded_length(label->text) <= LV_LABEL_DOT_NUM) { /*Don't turn to dots all the characters*/
label->dot_end = LV_LABEL_DOT_END_INV;
}
else {
lv_point_t p;
lv_coord_t y_overed;
p.x = lv_area_get_width(&txt_coords) -
(lv_font_get_glyph_width(font, '.', '.') + letter_space) *
LV_LABEL_DOT_NUM; /*Shrink with dots*/
p.y = lv_area_get_height(&txt_coords);
y_overed = p.y %
(lv_font_get_line_height(font) + line_space); /*Round down to the last line*/
if(y_overed >= lv_font_get_line_height(font)) {
p.y -= y_overed;
p.y += lv_font_get_line_height(font);
}
else {
p.y -= y_overed;
p.y -= line_space;
}
uint32_t letter_id = lv_label_get_letter_on(obj, &p);
/*Be sure there is space for the dots*/
size_t txt_len = strlen(label->text);
uint32_t byte_id = _lv_txt_encoded_get_byte_id(label->text, letter_id);
while(byte_id + LV_LABEL_DOT_NUM > txt_len) {
_lv_txt_encoded_prev(label->text, &byte_id);
letter_id--;
}
/*Save letters under the dots and replace them with dots*/
uint32_t byte_id_ori = byte_id;
uint32_t i;
uint8_t len = 0;
for(i = 0; i <= LV_LABEL_DOT_NUM; i++) {
len += _lv_txt_encoded_size(&label->text[byte_id]);
_lv_txt_encoded_next(label->text, &byte_id);
if (len > LV_LABEL_DOT_NUM || byte_id > txt_len) {
break;
}
}
if(lv_label_set_dot_tmp(obj, &label->text[byte_id_ori], len)) {
for(i = 0; i < LV_LABEL_DOT_NUM; i++) {
label->text[byte_id_ori + i] = '.';
}
label->text[byte_id_ori + LV_LABEL_DOT_NUM] = '\0';
label->dot_end = letter_id + LV_LABEL_DOT_NUM;
}
}
}
else if(label->long_mode == LV_LABEL_LONG_CLIP) {
/*Do nothing*/
}
lv_obj_invalidate(obj);
}
static void lv_label_revert_dots(lv_obj_t * obj)
{
lv_label_t * label = (lv_label_t *)obj;
if(label->long_mode != LV_LABEL_LONG_DOT) return;
if(label->dot_end == LV_LABEL_DOT_END_INV) return;
uint32_t letter_i = label->dot_end - LV_LABEL_DOT_NUM;
uint32_t byte_i = _lv_txt_encoded_get_byte_id(label->text, letter_i);
/*Restore the characters*/
uint8_t i = 0;
char * dot_tmp = lv_label_get_dot_tmp(obj);
while(label->text[byte_i + i] != '\0') {
label->text[byte_i + i] = dot_tmp[i];
i++;
}
label->text[byte_i + i] = dot_tmp[i];
lv_label_dot_tmp_free(obj);
label->dot_end = LV_LABEL_DOT_END_INV;
}
/**
* Store `len` characters from `data`. Allocates space if necessary.
*
* @param label pointer to label object
* @param len Number of characters to store.
* @return true on success.
*/
static bool lv_label_set_dot_tmp(lv_obj_t * obj, char * data, uint32_t len)
{
lv_label_t * label = (lv_label_t *)obj;
lv_label_dot_tmp_free(obj); /*Deallocate any existing space*/
if(len > sizeof(char *)) {
/*Memory needs to be allocated. Allocates an additional byte
*for a NULL-terminator so it can be copied.*/
label->dot.tmp_ptr = lv_mem_alloc(len + 1);
if(label->dot.tmp_ptr == NULL) {
LV_LOG_ERROR("Failed to allocate memory for dot_tmp_ptr");
return false;
}
lv_memcpy(label->dot.tmp_ptr, data, len);
label->dot.tmp_ptr[len] = '\0';
label->dot_tmp_alloc = true;
}
else {
/*Characters can be directly stored in object*/
label->dot_tmp_alloc = false;
lv_memcpy(label->dot.tmp, data, len);
}
return true;
}
/**
* Get the stored dot_tmp characters
* @param label pointer to label object
* @return char pointer to a stored characters. Is *not* necessarily NULL-terminated.
*/
static char * lv_label_get_dot_tmp(lv_obj_t * obj)
{
lv_label_t * label = (lv_label_t *)obj;
if(label->dot_tmp_alloc) {
return label->dot.tmp_ptr;
}
else {
return label->dot.tmp;
}
}
/**
* Free the dot_tmp_ptr field if it was previously allocated.
* Always clears the field
* @param label pointer to label object.
*/
static void lv_label_dot_tmp_free(lv_obj_t * obj)
{
lv_label_t * label = (lv_label_t *)obj;
if(label->dot_tmp_alloc && label->dot.tmp_ptr) {
lv_mem_free(label->dot.tmp_ptr);
}
label->dot_tmp_alloc = false;
label->dot.tmp_ptr = NULL;
}
static void set_ofs_x_anim(void * obj, int32_t v)
{
lv_label_t * label = (lv_label_t *)obj;
label->offset.x = v;
lv_obj_invalidate(obj);
}
static void set_ofs_y_anim(void * obj, int32_t v)
{
lv_label_t * label = (lv_label_t *)obj;
label->offset.y = v;
lv_obj_invalidate(obj);
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_label.c | C | apache-2.0 | 42,285 |
/**
* @file lv_label.h
*
*/
#ifndef LV_LABEL_H
#define LV_LABEL_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_LABEL != 0
#include <stdarg.h>
#include "../core/lv_obj.h"
#include "../font/lv_font.h"
#include "../font/lv_symbol_def.h"
#include "../misc/lv_txt.h"
#include "../draw/lv_draw.h"
/*********************
* DEFINES
*********************/
#define LV_LABEL_WAIT_CHAR_COUNT 3
#define LV_LABEL_DOT_NUM 3
#define LV_LABEL_POS_LAST 0xFFFF
#define LV_LABEL_TEXT_SELECTION_OFF LV_DRAW_LABEL_NO_TXT_SEL
LV_EXPORT_CONST_INT(LV_LABEL_DOT_NUM);
LV_EXPORT_CONST_INT(LV_LABEL_POS_LAST);
LV_EXPORT_CONST_INT(LV_LABEL_TEXT_SELECTION_OFF);
/**********************
* TYPEDEFS
**********************/
/** Long mode behaviors. Used in 'lv_label_ext_t'*/
enum {
LV_LABEL_LONG_WRAP, /**< Keep the object width, wrap the too long lines and expand the object height*/
LV_LABEL_LONG_DOT, /**< Keep the size and write dots at the end if the text is too long*/
LV_LABEL_LONG_SCROLL, /**< Keep the size and roll the text back and forth*/
LV_LABEL_LONG_SCROLL_CIRCULAR, /**< Keep the size and roll the text circularly*/
LV_LABEL_LONG_CLIP, /**< Keep the size and clip the text out of it*/
};
typedef uint8_t lv_label_long_mode_t;
typedef struct {
lv_obj_t obj;
char * text;
union {
char * tmp_ptr; /*Pointer to the allocated memory containing the character replaced by dots*/
char tmp[LV_LABEL_DOT_NUM + 1]; /*Directly store the characters if <=4 characters*/
} dot;
uint32_t dot_end; /*The real text length, used in dot mode*/
#if LV_LABEL_LONG_TXT_HINT
lv_draw_label_hint_t hint;
#endif
#if LV_LABEL_TEXT_SELECTION
uint32_t sel_start;
uint32_t sel_end;
#endif
lv_point_t offset; /*Text draw position offset*/
lv_label_long_mode_t long_mode : 3; /*Determinate what to do with the long texts*/
uint8_t static_txt : 1; /*Flag to indicate the text is static*/
uint8_t recolor : 1; /*Enable in-line letter re-coloring*/
uint8_t expand : 1; /*Ignore real width (used by the library with LV_LABEL_LONG_SROLL)*/
uint8_t dot_tmp_alloc : 1; /*1: dot_tmp has been allocated;.0: dot_tmp directly holds up to 4 bytes of characters*/
} lv_label_t;
extern const lv_obj_class_t lv_label_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a label objects
* @param parent pointer to an object, it will be the parent of the new label.
* @return pointer to the created button
*/
lv_obj_t * lv_label_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set a new text for a label. Memory will be allocated to store the text by the label.
* @param label pointer to a label object
* @param text '\0' terminated character string. NULL to refresh with the current text.
*/
void lv_label_set_text(lv_obj_t * obj, const char * text);
/**
* Set a new formatted text for a label. Memory will be allocated to store the text by the label.
* @param label pointer to a label object
* @param fmt `printf`-like format
* @example lv_label_set_text_fmt(label1, "%d user", user_num);
*/
void lv_label_set_text_fmt(lv_obj_t * obj, const char * fmt, ...) LV_FORMAT_ATTRIBUTE(2, 3);
/**
* Set a static text. It will not be saved by the label so the 'text' variable
* has to be 'alive' while the label exists.
* @param label pointer to a label object
* @param text pointer to a text. NULL to refresh with the current text.
*/
void lv_label_set_text_static(lv_obj_t * obj, const char * text);
/**
* Set the behavior of the label with longer text then the object size
* @param label pointer to a label object
* @param long_mode the new mode from 'lv_label_long_mode' enum.
* In LV_LONG_WRAP/DOT/SCROLL/SCROLL_CIRC the size of the label should be set AFTER this function
*/
void lv_label_set_long_mode(lv_obj_t * obj, lv_label_long_mode_t long_mode);
/**
* Enable the recoloring by in-line commands
* @param label pointer to a label object
* @param en true: enable recoloring, false: disable
* @example "This is a #ff0000 red# word"
*/
void lv_label_set_recolor(lv_obj_t * obj, bool en);
/**
* Set where text selection should start
* @param obj pointer to a label object
* @param index character index from where selection should start. `LV_LABEL_TEXT_SELECTION_OFF` for no selection
*/
void lv_label_set_text_sel_start(lv_obj_t * obj, uint32_t index);
/**
* Set where text selection should end
* @param obj pointer to a label object
* @param index character index where selection should end. `LV_LABEL_TEXT_SELECTION_OFF` for no selection
*/
void lv_label_set_text_sel_end(lv_obj_t * obj, uint32_t index);
/*=====================
* Getter functions
*====================*/
/**
* Get the text of a label
* @param obj pointer to a label object
* @return the text of the label
*/
char * lv_label_get_text(const lv_obj_t * obj);
/**
* Get the long mode of a label
* @param obj pointer to a label object
* @return the current long mode
*/
lv_label_long_mode_t lv_label_get_long_mode(const lv_obj_t * obj);
/**
* Get the recoloring attribute
* @param obj pointer to a label object
* @return true: recoloring is enabled, false: disable
*/
bool lv_label_get_recolor(const lv_obj_t * obj);
/**
* Get the relative x and y coordinates of a letter
* @param obj pointer to a label object
* @param index index of the character [0 ... text length - 1].
* Expressed in character index, not byte index (different in UTF-8)
* @param pos store the result here (E.g. index = 0 gives 0;0 coordinates if the text if aligned to the left)
*/
void lv_label_get_letter_pos(const lv_obj_t * obj, uint32_t char_id, lv_point_t * pos);
/**
* Get the index of letter on a relative point of a label.
* @param obj pointer to label object
* @param pos pointer to point with coordinates on a the label
* @return The index of the letter on the 'pos_p' point (E.g. on 0;0 is the 0. letter if aligned to the left)
* Expressed in character index and not byte index (different in UTF-8)
*/
uint32_t lv_label_get_letter_on(const lv_obj_t * obj, lv_point_t * pos_in);
/**
* Check if a character is drawn under a point.
* @param label Label object
* @param pos Point to check for character under
* @return whether a character is drawn under the point
*/
bool lv_label_is_char_under_pos(const lv_obj_t * obj, lv_point_t * pos);
/**
* @brief Get the selection start index.
* @param obj pointer to a label object.
* @return selection start index. `LV_LABEL_TEXT_SELECTION_OFF` if nothing is selected.
*/
uint32_t lv_label_get_text_selection_start(const lv_obj_t * obj);
/**
* @brief Get the selection end index.
* @param obj pointer to a label object.
* @return selection end index. `LV_LABEL_TXT_SEL_OFF` if nothing is selected.
*/
uint32_t lv_label_get_text_selection_end(const lv_obj_t * obj);
/*=====================
* Other functions
*====================*/
/**
* Insert a text to a label. The label text can not be static.
* @param obj pointer to a label object
* @param pos character index to insert. Expressed in character index and not byte index.
* 0: before first char. LV_LABEL_POS_LAST: after last char.
* @param txt pointer to the text to insert
*/
void lv_label_ins_text(lv_obj_t * obj, uint32_t pos, const char * txt);
/**
* Delete characters from a label. The label text can not be static.
* @param label pointer to a label object
* @param pos character index from where to cut. Expressed in character index and not byte index.
* 0: start in from of the first character
* @param cnt number of characters to cut
*/
void lv_label_cut_text(lv_obj_t * obj, uint32_t pos, uint32_t cnt);
/**********************
* MACROS
**********************/
#endif /*LV_USE_LABEL*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_LABEL_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_label.h | C | apache-2.0 | 8,420 |
/**
* @file lv_line.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_line.h"
#if LV_USE_LINE != 0
#include "../misc/lv_assert.h"
#include "../draw/lv_draw.h"
#include "../misc/lv_math.h"
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_line_class
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_line_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_line_event(const lv_obj_class_t * class_p, lv_event_t * e);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_line_class = {
.constructor_cb = lv_line_constructor,
.event_cb = lv_line_event,
.width_def = LV_SIZE_CONTENT,
.height_def = LV_SIZE_CONTENT,
.instance_size = sizeof(lv_line_t),
.base_class = &lv_obj_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_line_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*=====================
* Setter functions
*====================*/
void lv_line_set_points(lv_obj_t * obj, const lv_point_t points[], uint16_t point_num)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_line_t * line = (lv_line_t *)obj;
line->point_array = points;
line->point_num = point_num;
lv_obj_refresh_self_size(obj);
lv_obj_invalidate(obj);
}
void lv_line_set_y_invert(lv_obj_t * obj, bool en)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_line_t * line = (lv_line_t *)obj;
if(line->y_inv == en) return;
line->y_inv = en == false ? 0 : 1;
lv_obj_invalidate(obj);
}
/*=====================
* Getter functions
*====================*/
bool lv_line_get_y_invert(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_line_t * line = (lv_line_t *)obj;
return line->y_inv == 0 ? false : true;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_line_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_line_t * line = (lv_line_t *)obj;
line->point_num = 0;
line->point_array = NULL;
line->y_inv = 0;
lv_obj_clear_flag(obj, LV_OBJ_FLAG_CLICKABLE);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_line_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
if(code == LV_EVENT_REFR_EXT_DRAW_SIZE) {
/*The corner of the skew lines is out of the intended area*/
lv_coord_t line_width = lv_obj_get_style_line_width(obj, LV_PART_MAIN);
lv_coord_t * s = lv_event_get_param(e);
if(*s < line_width) *s = line_width;
}
else if(code == LV_EVENT_GET_SELF_SIZE) {
lv_line_t * line = (lv_line_t *)obj;
lv_point_t * p = lv_event_get_param(e);
lv_coord_t w = 0;
lv_coord_t h = 0;
if(line->point_num > 0) {
uint16_t i;
for(i = 0; i < line->point_num; i++) {
w = LV_MAX(line->point_array[i].x, w);
h = LV_MAX(line->point_array[i].y, h);
}
lv_coord_t line_width = lv_obj_get_style_line_width(obj, LV_PART_MAIN);
w += line_width;
h += line_width;
p->x = w;
p->y = h;
}
}
else if(code == LV_EVENT_DRAW_MAIN) {
lv_line_t * line = (lv_line_t *)obj;
const lv_area_t * clip_area = lv_event_get_param(e);
if(line->point_num == 0 || line->point_array == NULL) return;
lv_area_t area;
lv_obj_get_coords(obj, &area);
lv_coord_t x_ofs = area.x1 - lv_obj_get_scroll_x(obj);
lv_coord_t y_ofs = area.y1 - lv_obj_get_scroll_y(obj);
lv_point_t p1;
lv_point_t p2;
lv_coord_t h = lv_obj_get_height(obj);
uint16_t i;
lv_draw_line_dsc_t line_dsc;
lv_draw_line_dsc_init(&line_dsc);
lv_obj_init_draw_line_dsc(obj, LV_PART_MAIN, &line_dsc);
/*Read all points and draw the lines*/
for(i = 0; i < line->point_num - 1; i++) {
p1.x = line->point_array[i].x + x_ofs;
p2.x = line->point_array[i + 1].x + x_ofs;
if(line->y_inv == 0) {
p1.y = line->point_array[i].y + y_ofs;
p2.y = line->point_array[i + 1].y + y_ofs;
}
else {
p1.y = h - line->point_array[i].y + y_ofs;
p2.y = h - line->point_array[i + 1].y + y_ofs;
}
lv_draw_line(&p1, &p2, clip_area, &line_dsc);
line_dsc.round_start = 0; /*Draw the rounding only on the end points after the first line*/
}
}
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_line.c | C | apache-2.0 | 5,256 |
/**
* @file lv_line.h
*
*/
#ifndef LV_LINE_H
#define LV_LINE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_LINE != 0
#include "../core/lv_obj.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/*Data of line*/
typedef struct {
lv_obj_t obj;
const lv_point_t * point_array; /**< Pointer to an array with the points of the line*/
uint16_t point_num; /**< Number of points in 'point_array'*/
uint8_t y_inv : 1; /**< 1: y == 0 will be on the bottom*/
} lv_line_t;
extern const lv_obj_class_t lv_line_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a line objects
* @param par pointer to an object, it will be the parent of the new line
* @return pointer to the created line
*/
lv_obj_t * lv_line_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set an array of points. The line object will connect these points.
* @param obj pointer to a line object
* @param points an array of points. Only the address is saved, so the array needs to be alive while the line exists
* @param point_num number of points in 'point_a'
*/
void lv_line_set_points(lv_obj_t * obj, const lv_point_t points[], uint16_t point_num);
/**
* Enable (or disable) the y coordinate inversion.
* If enabled then y will be subtracted from the height of the object,
* therefore the y = 0 coordinate will be on the bottom.
* @param obj pointer to a line object
* @param en true: enable the y inversion, false:disable the y inversion
*/
void lv_line_set_y_invert(lv_obj_t * obj, bool en);
/*=====================
* Getter functions
*====================*/
/**
* Get the y inversion attribute
* @param obj pointer to a line object
* @return true: y inversion is enabled, false: disabled
*/
bool lv_line_get_y_invert(const lv_obj_t * obj);
/**********************
* MACROS
**********************/
#endif /*LV_USE_LINE*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_LINE_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_line.h | C | apache-2.0 | 2,272 |
/**
* @file lv_templ.c
*
*/
/**
* TODO Remove these instructions
* Search and replace: templ -> object short name with lower case(e.g. btn, label etc)
* TEMPL -> object short name with upper case (e.g. BTN, LABEL etc.)
*
* You can remove the defined() clause from the #if statement below. This exists because
* LV_USE_TEMPL is not in lv_conf.h or lv_conf_template.h by default.
*/
/*********************
* INCLUDES
*********************/
//#include "lv_templ.h" /*TODO uncomment this*/
#if defined(LV_USE_TEMPL) && LV_USE_TEMPL != 0
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_templ_class
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_templ_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_templ_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_templ_event(const lv_obj_class_t * class_p, lv_event_t * e);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_templ_class = {
.constructor_cb = lv_templ_constructor,
.destructor_cb = lv_templ_destructor,
.event_cb = lv_templ_event,
.width_def = LV_DPI_DEF,
.height_def = LV_DPI_DEF,
.instance_size = sizeof(lv_templ_t),
.group_def = LV_OBJ_CLASS_GROUP_DEF_INHERIT,
.editable = LV_OBJ_CLASS_EDITABLE_INHERIT,
.base_class = &lv_templ_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_templ_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*======================
* Add/remove functions
*=====================*/
/*
* New object specific "add" or "remove" functions come here
*/
/*=====================
* Setter functions
*====================*/
/*
* New object specific "set" functions come here
*/
/*=====================
* Getter functions
*====================*/
/*
* New object specific "get" functions come here
*/
/*=====================
* Other functions
*====================*/
/*
* New object specific "other" functions come here
*/
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_templ_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_templ_t * templ = (lv_templ_t *)obj;
/*Initialize the widget's data*/
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_templ_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
lv_templ_t * templ = (lv_templ_t *)obj;
/*Free the widget specific data*/
}
static void lv_templ_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
/*Add the widget specific event handling here*/
}
#else /*Enable this file at the top*/
/*This dummy typedef exists purely to silence -Wpedantic.*/
typedef int keep_pedantic_happy;
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_objx_templ.c | C | apache-2.0 | 3,300 |
/**
* @file lv_templ.h
*
*/
/**
* TODO Remove these instructions
* Search and replace: templ -> object short name with lower case(e.g. btn, label etc)
* TEMPL -> object short name with upper case (e.g. BTN, LABEL etc.)
*
*/
#ifndef LV_TEMPL_H
#define LV_TEMPL_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_TEMPL != 0
#include "../core/lv_obj.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/*Data of template*/
typedef struct {
lv_ANCESTOR_t ancestor; /*The ancestor widget, e.g. lv_slider_t slider*/
/*New data for this type*/
} lv_templ_t;
extern const lv_obj_class_t lv_templ_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a templ objects
* @param parent pointer to an object, it will be the parent of the new templ
* @return pointer to the created bar
*/
lv_obj_t * lv_templ_create(lv_obj_t * parent);
/*======================
* Add/remove functions
*=====================*/
/*=====================
* Setter functions
*====================*/
/*=====================
* Getter functions
*====================*/
/*=====================
* Other functions
*====================*/
/**********************
* MACROS
**********************/
#endif /*LV_USE_TEMPL*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_TEMPL_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_objx_templ.h | C | apache-2.0 | 1,540 |
/**
* @file lv_roller.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_roller.h"
#if LV_USE_ROLLER != 0
#include "../misc/lv_assert.h"
#include "../draw/lv_draw.h"
#include "../core/lv_group.h"
#include "../core/lv_indev.h"
#include "../core/lv_indev_scroll.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_roller_class
#define MY_CLASS_LABEL &lv_roller_label_class
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_roller_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_roller_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void lv_roller_label_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void draw_main(lv_event_t * e);
static void draw_label(lv_event_t * e);
static void get_sel_area(lv_obj_t * obj, lv_area_t * sel_area);
static void refr_position(lv_obj_t * obj, lv_anim_enable_t animen);
static lv_res_t release_handler(lv_obj_t * obj);
static void inf_normalize(lv_obj_t * obj_scrl);
static lv_obj_t * get_label(const lv_obj_t * obj);
static lv_coord_t get_selected_label_width(const lv_obj_t * obj);
static void scroll_anim_ready_cb(lv_anim_t * a);
static void set_y_anim(void * obj, int32_t v);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_roller_class = {
.constructor_cb = lv_roller_constructor,
.event_cb = lv_roller_event,
.width_def = LV_SIZE_CONTENT,
.height_def = LV_DPI_DEF,
.instance_size = sizeof(lv_roller_t),
.editable = LV_OBJ_CLASS_EDITABLE_TRUE,
.group_def = LV_OBJ_CLASS_GROUP_DEF_TRUE,
.base_class = &lv_obj_class
};
const lv_obj_class_t lv_roller_label_class = {
.event_cb = lv_roller_label_event,
.instance_size = sizeof(lv_label_t),
.base_class = &lv_label_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Create a roller object
* @param par pointer to an object, it will be the parent of the new roller
* @return pointer to the created roller
*/
lv_obj_t * lv_roller_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*=====================
* Setter functions
*====================*/
/**
* Set the options on a roller
* @param roller pointer to roller object
* @param options a string with '\n' separated options. E.g. "One\nTwo\nThree"
* @param mode `LV_ROLLER_MODE_NORMAL` or `LV_ROLLER_MODE_INFINITE`
*/
void lv_roller_set_options(lv_obj_t * obj, const char * options, lv_roller_mode_t mode)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(options);
lv_roller_t * roller = (lv_roller_t *)obj;
lv_obj_t * label = get_label(obj);
roller->sel_opt_id = 0;
roller->sel_opt_id_ori = 0;
/*Count the '\n'-s to determine the number of options*/
roller->option_cnt = 0;
uint32_t cnt;
for(cnt = 0; options[cnt] != '\0'; cnt++) {
if(options[cnt] == '\n') roller->option_cnt++;
}
roller->option_cnt++; /*Last option has no `\n`*/
if(mode == LV_ROLLER_MODE_NORMAL) {
roller->mode = LV_ROLLER_MODE_NORMAL;
lv_label_set_text(label, options);
}
else {
roller->mode = LV_ROLLER_MODE_INFINITE;
size_t opt_len = strlen(options) + 1; /*+1 to add '\n' after option lists*/
char * opt_extra = lv_mem_buf_get(opt_len * LV_ROLLER_INF_PAGES);
uint8_t i;
for(i = 0; i < LV_ROLLER_INF_PAGES; i++) {
strcpy(&opt_extra[opt_len * i], options);
opt_extra[opt_len * (i + 1) - 1] = '\n';
}
opt_extra[opt_len * LV_ROLLER_INF_PAGES - 1] = '\0';
lv_label_set_text(label, opt_extra);
lv_mem_buf_release(opt_extra);
roller->sel_opt_id = ((LV_ROLLER_INF_PAGES / 2) + 0) * roller->option_cnt;
roller->option_cnt = roller->option_cnt * LV_ROLLER_INF_PAGES;
inf_normalize(obj);
}
roller->sel_opt_id_ori = roller->sel_opt_id;
/*If the selected text has larger font the label needs some extra draw padding to draw it.*/
lv_obj_refresh_ext_draw_size(label);
}
/**
* Set the selected option
* @param roller pointer to a roller object
* @param sel_opt id of the selected option (0 ... number of option - 1);
* @param anim_en LV_ANIM_ON: set with animation; LV_ANOM_OFF set immediately
*/
void lv_roller_set_selected(lv_obj_t * obj, uint16_t sel_opt, lv_anim_enable_t anim)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
/*Set the value even if it's the same as the current value because
*if moving to the next option with an animation which was just deleted in the PRESS Call the ancestor's event handler
*nothing will continue the animation.*/
lv_roller_t * roller = (lv_roller_t *)obj;
/*In infinite mode interpret the new ID relative to the currently visible "page"*/
if(roller->mode == LV_ROLLER_MODE_INFINITE) {
int32_t sel_opt_signed = sel_opt;
uint16_t page = roller->sel_opt_id / LV_ROLLER_INF_PAGES;
/*`sel_opt` should be less than the number of options set by the user.
*If it's more then probably it's a reference from not the first page
*so normalize `sel_opt`*/
if(page != 0) {
sel_opt_signed -= page * LV_ROLLER_INF_PAGES;
}
sel_opt = page * LV_ROLLER_INF_PAGES + sel_opt_signed;
}
roller->sel_opt_id = sel_opt < roller->option_cnt ? sel_opt : roller->option_cnt - 1;
roller->sel_opt_id_ori = roller->sel_opt_id;
refr_position(obj, anim);
}
/**
* Set the height to show the given number of rows (options)
* @param roller pointer to a roller object
* @param row_cnt number of desired visible rows
*/
void lv_roller_set_visible_row_count(lv_obj_t * obj, uint8_t row_cnt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_coord_t border_width = lv_obj_get_style_border_width(obj, LV_PART_MAIN);
lv_obj_set_height(obj, (lv_font_get_line_height(font) + line_space) * row_cnt + 2 * border_width);
}
/*=====================
* Getter functions
*====================*/
/**
* Get the id of the selected option
* @param roller pointer to a roller object
* @return id of the selected option (0 ... number of option - 1);
*/
uint16_t lv_roller_get_selected(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_roller_t * roller = (lv_roller_t *)obj;
if(roller->mode == LV_ROLLER_MODE_INFINITE) {
uint16_t real_id_cnt = roller->option_cnt / LV_ROLLER_INF_PAGES;
return roller->sel_opt_id % real_id_cnt;
}
else {
return roller->sel_opt_id;
}
}
/**
* Get the current selected option as a string
* @param ddlist pointer to ddlist object
* @param buf pointer to an array to store the string
* @param buf_size size of `buf` in bytes. 0: to ignore it.
*/
void lv_roller_get_selected_str(const lv_obj_t * obj, char * buf, uint32_t buf_size)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_roller_t * roller = (lv_roller_t *)obj;
lv_obj_t * label = get_label(obj);
uint32_t i;
uint16_t line = 0;
const char * opt_txt = lv_label_get_text(label);
size_t txt_len = strlen(opt_txt);
for(i = 0; i < txt_len && line != roller->sel_opt_id; i++) {
if(opt_txt[i] == '\n') line++;
}
uint32_t c;
for(c = 0; i < txt_len && opt_txt[i] != '\n'; c++, i++) {
if(buf_size && c >= buf_size - 1) {
LV_LOG_WARN("lv_dropdown_get_selected_str: the buffer was too small");
break;
}
buf[c] = opt_txt[i];
}
buf[c] = '\0';
}
/**
* Get the options of a roller
* @param roller pointer to roller object
* @return the options separated by '\n'-s (E.g. "Option1\nOption2\nOption3")
*/
const char * lv_roller_get_options(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
return lv_label_get_text(get_label(obj));
}
/**
* Get the total number of options
* @param roller pointer to a roller object
* @return the total number of options
*/
uint16_t lv_roller_get_option_cnt(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_roller_t * roller = (lv_roller_t *)obj;
if(roller->mode == LV_ROLLER_MODE_INFINITE) {
return roller->option_cnt / LV_ROLLER_INF_PAGES;
}
else {
return roller->option_cnt;
}
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_roller_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_roller_t * roller = (lv_roller_t *)obj;
roller->mode = LV_ROLLER_MODE_NORMAL;
roller->option_cnt = 0;
roller->sel_opt_id = 0;
roller->sel_opt_id_ori = 0;
lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLL_CHAIN);
LV_LOG_INFO("begin");
lv_obj_t * label = lv_obj_class_create_obj(&lv_roller_label_class, obj);
lv_obj_class_init_obj(label);
lv_roller_set_options(obj, "Option 1\nOption 2\nOption 3\nOption 4\nOption 5", LV_ROLLER_MODE_NORMAL);
LV_LOG_TRACE("finshed");
}
static void lv_roller_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
lv_roller_t * roller = (lv_roller_t *)obj;
if(code == LV_EVENT_GET_SELF_SIZE) {
lv_point_t * p = lv_event_get_param(e);
p->x = get_selected_label_width(obj);
}
else if(code == LV_EVENT_STYLE_CHANGED) {
lv_obj_t * label = get_label(obj);
/*Be sure the label's style is updated before processing the roller*/
if(label) lv_event_send(label, LV_EVENT_STYLE_CHANGED, NULL);
lv_obj_refresh_self_size(obj);
refr_position(obj, false);
}
else if(code == LV_EVENT_SIZE_CHANGED) {
refr_position(obj, false);
}
else if(code == LV_EVENT_PRESSED) {
roller->moved = 0;
lv_anim_del(get_label(obj), set_y_anim);
}
else if(code == LV_EVENT_PRESSING) {
lv_indev_t * indev = lv_indev_get_act();
lv_point_t p;
lv_indev_get_vect(indev, &p);
if(p.y) {
lv_obj_t * label = get_label(obj);
lv_obj_set_y(label, lv_obj_get_y(label) + p.y);
roller->moved = 1;
}
}
else if(code == LV_EVENT_RELEASED) {
release_handler(obj);
}
else if(code == LV_EVENT_FOCUSED) {
lv_group_t * g = lv_obj_get_group(obj);
bool editing = lv_group_get_editing(g);
lv_indev_type_t indev_type = lv_indev_get_type(lv_indev_get_act());
/*Encoders need special handling*/
if(indev_type == LV_INDEV_TYPE_ENCODER) {
/*In navigate mode revert the original value*/
if(!editing) {
if(roller->sel_opt_id != roller->sel_opt_id_ori) {
roller->sel_opt_id = roller->sel_opt_id_ori;
refr_position(obj, true);
}
}
/*Save the current state when entered to edit mode*/
else {
roller->sel_opt_id_ori = roller->sel_opt_id;
}
}
else {
roller->sel_opt_id_ori = roller->sel_opt_id; /*Save the current value. Used to revert this state if
ENTER won't be pressed*/
}
}
else if(code == LV_EVENT_DEFOCUSED) {
/*Revert the original state*/
if(roller->sel_opt_id != roller->sel_opt_id_ori) {
roller->sel_opt_id = roller->sel_opt_id_ori;
refr_position(obj, true);
}
}
else if(code == LV_EVENT_KEY) {
char c = *((char *)lv_event_get_param(e));
if(c == LV_KEY_RIGHT || c == LV_KEY_DOWN) {
if(roller->sel_opt_id + 1 < roller->option_cnt) {
uint16_t ori_id = roller->sel_opt_id_ori; /*lv_roller_set_selected will overwrite this*/
lv_roller_set_selected(obj, roller->sel_opt_id + 1, true);
roller->sel_opt_id_ori = ori_id;
}
}
else if(c == LV_KEY_LEFT || c == LV_KEY_UP) {
if(roller->sel_opt_id > 0) {
uint16_t ori_id = roller->sel_opt_id_ori; /*lv_roller_set_selected will overwrite this*/
lv_roller_set_selected(obj, roller->sel_opt_id - 1, true);
roller->sel_opt_id_ori = ori_id;
}
}
}
else if(code == LV_EVENT_REFR_EXT_DRAW_SIZE) {
lv_obj_t * label = get_label(obj);
lv_obj_refresh_ext_draw_size(label);
}
else if(code == LV_EVENT_DRAW_MAIN || code == LV_EVENT_DRAW_POST) {
draw_main(e);
}
}
static void lv_roller_label_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
lv_event_code_t code = lv_event_get_code(e);
/*LV_EVENT_DRAW_MAIN will be called in the draw function*/
if(code != LV_EVENT_DRAW_MAIN) {
/* Call the ancestor's event handler */
res = lv_obj_event_base(MY_CLASS_LABEL, e);
if(res != LV_RES_OK) return;
}
lv_obj_t * label = lv_event_get_target(e);
if(code == LV_EVENT_REFR_EXT_DRAW_SIZE) {
/*If the selected text has a larger font it needs some extra space to draw it*/
lv_coord_t * s = lv_event_get_param(e);
lv_obj_t * obj = lv_obj_get_parent(label);
lv_coord_t sel_w = get_selected_label_width(obj);
lv_coord_t label_w = lv_obj_get_width(label);
*s = LV_MAX(*s, sel_w - label_w);
}
else if(code == LV_EVENT_SIZE_CHANGED) {
refr_position(lv_obj_get_parent(label), LV_ANIM_OFF);
}
else if(code == LV_EVENT_DRAW_MAIN) {
draw_label(e);
}
}
static void draw_main(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
if(code == LV_EVENT_DRAW_MAIN) {
/*Draw the selected rectangle*/
const lv_area_t * clip_area = lv_event_get_param(e);
lv_area_t sel_area;
get_sel_area(obj, &sel_area);
lv_draw_rect_dsc_t sel_dsc;
lv_draw_rect_dsc_init(&sel_dsc);
lv_obj_init_draw_rect_dsc(obj, LV_PART_SELECTED, &sel_dsc);
lv_draw_rect(&sel_area, clip_area, &sel_dsc);
}
/*Post draw when the children are drawn*/
else if(code == LV_EVENT_DRAW_POST) {
const lv_area_t * clip_area = lv_event_get_param(e);
lv_draw_label_dsc_t label_dsc;
lv_draw_label_dsc_init(&label_dsc);
lv_obj_init_draw_label_dsc(obj, LV_PART_SELECTED, &label_dsc);
/*Redraw the text on the selected area*/
lv_area_t sel_area;
get_sel_area(obj, &sel_area);
lv_area_t mask_sel;
bool area_ok;
area_ok = _lv_area_intersect(&mask_sel, clip_area, &sel_area);
if(area_ok) {
lv_obj_t * label = get_label(obj);
/*Get the size of the "selected text"*/
lv_point_t res_p;
lv_txt_get_size(&res_p, lv_label_get_text(label), label_dsc.font, label_dsc.letter_space, label_dsc.line_space,
lv_obj_get_width(obj), LV_TEXT_FLAG_EXPAND);
/*Move the selected label proportionally with the background label*/
lv_coord_t roller_h = lv_obj_get_height(obj);
int32_t label_y_prop = label->coords.y1 - (roller_h / 2 +
obj->coords.y1); /*label offset from the middle line of the roller*/
label_y_prop = (label_y_prop * 16384) / lv_obj_get_height(
label); /*Proportional position from the middle line (upscaled by << 14)*/
/*Apply a correction with different line heights*/
const lv_font_t * normal_label_font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t corr = (label_dsc.font->line_height - normal_label_font->line_height) / 2;
/*Apply the proportional position to the selected text*/
res_p.y -= corr;
int32_t label_sel_y = roller_h / 2 + obj->coords.y1;
label_sel_y += (label_y_prop * res_p.y) >> 14;
label_sel_y -= corr;
lv_coord_t bwidth = lv_obj_get_style_border_width(obj, LV_PART_MAIN);
lv_coord_t pleft = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t pright = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
/*Draw the selected text*/
lv_area_t label_sel_area;
label_sel_area.x1 = obj->coords.x1 + pleft + bwidth;
label_sel_area.y1 = label_sel_y;
label_sel_area.x2 = obj->coords.x2 - pright - bwidth;
label_sel_area.y2 = label_sel_area.y1 + res_p.y;
label_dsc.flag |= LV_TEXT_FLAG_EXPAND;
lv_draw_label(&label_sel_area, &mask_sel, &label_dsc, lv_label_get_text(label), NULL);
}
}
}
static void draw_label(lv_event_t * e)
{
/* Split the drawing of the label into an upper (above the selected area)
* and a lower (below the selected area)*/
lv_obj_t * label_obj = lv_event_get_target(e);
lv_obj_t * roller = lv_obj_get_parent(label_obj);
lv_draw_label_dsc_t label_draw_dsc;
lv_draw_label_dsc_init(&label_draw_dsc);
lv_obj_init_draw_label_dsc(roller, LV_PART_MAIN, &label_draw_dsc);
const lv_area_t * clip_area = lv_event_get_param(e);
lv_area_t sel_area;
get_sel_area(roller, &sel_area);
lv_area_t clip2;
clip2.x1 = label_obj->coords.x1;
clip2.y1 = label_obj->coords.y1;
clip2.x2 = label_obj->coords.x2;
clip2.y2 = sel_area.y1;
if(_lv_area_intersect(&clip2, clip_area, &clip2)) {
lv_draw_label(&label_obj->coords, &clip2, &label_draw_dsc, lv_label_get_text(label_obj), NULL);
}
clip2.x1 = label_obj->coords.x1;
clip2.y1 = sel_area.y2;
clip2.x2 = label_obj->coords.x2;
clip2.y2 = label_obj->coords.y2;
if(_lv_area_intersect(&clip2, clip_area, &clip2)) {
lv_draw_label(&label_obj->coords, &clip2, &label_draw_dsc, lv_label_get_text(label_obj), NULL);
}
}
static void get_sel_area(lv_obj_t * obj, lv_area_t * sel_area)
{
const lv_font_t * font_main = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
const lv_font_t * font_sel = lv_obj_get_style_text_font(obj, LV_PART_SELECTED);
lv_coord_t font_main_h = lv_font_get_line_height(font_main);
lv_coord_t font_sel_h = lv_font_get_line_height(font_sel);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_coord_t d = (font_sel_h + font_main_h) / 2 + line_space;
sel_area->y1 = obj->coords.y1 + lv_obj_get_height(obj) / 2 - d / 2;
sel_area->y2 = sel_area->y1 + d;
lv_area_t roller_coords;
lv_obj_get_coords(obj, &roller_coords);
sel_area->x1 = roller_coords.x1;
sel_area->x2 = roller_coords.x2;
}
/**
* Refresh the position of the roller. It uses the id stored in: roller->ddlist.selected_option_id
* @param roller pointer to a roller object
* @param anim_en LV_ANIM_ON: refresh with animation; LV_ANOM_OFF: without animation
*/
static void refr_position(lv_obj_t * obj, lv_anim_enable_t anim_en)
{
lv_obj_t * label = get_label(obj);
if(label == NULL) return;
lv_text_align_t align = lv_obj_calculate_style_text_align(label, LV_PART_MAIN, lv_label_get_text(label));
switch(align) {
case LV_TEXT_ALIGN_CENTER:
lv_obj_set_x(label, (lv_obj_get_content_width(obj) - lv_obj_get_width(label)) / 2);
break;
case LV_TEXT_ALIGN_RIGHT:
lv_obj_set_x(label, lv_obj_get_content_width(obj) - lv_obj_get_width(label));
break;
case LV_TEXT_ALIGN_LEFT:
lv_obj_set_x(label, 0);
break;
}
lv_roller_t * roller = (lv_roller_t *)obj;
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_coord_t font_h = lv_font_get_line_height(font);
lv_coord_t h = lv_obj_get_content_height(obj);
uint16_t anim_time = lv_obj_get_style_anim_time(obj, LV_PART_MAIN);
/*Normally the animation's `end_cb` sets correct position of the roller if infinite.
*But without animations do it manually*/
if(anim_en == LV_ANIM_OFF || anim_time == 0) {
inf_normalize(obj);
}
int32_t id = roller->sel_opt_id;
lv_coord_t sel_y1 = id * (font_h + line_space);
lv_coord_t mid_y1 = h / 2 - font_h / 2;
lv_coord_t new_y = mid_y1 - sel_y1;
if(anim_en == LV_ANIM_OFF || anim_time == 0) {
lv_anim_del(label, set_y_anim);
lv_obj_set_y(label, new_y);
}
else {
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, label);
lv_anim_set_exec_cb(&a, set_y_anim);
lv_anim_set_values(&a, lv_obj_get_y(label), new_y);
lv_anim_set_time(&a, anim_time);
lv_anim_set_ready_cb(&a, scroll_anim_ready_cb);
lv_anim_set_path_cb(&a, lv_anim_path_ease_out);
lv_anim_start(&a);
}
}
static lv_res_t release_handler(lv_obj_t * obj)
{
lv_obj_t * label = get_label(obj);
if(label == NULL) return LV_RES_OK;
lv_indev_t * indev = lv_indev_get_act();
lv_roller_t * roller = (lv_roller_t *)obj;
/*Leave edit mode once a new option is selected*/
lv_indev_type_t indev_type = lv_indev_get_type(indev);
if(indev_type == LV_INDEV_TYPE_ENCODER || indev_type == LV_INDEV_TYPE_KEYPAD) {
roller->sel_opt_id_ori = roller->sel_opt_id;
if(indev_type == LV_INDEV_TYPE_ENCODER) {
lv_group_t * g = lv_obj_get_group(obj);
if(lv_group_get_editing(g)) {
lv_group_set_editing(g, false);
}
}
}
if(lv_indev_get_type(indev) == LV_INDEV_TYPE_POINTER || lv_indev_get_type(indev) == LV_INDEV_TYPE_BUTTON) {
/*Search the clicked option (For KEYPAD and ENCODER the new value should be already set)*/
int16_t new_opt = -1;
if(roller->moved == 0) {
new_opt = 0;
lv_point_t p;
lv_indev_get_point(indev, &p);
p.y -= label->coords.y1;
p.x -= label->coords.x1;
uint32_t letter_i;
letter_i = lv_label_get_letter_on(label, &p);
const char * txt = lv_label_get_text(label);
uint32_t i = 0;
uint32_t i_prev = 0;
uint32_t letter_cnt = 0;
for(letter_cnt = 0; letter_cnt < letter_i; letter_cnt++) {
uint32_t letter = _lv_txt_encoded_next(txt, &i);
/*Count he lines to reach the clicked letter. But ignore the last '\n' because it
* still belongs to the clicked line*/
if(letter == '\n' && i_prev != letter_i) new_opt++;
i_prev = i;
}
}
else {
/*If dragged then align the list to have an element in the middle*/
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_coord_t font_h = lv_font_get_line_height(font);
lv_coord_t label_unit = font_h + line_space;
lv_coord_t mid = obj->coords.y1 + (obj->coords.y2 - obj->coords.y1) / 2;
lv_coord_t label_y1 = label->coords.y1 + lv_indev_scroll_throw_predict(indev, LV_DIR_VER);
int32_t id = (mid - label_y1) / label_unit;
if(id < 0) id = 0;
if(id >= roller->option_cnt) id = roller->option_cnt - 1;
new_opt = id;
}
if(new_opt >= 0) {
lv_roller_set_selected(obj, new_opt, LV_ANIM_ON);
}
}
uint32_t id = roller->sel_opt_id; /*Just to use uint32_t in event data*/
lv_res_t res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, &id);
return res;
}
/**
* Set the middle page for the roller if infinite is enabled
* @param roller pointer to a roller object
*/
static void inf_normalize(lv_obj_t * obj)
{
lv_roller_t * roller = (lv_roller_t *)obj;
if(roller->mode == LV_ROLLER_MODE_INFINITE) {
uint16_t real_id_cnt = roller->option_cnt / LV_ROLLER_INF_PAGES;
roller->sel_opt_id = roller->sel_opt_id % real_id_cnt;
roller->sel_opt_id += (LV_ROLLER_INF_PAGES / 2) * real_id_cnt; /*Select the middle page*/
roller->sel_opt_id_ori = roller->sel_opt_id % real_id_cnt;
roller->sel_opt_id_ori += (LV_ROLLER_INF_PAGES / 2) * real_id_cnt; /*Select the middle page*/
/*Move to the new id*/
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
lv_coord_t font_h = lv_font_get_line_height(font);
lv_coord_t h = lv_obj_get_content_height(obj);
lv_obj_t * label = get_label(obj);
lv_coord_t sel_y1 = roller->sel_opt_id * (font_h + line_space);
lv_coord_t mid_y1 = h / 2 - font_h / 2;
lv_coord_t new_y = mid_y1 - sel_y1;
lv_obj_set_y(label, new_y);
}
}
static lv_obj_t * get_label(const lv_obj_t * obj)
{
return lv_obj_get_child(obj, 0);
}
static lv_coord_t get_selected_label_width(const lv_obj_t * obj)
{
lv_obj_t * label = get_label(obj);
if(label == NULL) return 0;
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_SELECTED);
lv_coord_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_SELECTED);
const char * txt = lv_label_get_text(label);
lv_point_t size;
lv_txt_get_size(&size, txt, font, letter_space, 0, LV_COORD_MAX, LV_TEXT_FLAG_NONE);
return size.x;
}
static void scroll_anim_ready_cb(lv_anim_t * a)
{
lv_obj_t * obj = lv_obj_get_parent(a->var); /*The label is animated*/
inf_normalize(obj);
}
static void set_y_anim(void * obj, int32_t v)
{
lv_obj_set_y(obj, v);
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_roller.c | C | apache-2.0 | 26,603 |
/**
* @file lv_roller.h
*
*/
#ifndef LV_ROLLER_H
#define LV_ROLLER_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_ROLLER != 0
#include "../core/lv_obj.h"
#include "lv_label.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/** Roller mode.*/
enum {
LV_ROLLER_MODE_NORMAL, /**< Normal mode (roller ends at the end of the options).*/
LV_ROLLER_MODE_INFINITE, /**< Infinite mode (roller can be scrolled forever).*/
};
typedef uint8_t lv_roller_mode_t;
typedef struct {
lv_obj_t obj;
uint16_t option_cnt; /**< Number of options*/
uint16_t sel_opt_id; /**< Index of the current option*/
uint16_t sel_opt_id_ori; /**< Store the original index on focus*/
lv_roller_mode_t mode : 1;
uint32_t moved : 1;
} lv_roller_t;
extern const lv_obj_class_t lv_roller_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a roller objects
* @param parent pointer to an object, it will be the parent of the new roller.
* @return pointer to the created roller
*/
lv_obj_t * lv_roller_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set the options on a roller
* @param obj pointer to roller object
* @param options a string with '\n' separated options. E.g. "One\nTwo\nThree"
* @param mode `LV_ROLLER_MODE_NORMAL` or `LV_ROLLER_MODE_INFINITE`
*/
void lv_roller_set_options(lv_obj_t * obj, const char * options, lv_roller_mode_t mode);
/**
* Set the selected option
* @param obj pointer to a roller object
* @param sel_opt index of the selected option (0 ... number of option - 1);
* @param anim_en LV_ANIM_ON: set with animation; LV_ANOM_OFF set immediately
*/
void lv_roller_set_selected(lv_obj_t * obj, uint16_t sel_opt, lv_anim_enable_t anim);
/**
* Set the height to show the given number of rows (options)
* @param obj pointer to a roller object
* @param row_cnt number of desired visible rows
*/
void lv_roller_set_visible_row_count(lv_obj_t * obj, uint8_t row_cnt);
/*=====================
* Getter functions
*====================*/
/**
* Get the index of the selected option
* @param obj pointer to a roller object
* @return index of the selected option (0 ... number of option - 1);
*/
uint16_t lv_roller_get_selected(const lv_obj_t * obj);
/**
* Get the current selected option as a string.
* @param obj pointer to ddlist object
* @param buf pointer to an array to store the string
* @param buf_size size of `buf` in bytes. 0: to ignore it.
*/
void lv_roller_get_selected_str(const lv_obj_t * obj, char * buf, uint32_t buf_size);
/**
* Get the options of a roller
* @param obj pointer to roller object
* @return the options separated by '\n'-s (E.g. "Option1\nOption2\nOption3")
*/
const char * lv_roller_get_options(const lv_obj_t * obj);
/**
* Get the total number of options
* @param obj pointer to a roller object
* @return the total number of options
*/
uint16_t lv_roller_get_option_cnt(const lv_obj_t * obj);
/**********************
* MACROS
**********************/
#endif /*LV_USE_ROLLER*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_ROLLER_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_roller.h | C | apache-2.0 | 3,449 |
/**
* @file lv_slider.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_slider.h"
#if LV_USE_SLIDER != 0
#include "../misc/lv_assert.h"
#include "../core/lv_group.h"
#include "../core/lv_indev.h"
#include "../draw/lv_draw.h"
#include "../misc/lv_math.h"
#include "../core/lv_disp.h"
#include "lv_img.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_slider_class
#define LV_SLIDER_KNOB_COORD(hor, is_rtl, area) (hor ? (is_rtl ? area.x1 : area.x2) : (is_rtl ? area.y1 : area.y2))
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_slider_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_slider_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void position_knob(lv_obj_t * obj, lv_area_t * knob_area, lv_coord_t knob_size, bool hor);
static void draw_knob(lv_event_t * e);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_slider_class = {
.constructor_cb = lv_slider_constructor,
.event_cb = lv_slider_event,
.editable = LV_OBJ_CLASS_EDITABLE_TRUE,
.group_def = LV_OBJ_CLASS_GROUP_DEF_TRUE,
.instance_size = sizeof(lv_slider_t),
.base_class = &lv_bar_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_slider_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
bool lv_slider_is_dragged(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_slider_t * slider = (lv_slider_t *)obj;
return slider->dragging ? true : false;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_slider_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_slider_t * slider = (lv_slider_t *)obj;
/*Initialize the allocated 'slider'*/
slider->value_to_set = NULL;
slider->dragging = 0;
slider->left_knob_focus = 0;
lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLL_CHAIN);
lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_ext_click_area(obj, LV_DPX(8));
}
static void lv_slider_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
lv_slider_t * slider = (lv_slider_t *)obj;
lv_slider_mode_t type = lv_slider_get_mode(obj);
/*Advanced hit testing: react only on dragging the knob(s)*/
if(code == LV_EVENT_HIT_TEST) {
lv_hit_test_info_t * info = lv_event_get_param(e);
/*Ordinary slider: was the knob area hit?*/
info->res = _lv_area_is_point_on(&slider->right_knob_area, info->point, 0);
/*There's still a change we have a hit, if we have another knob*/
if((info->res == false) && (type == LV_SLIDER_MODE_RANGE)) {
info->res = _lv_area_is_point_on(&slider->left_knob_area, info->point, 0);
}
}
else if(code == LV_EVENT_PRESSED) {
lv_obj_invalidate(obj);
lv_point_t p;
slider->dragging = true;
if(type == LV_SLIDER_MODE_NORMAL || type == LV_SLIDER_MODE_SYMMETRICAL) {
slider->value_to_set = &slider->bar.cur_value;
}
else if(type == LV_SLIDER_MODE_RANGE) {
lv_indev_get_point(lv_indev_get_act(), &p);
bool hor = lv_obj_get_width(obj) >= lv_obj_get_height(obj);
lv_base_dir_t base_dir = lv_obj_get_style_base_dir(obj, LV_PART_MAIN);
lv_coord_t dist_left, dist_right;
if(hor) {
if((base_dir != LV_BASE_DIR_RTL && p.x > slider->right_knob_area.x2) || (base_dir == LV_BASE_DIR_RTL &&
p.x < slider->right_knob_area.x1)) {
slider->value_to_set = &slider->bar.cur_value;
}
else if((base_dir != LV_BASE_DIR_RTL && p.x < slider->left_knob_area.x1) || (base_dir == LV_BASE_DIR_RTL &&
p.x > slider->left_knob_area.x2)) {
slider->value_to_set = &slider->bar.start_value;
}
else {
/*Calculate the distance from each knob*/
dist_left = LV_ABS((slider->left_knob_area.x1 + (slider->left_knob_area.x2 - slider->left_knob_area.x1) / 2) - p.x);
dist_right = LV_ABS((slider->right_knob_area.x1 + (slider->right_knob_area.x2 - slider->right_knob_area.x1) / 2) - p.x);
/*Use whichever one is closer*/
if(dist_right < dist_left) {
slider->value_to_set = &slider->bar.cur_value;
slider->left_knob_focus = 0;
}
else {
slider->value_to_set = &slider->bar.start_value;
slider->left_knob_focus = 1;
}
}
}
else {
if(p.y < slider->right_knob_area.y1) {
slider->value_to_set = &slider->bar.cur_value;
}
else if(p.y > slider->left_knob_area.y2) {
slider->value_to_set = &slider->bar.start_value;
}
else {
/*Calculate the distance from each knob*/
dist_left = LV_ABS((slider->left_knob_area.y1 + (slider->left_knob_area.y2 - slider->left_knob_area.y1) / 2) - p.y);
dist_right = LV_ABS((slider->right_knob_area.y1 + (slider->right_knob_area.y2 - slider->right_knob_area.y1) / 2) - p.y);
/*Use whichever one is closer*/
if(dist_right < dist_left) {
slider->value_to_set = &slider->bar.cur_value;
slider->left_knob_focus = 0;
}
else {
slider->value_to_set = &slider->bar.start_value;
slider->left_knob_focus = 1;
}
}
}
}
}
else if(code == LV_EVENT_PRESSING && slider->value_to_set != NULL) {
lv_indev_t * indev = lv_indev_get_act();
if(lv_indev_get_type(indev) != LV_INDEV_TYPE_POINTER) return;
lv_point_t p;
lv_indev_get_point(indev, &p);
lv_base_dir_t base_dir = lv_obj_get_style_base_dir(obj, LV_PART_MAIN);
lv_coord_t w = lv_obj_get_width(obj);
lv_coord_t h = lv_obj_get_height(obj);
lv_coord_t bg_left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t bg_right = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
lv_coord_t bg_top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_coord_t bg_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
int32_t range = slider->bar.max_value - slider->bar.min_value;
int32_t new_value = 0;
int32_t real_max_value = slider->bar.max_value;
int32_t real_min_value = slider->bar.min_value;
if(w >= h) {
lv_coord_t indic_w = w - bg_left - bg_right;
if(base_dir == LV_BASE_DIR_RTL) {
new_value = (obj->coords.x2 - bg_right) - p.x; /*Make the point relative to the indicator*/
}
else {
new_value = p.x - (obj->coords.x1 + bg_left); /*Make the point relative to the indicator*/
}
new_value = (new_value * range) / indic_w;
new_value += slider->bar.min_value;
}
else {
lv_coord_t indic_h = h - bg_bottom - bg_top;
new_value = p.y - (obj->coords.y2 + bg_bottom); /*Make the point relative to the indicator*/
new_value = (-new_value * range) / indic_h;
new_value += slider->bar.min_value;
}
/*Figure out the min. and max. for this mode*/
if(slider->value_to_set == &slider->bar.start_value) {
real_max_value = slider->bar.cur_value;
}
else {
real_min_value = slider->bar.start_value;
}
if(new_value < real_min_value) new_value = real_min_value;
else if(new_value > real_max_value) new_value = real_max_value;
if(*slider->value_to_set != new_value) {
*slider->value_to_set = new_value;
lv_obj_invalidate(obj);
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL);
if(res != LV_RES_OK) return;
}
}
else if(code == LV_EVENT_RELEASED || code == LV_EVENT_PRESS_LOST) {
slider->dragging = false;
slider->value_to_set = NULL;
lv_obj_invalidate(obj);
/*Leave edit mode if released. (No need to wait for LONG_PRESS)*/
lv_group_t * g = lv_obj_get_group(obj);
bool editing = lv_group_get_editing(g);
lv_indev_type_t indev_type = lv_indev_get_type(lv_indev_get_act());
if(indev_type == LV_INDEV_TYPE_ENCODER) {
if(editing) {
if(lv_slider_get_mode(obj) == LV_SLIDER_MODE_RANGE) {
if(slider->left_knob_focus == 0) slider->left_knob_focus = 1;
else {
slider->left_knob_focus = 0;
lv_group_set_editing(g, false);
}
}
else {
lv_group_set_editing(g, false);
}
}
}
}
else if(code == LV_EVENT_FOCUSED) {
lv_indev_type_t indev_type = lv_indev_get_type(lv_indev_get_act());
if(indev_type == LV_INDEV_TYPE_ENCODER || indev_type == LV_INDEV_TYPE_KEYPAD) {
slider->left_knob_focus = 0;
}
}
else if(code == LV_EVENT_SIZE_CHANGED) {
lv_obj_refresh_ext_draw_size(obj);
}
else if(code == LV_EVENT_REFR_EXT_DRAW_SIZE) {
lv_coord_t knob_left = lv_obj_get_style_pad_left(obj, LV_PART_KNOB);
lv_coord_t knob_right = lv_obj_get_style_pad_right(obj, LV_PART_KNOB);
lv_coord_t knob_top = lv_obj_get_style_pad_top(obj, LV_PART_KNOB);
lv_coord_t knob_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_KNOB);
/*The smaller size is the knob diameter*/
lv_coord_t zoom = lv_obj_get_style_transform_zoom(obj, LV_PART_KNOB);
lv_coord_t trans_w = lv_obj_get_style_transform_width(obj, LV_PART_KNOB);
lv_coord_t trans_h = lv_obj_get_style_transform_height(obj, LV_PART_KNOB);
lv_coord_t knob_size = LV_MIN(lv_obj_get_width(obj) + 2 * trans_w, lv_obj_get_height(obj) + 2 * trans_h) >> 1;
knob_size = (knob_size * zoom) >> 8;
knob_size += LV_MAX(LV_MAX(knob_left, knob_right), LV_MAX(knob_bottom, knob_top));
knob_size += 2; /*For rounding error*/
knob_size += lv_obj_calculate_ext_draw_size(obj, LV_PART_KNOB);
/*Indic. size is handled by bar*/
lv_coord_t * s = lv_event_get_param(e);
*s = LV_MAX(*s, knob_size);
}
else if(code == LV_EVENT_KEY) {
char c = *((char *)lv_event_get_param(e));
if(c == LV_KEY_RIGHT || c == LV_KEY_UP) {
if(!slider->left_knob_focus) lv_slider_set_value(obj, lv_slider_get_value(obj) + 1, LV_ANIM_ON);
else lv_slider_set_left_value(obj, lv_slider_get_left_value(obj) + 1, LV_ANIM_ON);
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL);
if(res != LV_RES_OK) return;
}
else if(c == LV_KEY_LEFT || c == LV_KEY_DOWN) {
if(!slider->left_knob_focus) lv_slider_set_value(obj, lv_slider_get_value(obj) - 1, LV_ANIM_ON);
else lv_slider_set_left_value(obj, lv_slider_get_left_value(obj) - 1, LV_ANIM_ON);
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL);
if(res != LV_RES_OK) return;
}
}
else if(code == LV_EVENT_DRAW_MAIN) {
draw_knob(e);
}
}
static void draw_knob(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_slider_t * slider = (lv_slider_t *)obj;
const lv_area_t * clip_area = lv_event_get_param(e);
lv_base_dir_t base_dir = lv_obj_get_style_base_dir(obj, LV_PART_MAIN);
lv_coord_t objw = lv_obj_get_width(obj);
lv_coord_t objh = lv_obj_get_height(obj);
bool hor = objw >= objh ? true : false;
lv_coord_t knob_size = hor ? objh : objw;
bool sym = false;
if(slider->bar.mode == LV_BAR_MODE_SYMMETRICAL && slider->bar.min_value < 0 && slider->bar.max_value > 0) sym = true;
lv_area_t knob_area;
/*Horizontal*/
if(hor) {
if(!sym) {
knob_area.x1 = LV_SLIDER_KNOB_COORD(hor, base_dir == LV_BASE_DIR_RTL, slider->bar.indic_area);
}
else {
if(slider->bar.cur_value >= 0) {
knob_area.x1 = LV_SLIDER_KNOB_COORD(hor, base_dir == LV_BASE_DIR_RTL, slider->bar.indic_area);
}
else {
knob_area.x1 = LV_SLIDER_KNOB_COORD(hor, base_dir != LV_BASE_DIR_RTL, slider->bar.indic_area);
}
}
}
/*Vertical*/
else {
if(!sym) {
knob_area.y1 = slider->bar.indic_area.y1;
}
else {
if(slider->bar.cur_value >= 0) {
knob_area.y1 = slider->bar.indic_area.y1;
}
else {
knob_area.y1 = slider->bar.indic_area.y2;
}
}
}
lv_draw_rect_dsc_t knob_rect_dsc;
lv_draw_rect_dsc_init(&knob_rect_dsc);
lv_obj_init_draw_rect_dsc(obj, LV_PART_KNOB, &knob_rect_dsc);
position_knob(obj, &knob_area, knob_size, hor);
lv_area_copy(&slider->right_knob_area, &knob_area);
lv_obj_draw_part_dsc_t part_draw_dsc;
lv_obj_draw_dsc_init(&part_draw_dsc, clip_area);
part_draw_dsc.part = LV_PART_KNOB;
part_draw_dsc.class_p = MY_CLASS;
part_draw_dsc.type = LV_SLIDER_DRAW_PART_KNOB;
part_draw_dsc.id = 0;
part_draw_dsc.draw_area = &slider->right_knob_area;
part_draw_dsc.rect_dsc = &knob_rect_dsc;
if(lv_slider_get_mode(obj) != LV_SLIDER_MODE_RANGE) {
lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_draw_dsc);
lv_draw_rect(&slider->right_knob_area, clip_area, &knob_rect_dsc);
lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_draw_dsc);
}
else {
/*Save the draw part_draw_dsc. because it can be modified in the event*/
lv_draw_rect_dsc_t knob_rect_dsc_tmp;
lv_memcpy(&knob_rect_dsc_tmp, &knob_rect_dsc, sizeof(lv_draw_rect_dsc_t));
lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_draw_dsc);
lv_draw_rect(&slider->right_knob_area, clip_area, &knob_rect_dsc);
lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_draw_dsc);
/*Draw a second knob for the start_value side*/
if(hor) {
knob_area.x1 = LV_SLIDER_KNOB_COORD(hor, base_dir != LV_BASE_DIR_RTL, slider->bar.indic_area);
}
else {
knob_area.y1 = slider->bar.indic_area.y2;
}
position_knob(obj, &knob_area, knob_size, hor);
lv_area_copy(&slider->left_knob_area, &knob_area);
lv_memcpy(&knob_rect_dsc, &knob_rect_dsc_tmp, sizeof(lv_draw_rect_dsc_t));
part_draw_dsc.type = LV_SLIDER_DRAW_PART_KNOB_LEFT;
part_draw_dsc.draw_area = &slider->left_knob_area;
part_draw_dsc.rect_dsc = &knob_rect_dsc;
part_draw_dsc.id = 1;
lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_draw_dsc);
lv_draw_rect(&slider->left_knob_area, clip_area, &knob_rect_dsc);
lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_draw_dsc);
}
}
static void position_knob(lv_obj_t * obj, lv_area_t * knob_area, lv_coord_t knob_size, bool hor)
{
if(hor) {
knob_area->x1 -= (knob_size >> 1);
knob_area->x2 = knob_area->x1 + knob_size - 1;
knob_area->y1 = obj->coords.y1;
knob_area->y2 = obj->coords.y2;
}
else {
knob_area->y1 -= (knob_size >> 1);
knob_area->y2 = knob_area->y1 + knob_size - 1;
knob_area->x1 = obj->coords.x1;
knob_area->x2 = obj->coords.x2;
}
lv_coord_t knob_left = lv_obj_get_style_pad_left(obj, LV_PART_KNOB);
lv_coord_t knob_right = lv_obj_get_style_pad_right(obj, LV_PART_KNOB);
lv_coord_t knob_top = lv_obj_get_style_pad_top(obj, LV_PART_KNOB);
lv_coord_t knob_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_KNOB);
lv_coord_t transf_w = lv_obj_get_style_transform_width(obj, LV_PART_KNOB);
lv_coord_t transf_h = lv_obj_get_style_transform_height(obj, LV_PART_KNOB);
/*Apply the paddings on the knob area*/
knob_area->x1 -= knob_left + transf_w;
knob_area->x2 += knob_right + transf_w;
knob_area->y1 -= knob_top + transf_h;
knob_area->y2 += knob_bottom + transf_h;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_slider.c | C | apache-2.0 | 17,277 |
/**
* @file lv_slider.h
*
*/
#ifndef LV_SLIDER_H
#define LV_SLIDER_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_SLIDER != 0
/*Testing of dependencies*/
#if LV_USE_BAR == 0
#error "lv_slider: lv_bar is required. Enable it in lv_conf.h (LV_USE_BAR 1)"
#endif
#include "../core/lv_obj.h"
#include "lv_bar.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
enum {
LV_SLIDER_MODE_NORMAL = LV_BAR_MODE_NORMAL,
LV_SLIDER_MODE_SYMMETRICAL = LV_BAR_MODE_SYMMETRICAL,
LV_SLIDER_MODE_RANGE = LV_BAR_MODE_RANGE
};
typedef uint8_t lv_slider_mode_t;
typedef struct {
lv_bar_t bar; /*Add the ancestor's type first*/
lv_area_t left_knob_area;
lv_area_t right_knob_area;
int32_t * value_to_set; /*Which bar value to set*/
uint8_t dragging : 1; /*1: the slider is being dragged*/
uint8_t left_knob_focus : 1; /*1: with encoder now the right knob can be adjusted*/
} lv_slider_t;
extern const lv_obj_class_t lv_slider_class;
/**
* `type` field in `lv_obj_draw_part_dsc_t` if `class_p = lv_slider_class`
* Used in `LV_EVENT_DRAW_PART_BEGIN` and `LV_EVENT_DRAW_PART_END`
*/
typedef enum {
LV_SLIDER_DRAW_PART_KNOB, /**< The main (right) knob's rectangle*/
LV_SLIDER_DRAW_PART_KNOB_LEFT, /**< The left knob's rectangle*/
} lv_slider_draw_part_type_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a slider objects
* @param parent pointer to an object, it will be the parent of the new slider.
* @return pointer to the created slider
*/
lv_obj_t * lv_slider_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set a new value on the slider
* @param obj pointer to a slider object
* @param value the new value
* @param anim LV_ANIM_ON: set the value with an animation; LV_ANIM_OFF: change the value immediately
*/
static inline void lv_slider_set_value(lv_obj_t * obj, int32_t value, lv_anim_enable_t anim)
{
lv_bar_set_value(obj, value, anim);
}
/**
* Set a new value for the left knob of a slider
* @param obj pointer to a slider object
* @param value new value
* @param anim LV_ANIM_ON: set the value with an animation; LV_ANIM_OFF: change the value immediately
*/
static inline void lv_slider_set_left_value(lv_obj_t * obj, int32_t value, lv_anim_enable_t anim)
{
lv_bar_set_start_value(obj, value, anim);
}
/**
* Set minimum and the maximum values of a bar
* @param obj pointer to the slider object
* @param min minimum value
* @param max maximum value
*/
static inline void lv_slider_set_range(lv_obj_t * obj, int32_t min, int32_t max)
{
lv_bar_set_range(obj, min, max);
}
/**
* Set the mode of slider.
* @param obj pointer to a slider object
* @param mode the mode of the slider. See ::lv_slider_mode_t
*/
static inline void lv_slider_set_mode(lv_obj_t * obj, lv_slider_mode_t mode)
{
lv_bar_set_mode(obj, (lv_bar_mode_t)mode);
}
/*=====================
* Getter functions
*====================*/
/**
* Get the value of the main knob of a slider
* @param obj pointer to a slider object
* @return the value of the main knob of the slider
*/
static inline int32_t lv_slider_get_value(const lv_obj_t * obj)
{
return lv_bar_get_value(obj);
}
/**
* Get the value of the left knob of a slider
* @param obj pointer to a slider object
* @return the value of the left knob of the slider
*/
static inline int32_t lv_slider_get_left_value(const lv_obj_t * obj)
{
return lv_bar_get_start_value(obj);
}
/**
* Get the minimum value of a slider
* @param obj pointer to a slider object
* @return the minimum value of the slider
*/
static inline int32_t lv_slider_get_min_value(const lv_obj_t * obj)
{
return lv_bar_get_min_value(obj);
}
/**
* Get the maximum value of a slider
* @param obj pointer to a slider object
* @return the maximum value of the slider
*/
static inline int32_t lv_slider_get_max_value(const lv_obj_t * obj)
{
return lv_bar_get_max_value(obj);
}
/**
* Give the slider is being dragged or not
* @param obj pointer to a slider object
* @return true: drag in progress false: not dragged
*/
bool lv_slider_is_dragged(const lv_obj_t * obj);
/**
* Get the mode of the slider.
* @param obj pointer to a bar object
* @return see ::lv_slider_mode_t
*/
static inline lv_slider_mode_t lv_slider_get_mode(lv_obj_t * slider)
{
lv_bar_mode_t mode = lv_bar_get_mode(slider);
if(mode == LV_BAR_MODE_SYMMETRICAL) return LV_SLIDER_MODE_SYMMETRICAL;
else if(mode == LV_BAR_MODE_RANGE) return LV_SLIDER_MODE_RANGE;
else return LV_SLIDER_MODE_NORMAL;
}
/**********************
* MACROS
**********************/
#endif /*LV_USE_SLIDER*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_SLIDER_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_slider.h | C | apache-2.0 | 5,113 |
/**
* @file lv_sw.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_switch.h"
#if LV_USE_SWITCH != 0
#include "../misc/lv_assert.h"
#include "../misc/lv_math.h"
#include "../misc/lv_anim.h"
#include "../core/lv_indev.h"
#include "../core/lv_disp.h"
#include "lv_img.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_switch_class
#define LV_SWITCH_IS_ANIMATING(sw) (((sw)->anim_state) != LV_SWITCH_ANIM_STATE_INV)
/** Switch animation start value. (Not the real value of the switch just indicates process animation)*/
#define LV_SWITCH_ANIM_STATE_START 0
/** Switch animation end value. (Not the real value of the switch just indicates process animation)*/
#define LV_SWITCH_ANIM_STATE_END 256
/** Mark no animation is in progress*/
#define LV_SWITCH_ANIM_STATE_INV -1
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_switch_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_switch_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_switch_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void draw_main(lv_event_t * e);
static void lv_switch_anim_exec_cb(void * sw, int32_t value);
static void lv_switch_trigger_anim(lv_obj_t * obj);
static void lv_switch_anim_ready(lv_anim_t * a);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_switch_class = {
.constructor_cb = lv_switch_constructor,
.destructor_cb = lv_switch_destructor,
.event_cb = lv_switch_event,
.width_def = (4 * LV_DPI_DEF) / 10,
.height_def = (4 * LV_DPI_DEF) / 17,
.group_def = LV_OBJ_CLASS_GROUP_DEF_TRUE,
.instance_size = sizeof(lv_switch_t),
.base_class = &lv_obj_class
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_switch_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_switch_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_switch_t * sw = (lv_switch_t *)obj;
sw->anim_state = LV_SWITCH_ANIM_STATE_INV;
lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(obj, LV_OBJ_FLAG_CHECKABLE);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_switch_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_switch_t * sw = (lv_switch_t *)obj;
lv_anim_del(sw, NULL);
}
static void lv_switch_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
if(code == LV_EVENT_REFR_EXT_DRAW_SIZE) {
lv_coord_t knob_left = lv_obj_get_style_pad_left(obj, LV_PART_KNOB);
lv_coord_t knob_right = lv_obj_get_style_pad_right(obj, LV_PART_KNOB);
lv_coord_t knob_top = lv_obj_get_style_pad_top(obj, LV_PART_KNOB);
lv_coord_t knob_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_KNOB);
/*The smaller size is the knob diameter*/
lv_coord_t knob_size = LV_MAX4(knob_left, knob_right, knob_bottom, knob_top);
knob_size += 2; /*For rounding error*/
knob_size += lv_obj_calculate_ext_draw_size(obj, LV_PART_KNOB);
lv_coord_t * s = lv_event_get_param(e);
*s = LV_MAX(*s, knob_size);
*s = LV_MAX(*s, lv_obj_calculate_ext_draw_size(obj, LV_PART_INDICATOR));
}
else if(code == LV_EVENT_VALUE_CHANGED) {
lv_switch_trigger_anim(obj);
lv_obj_invalidate(obj);
}
else if(code == LV_EVENT_DRAW_MAIN) {
draw_main(e);
}
}
static void draw_main(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_switch_t * sw = (lv_switch_t *)obj;
const lv_area_t * clip_area = lv_event_get_param(e);
lv_base_dir_t base_dir = lv_obj_get_style_base_dir(obj, LV_PART_MAIN);
/*Calculate the indicator area*/
lv_coord_t bg_left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t bg_right = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
lv_coord_t bg_top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_coord_t bg_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
/*Draw the indicator*/
/*Respect the background's padding*/
lv_area_t indic_area;
lv_area_copy(&indic_area, &obj->coords);
indic_area.x1 += bg_left;
indic_area.x2 -= bg_right;
indic_area.y1 += bg_top;
indic_area.y2 -= bg_bottom;
lv_draw_rect_dsc_t draw_indic_dsc;
lv_draw_rect_dsc_init(&draw_indic_dsc);
lv_obj_init_draw_rect_dsc(obj, LV_PART_INDICATOR, &draw_indic_dsc);
lv_draw_rect(&indic_area, clip_area, &draw_indic_dsc);
/*Draw the knob*/
lv_coord_t objh = lv_obj_get_height(obj);
lv_coord_t knob_size = objh;
lv_area_t knob_area;
lv_coord_t anim_length = obj->coords.x2 - bg_right - obj->coords.x1 - bg_left - knob_size;
lv_coord_t anim_value_x;
bool chk = lv_obj_get_state(obj) & LV_STATE_CHECKED;
if(LV_SWITCH_IS_ANIMATING(sw)) {
/* Use the animation's coordinate */
anim_value_x = (anim_length * sw->anim_state) / LV_SWITCH_ANIM_STATE_END;
}
else {
/* Use LV_STATE_CHECKED to decide the coordinate */
anim_value_x = chk ? anim_length : 0;
}
if(base_dir == LV_BASE_DIR_RTL) {
anim_value_x = anim_length - anim_value_x;
}
knob_area.x1 = obj->coords.x1 + bg_left + anim_value_x;
knob_area.x2 = knob_area.x1 + knob_size;
knob_area.y1 = obj->coords.y1 + bg_top;
knob_area.y2 = obj->coords.y2 - bg_bottom;
lv_coord_t knob_left = lv_obj_get_style_pad_left(obj, LV_PART_KNOB);
lv_coord_t knob_right = lv_obj_get_style_pad_right(obj, LV_PART_KNOB);
lv_coord_t knob_top = lv_obj_get_style_pad_top(obj, LV_PART_KNOB);
lv_coord_t knob_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_KNOB);
/*Apply the paddings on the knob area*/
knob_area.x1 -= knob_left;
knob_area.x2 += knob_right;
knob_area.y1 -= knob_top;
knob_area.y2 += knob_bottom;
lv_draw_rect_dsc_t knob_rect_dsc;
lv_draw_rect_dsc_init(&knob_rect_dsc);
lv_obj_init_draw_rect_dsc(obj, LV_PART_KNOB, &knob_rect_dsc);
lv_draw_rect(&knob_area, clip_area, &knob_rect_dsc);
}
static void lv_switch_anim_exec_cb(void * var, int32_t value)
{
lv_switch_t * sw = var;
sw->anim_state = value;
lv_obj_invalidate((lv_obj_t *)sw);
}
/**
* Resets the switch's animation state to "no animation in progress".
*/
static void lv_switch_anim_ready(lv_anim_t * a)
{
lv_switch_t * sw = a->var;
sw->anim_state = LV_SWITCH_ANIM_STATE_INV;
lv_obj_invalidate((lv_obj_t *)sw);
}
/**
* Starts an animation for the switch knob. if the anim_time style property is greater than 0
* @param obj the switch to animate
*/
static void lv_switch_trigger_anim(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_switch_t * sw = (lv_switch_t *)obj;
uint32_t anim_dur_full = lv_obj_get_style_anim_time(obj, LV_PART_MAIN);
if(anim_dur_full > 0) {
bool chk = lv_obj_get_state(obj) & LV_STATE_CHECKED;
int32_t anim_start;
int32_t anim_end;
/*No animation in progress -> simply set the values*/
if(sw->anim_state == LV_SWITCH_ANIM_STATE_INV) {
anim_start = chk ? LV_SWITCH_ANIM_STATE_START : LV_SWITCH_ANIM_STATE_END;
anim_end = chk ? LV_SWITCH_ANIM_STATE_END : LV_SWITCH_ANIM_STATE_START;
}
/*Animation in progress. Start from the animation end value*/
else {
anim_start = sw->anim_state;
anim_end = chk ? LV_SWITCH_ANIM_STATE_END : LV_SWITCH_ANIM_STATE_START;
}
/*Calculate actual animation duration*/
uint32_t anim_dur = (anim_dur_full * LV_ABS(anim_start - anim_end)) / LV_SWITCH_ANIM_STATE_END;
/*Stop the previous animation if it exists*/
lv_anim_del(sw, NULL);
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, sw);
lv_anim_set_exec_cb(&a, lv_switch_anim_exec_cb);
lv_anim_set_values(&a, anim_start, anim_end);
lv_anim_set_ready_cb(&a, lv_switch_anim_ready);
lv_anim_set_time(&a, anim_dur);
lv_anim_start(&a);
}
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_switch.c | C | apache-2.0 | 8,860 |
/**
* @file lv_sw.h
*
*/
#ifndef LV_SWITCH_H
#define LV_SWITCH_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_SWITCH != 0
#include "../core/lv_obj.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef struct {
lv_obj_t obj;
int32_t anim_state;
} lv_switch_t;
extern const lv_obj_class_t lv_switch_class;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a switch objects
* @param parent pointer to an object, it will be the parent of the new switch
* @return pointer to the created switch
*/
lv_obj_t * lv_switch_create(lv_obj_t * parent);
/**********************
* MACROS
**********************/
#endif /*LV_USE_SWITCH*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_SWITCH_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_switch.h | C | apache-2.0 | 946 |
/**
* @file lv_table.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_table.h"
#if LV_USE_TABLE != 0
#include "../core/lv_indev.h"
#include "../misc/lv_assert.h"
#include "../misc/lv_txt.h"
#include "../misc/lv_txt_ap.h"
#include "../misc/lv_math.h"
#include "../misc/lv_printf.h"
#include "../draw/lv_draw.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_table_class
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_table_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_table_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_table_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void draw_main(lv_event_t * e);
static lv_coord_t get_row_height(lv_obj_t * obj, uint16_t row_id, const lv_font_t * font,
lv_coord_t letter_space, lv_coord_t line_space,
lv_coord_t cell_left, lv_coord_t cell_right, lv_coord_t cell_top, lv_coord_t cell_bottom);
static void refr_size(lv_obj_t * obj, uint32_t strat_row);
static lv_res_t get_pressed_cell(lv_obj_t * obj, uint16_t * row, uint16_t * col);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_table_class = {
.constructor_cb = lv_table_constructor,
.destructor_cb = lv_table_destructor,
.event_cb = lv_table_event,
.width_def = LV_SIZE_CONTENT,
.height_def = LV_SIZE_CONTENT,
.base_class = &lv_obj_class,
.editable = LV_OBJ_CLASS_EDITABLE_TRUE,
.group_def = LV_OBJ_CLASS_GROUP_DEF_TRUE,
.instance_size = sizeof(lv_table_t),
};
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_table_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*=====================
* Setter functions
*====================*/
void lv_table_set_cell_value(lv_obj_t * obj, uint16_t row, uint16_t col, const char * txt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(txt);
lv_table_t * table = (lv_table_t *)obj;
/*Auto expand*/
if(col >= table->col_cnt) lv_table_set_col_cnt(obj, col + 1);
if(row >= table->row_cnt) lv_table_set_row_cnt(obj, row + 1);
uint32_t cell = row * table->col_cnt + col;
lv_table_cell_ctrl_t ctrl = 0;
/*Save the control byte*/
if(table->cell_data[cell]) ctrl = table->cell_data[cell][0];
#if LV_USE_ARABIC_PERSIAN_CHARS
/*Get the size of the Arabic text and process it*/
size_t len_ap = _lv_txt_ap_calc_bytes_cnt(txt);
table->cell_data[cell] = lv_mem_realloc(table->cell_data[cell], len_ap + 1);
LV_ASSERT_MALLOC(table->cell_data[cell]);
if(table->cell_data[cell] == NULL) return;
_lv_txt_ap_proc(txt, &table->cell_data[cell][1]);
#else
table->cell_data[cell] = lv_mem_realloc(table->cell_data[cell], strlen(txt) + 2); /*+1: trailing '\0; +1: format byte*/
LV_ASSERT_MALLOC(table->cell_data[cell]);
strcpy(table->cell_data[cell] + 1, txt); /*+1 to skip the format byte*/
#endif
table->cell_data[cell][0] = ctrl;
refr_size(obj, row);
lv_obj_invalidate(obj);
}
void lv_table_set_cell_value_fmt(lv_obj_t * obj, uint16_t row, uint16_t col, const char * fmt, ...)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(fmt);
lv_table_t * table = (lv_table_t *)obj;
if(col >= table->col_cnt) {
LV_LOG_WARN("lv_table_set_cell_value: invalid column");
return;
}
/*Auto expand*/
if(row >= table->row_cnt) {
lv_table_set_row_cnt(obj, row + 1);
}
uint32_t cell = row * table->col_cnt + col;
lv_table_cell_ctrl_t ctrl = 0;
/*Save the control byte*/
if(table->cell_data[cell]) ctrl = table->cell_data[cell][0];
va_list ap, ap2;
va_start(ap, fmt);
va_copy(ap2, ap);
/*Allocate space for the new text by using trick from C99 standard section 7.19.6.12*/
uint32_t len = lv_vsnprintf(NULL, 0, fmt, ap);
va_end(ap);
#if LV_USE_ARABIC_PERSIAN_CHARS
/*Put together the text according to the format string*/
char * raw_txt = lv_mem_buf_get(len + 1);
LV_ASSERT_MALLOC(raw_txt);
if(raw_txt == NULL) {
va_end(ap2);
return;
}
lv_vsnprintf(raw_txt, len + 1, fmt, ap2);
/*Get the size of the Arabic text and process it*/
size_t len_ap = _lv_txt_ap_calc_bytes_cnt(raw_txt);
table->cell_data[cell] = lv_mem_realloc(table->cell_data[cell], len_ap + 1);
LV_ASSERT_MALLOC(table->cell_data[cell]);
if(table->cell_data[cell] == NULL) {
va_end(ap2);
return;
}
_lv_txt_ap_proc(raw_txt, &table->cell_data[cell][1]);
lv_mem_buf_release(raw_txt);
#else
table->cell_data[cell] = lv_mem_realloc(table->cell_data[cell], len + 2); /*+1: trailing '\0; +1: format byte*/
LV_ASSERT_MALLOC(table->cell_data[cell]);
if(table->cell_data[cell] == NULL) {
va_end(ap2);
return;
}
table->cell_data[cell][len + 1] = 0; /*Ensure NULL termination*/
lv_vsnprintf(&table->cell_data[cell][1], len + 1, fmt, ap2);
#endif
va_end(ap2);
table->cell_data[cell][0] = ctrl;
/*Refresh the row height*/
lv_coord_t cell_left = lv_obj_get_style_pad_left(obj, LV_PART_ITEMS);
lv_coord_t cell_right = lv_obj_get_style_pad_right(obj, LV_PART_ITEMS);
lv_coord_t cell_top = lv_obj_get_style_pad_top(obj, LV_PART_ITEMS);
lv_coord_t cell_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_ITEMS);
lv_coord_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_ITEMS);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_ITEMS);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_ITEMS);
lv_coord_t h = get_row_height(obj, row, font, letter_space, line_space,
cell_left, cell_right, cell_top, cell_bottom);
lv_coord_t minh = lv_obj_get_style_min_height(obj, LV_PART_ITEMS);
lv_coord_t maxh = lv_obj_get_style_max_height(obj, LV_PART_ITEMS);
table->row_h[row] = LV_CLAMP(minh, h, maxh);
lv_obj_invalidate(obj);
}
void lv_table_set_row_cnt(lv_obj_t * obj, uint16_t row_cnt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
uint16_t old_row_cnt = table->row_cnt;
table->row_cnt = row_cnt;
table->row_h = lv_mem_realloc(table->row_h, table->row_cnt * sizeof(table->row_h[0]));
LV_ASSERT_MALLOC(table->row_h);
if(table->row_h == NULL) return;
/*Free the unused cells*/
if(old_row_cnt > row_cnt) {
uint16_t old_cell_cnt = old_row_cnt * table->col_cnt;
uint32_t new_cell_cnt = table->col_cnt * table->row_cnt;
uint32_t i;
for(i = new_cell_cnt; i < old_cell_cnt; i++) {
lv_mem_free(table->cell_data[i]);
}
}
table->cell_data = lv_mem_realloc(table->cell_data, table->row_cnt * table->col_cnt * sizeof(char *));
LV_ASSERT_MALLOC(table->cell_data);
if(table->cell_data == NULL) return;
/*Initialize the new fields*/
if(old_row_cnt < row_cnt) {
uint32_t old_cell_cnt = old_row_cnt * table->col_cnt;
uint32_t new_cell_cnt = table->col_cnt * table->row_cnt;
lv_memset_00(&table->cell_data[old_cell_cnt], (new_cell_cnt - old_cell_cnt) * sizeof(table->cell_data[0]));
}
refr_size(obj, 0) ;
}
void lv_table_set_col_cnt(lv_obj_t * obj, uint16_t col_cnt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
uint16_t old_col_cnt = table->col_cnt;
table->col_cnt = col_cnt;
table->col_w = lv_mem_realloc(table->col_w, col_cnt * sizeof(table->row_h[0]));
LV_ASSERT_MALLOC(table->col_w);
if(table->col_w == NULL) return;
/*Free the unused cells*/
if(old_col_cnt > col_cnt) {
uint16_t old_cell_cnt = old_col_cnt * table->row_cnt;
uint32_t new_cell_cnt = table->col_cnt * table->row_cnt;
uint32_t i;
for(i = new_cell_cnt; i < old_cell_cnt; i++) {
lv_mem_free(table->cell_data[i]);
}
}
char ** new_cell_data = lv_mem_alloc(table->row_cnt * table->col_cnt * sizeof(char *));
LV_ASSERT_MALLOC(new_cell_data);
if(new_cell_data == NULL) return;
uint32_t new_cell_cnt = table->col_cnt * table->row_cnt;
lv_memset_00(new_cell_data, new_cell_cnt * sizeof(table->cell_data[0]));
/*Initialize the new fields*/
if(old_col_cnt < col_cnt) {
uint32_t col;
for(col = old_col_cnt; col < col_cnt; col++) {
table->col_w[col] = LV_DPI_DEF;
}
}
/*The new column(s) messes up the mapping of `cell_data`*/
uint32_t old_col_start;
uint32_t new_col_start;
uint32_t min_col_cnt = LV_MIN(old_col_cnt, col_cnt);
uint32_t row;
for(row = 0; row < table->row_cnt; row++) {
old_col_start = row * old_col_cnt;
new_col_start = row * col_cnt;
lv_memcpy_small(&new_cell_data[new_col_start], &table->cell_data[old_col_start],
sizeof(new_cell_data[0]) * min_col_cnt);
}
lv_mem_free(table->cell_data);
table->cell_data = new_cell_data;
refr_size(obj, 0) ;
}
void lv_table_set_col_width(lv_obj_t * obj, uint16_t col_id, lv_coord_t w)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
/*Auto expand*/
if(col_id >= table->col_cnt) lv_table_set_col_cnt(obj, col_id + 1);
table->col_w[col_id] = w;
refr_size(obj, 0) ;
}
void lv_table_add_cell_ctrl(lv_obj_t * obj, uint16_t row, uint16_t col, lv_table_cell_ctrl_t ctrl)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
/*Auto expand*/
if(col >= table->col_cnt) lv_table_set_col_cnt(obj, col + 1);
if(row >= table->row_cnt) lv_table_set_row_cnt(obj, row + 1);
uint32_t cell = row * table->col_cnt + col;
if(table->cell_data[cell] == NULL) {
table->cell_data[cell] = lv_mem_alloc(2); /*+1: trailing '\0; +1: format byte*/
LV_ASSERT_MALLOC(table->cell_data[cell]);
if(table->cell_data[cell] == NULL) return;
table->cell_data[cell][0] = 0;
table->cell_data[cell][1] = '\0';
}
table->cell_data[cell][0] |= ctrl;
}
void lv_table_clear_cell_ctrl(lv_obj_t * obj, uint16_t row, uint16_t col, lv_table_cell_ctrl_t ctrl)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
/*Auto expand*/
if(col >= table->col_cnt) lv_table_set_col_cnt(obj, col + 1);
if(row >= table->row_cnt) lv_table_set_row_cnt(obj, row + 1);
uint32_t cell = row * table->col_cnt + col;
if(table->cell_data[cell] == NULL) {
table->cell_data[cell] = lv_mem_alloc(2); /*+1: trailing '\0; +1: format byte*/
LV_ASSERT_MALLOC(table->cell_data[cell]);
if(table->cell_data[cell] == NULL) return;
table->cell_data[cell][0] = 0;
table->cell_data[cell][1] = '\0';
}
table->cell_data[cell][0] &= (~ctrl);
}
/*=====================
* Getter functions
*====================*/
const char * lv_table_get_cell_value(lv_obj_t * obj, uint16_t row, uint16_t col)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
if(row >= table->row_cnt || col >= table->col_cnt) {
LV_LOG_WARN("lv_table_set_cell_value: invalid row or column");
return "";
}
uint32_t cell = row * table->col_cnt + col;
if(table->cell_data[cell] == NULL) return "";
return &table->cell_data[cell][1]; /*Skip the format byte*/
}
uint16_t lv_table_get_row_cnt(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
return table->row_cnt;
}
uint16_t lv_table_get_col_cnt(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
return table->col_cnt;
}
lv_coord_t lv_table_get_col_width(lv_obj_t * obj, uint16_t col)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
if(col >= table->col_cnt) {
LV_LOG_WARN("lv_table_set_col_width: too big 'col_id'. Must be < LV_TABLE_COL_MAX.");
return 0;
}
return table->col_w[col];
}
bool lv_table_has_cell_ctrl(lv_obj_t * obj, uint16_t row, uint16_t col, lv_table_cell_ctrl_t ctrl)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_table_t * table = (lv_table_t *)obj;
if(row >= table->row_cnt || col >= table->col_cnt) {
LV_LOG_WARN("lv_table_get_cell_crop: invalid row or column");
return false;
}
uint32_t cell = row * table->col_cnt + col;
if(table->cell_data[cell] == NULL) return false;
else return (table->cell_data[cell][0] & ctrl) == ctrl ? true : false;
}
void lv_table_get_selected_cell(lv_obj_t * obj, uint16_t * row, uint16_t * col)
{
lv_table_t * table = (lv_table_t *)obj;
*row = table->row_act;
*col = table->col_act;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_table_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_table_t * table = (lv_table_t *)obj;
table->col_cnt = 1;
table->row_cnt = 1;
table->col_w = lv_mem_alloc(table->col_cnt * sizeof(table->col_w[0]));
table->row_h = lv_mem_alloc(table->row_cnt * sizeof(table->row_h[0]));
table->col_w[0] = LV_DPI_DEF;
table->row_h[0] = LV_DPI_DEF;
table->cell_data = lv_mem_realloc(table->cell_data, table->row_cnt * table->col_cnt * sizeof(char *));
table->cell_data[0] = NULL;
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_table_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_table_t * table = (lv_table_t *)obj;
/*Free the cell texts*/
uint16_t i;
for(i = 0; i < table->col_cnt * table->row_cnt; i++) {
if(table->cell_data[i]) {
lv_mem_free(table->cell_data[i]);
table->cell_data[i] = NULL;
}
}
if(table->cell_data) lv_mem_free(table->cell_data);
if(table->row_h) lv_mem_free(table->row_h);
}
static void lv_table_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
lv_table_t * table = (lv_table_t *)obj;
if(code == LV_EVENT_STYLE_CHANGED) {
refr_size(obj, 0);
}
else if(code == LV_EVENT_GET_SELF_SIZE) {
lv_point_t * p = lv_event_get_param(e);
uint32_t i;
lv_coord_t w = 0;
for(i = 0; i < table->col_cnt; i++) w += table->col_w[i];
lv_coord_t h = 0;
for(i = 0; i < table->row_cnt; i++) h += table->row_h[i];
p->x = w - 1;
p->y = h - 1;
}
else if(code == LV_EVENT_PRESSED || code == LV_EVENT_PRESSING) {
uint16_t col;
uint16_t row;
lv_res_t pr_res = get_pressed_cell(obj, &row, &col);
if(pr_res == LV_RES_OK && (table->col_act != col || table->row_act != row)) {
table->col_act = col;
table->row_act = row;
lv_obj_invalidate(obj);
}
}
else if(code == LV_EVENT_RELEASED) {
lv_obj_invalidate(obj);
lv_indev_t * indev = lv_indev_get_act();
lv_obj_t * scroll_obj = lv_indev_get_scroll_obj(indev);
if(table->col_act != LV_TABLE_CELL_NONE && table->row_act != LV_TABLE_CELL_NONE && scroll_obj == NULL) {
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL);
if(res != LV_RES_OK) return;
}
lv_indev_type_t indev_type = lv_indev_get_type(lv_indev_get_act());
if(indev_type == LV_INDEV_TYPE_POINTER || indev_type == LV_INDEV_TYPE_BUTTON) {
table->col_act = LV_TABLE_CELL_NONE;
table->row_act = LV_TABLE_CELL_NONE;
}
}
else if(code == LV_EVENT_FOCUSED) {
lv_obj_invalidate(obj);
}
else if(code == LV_EVENT_KEY) {
int32_t c = *((int32_t *)lv_event_get_param(e));
int32_t col = table->col_act;
int32_t row = table->row_act;
if(col == LV_TABLE_CELL_NONE || row == LV_TABLE_CELL_NONE) {
table->col_act = 0;
table->row_act = 0;
lv_obj_invalidate(obj);
return;
}
if(col >= table->col_cnt) col = 0;
if(row >= table->row_cnt) row = 0;
if(c == LV_KEY_LEFT) col--;
else if(c == LV_KEY_RIGHT) col++;
else if(c == LV_KEY_UP) row--;
else if(c == LV_KEY_DOWN) row++;
else return;
if(col >= table->col_cnt) {
if(row < table->row_cnt - 1) {
col = 0;
row++;
}
else {
col = table->col_cnt - 1;
}
}
else if(col < 0) {
if(row != 0) {
col = table->col_cnt - 1;
row--;
}
else {
col = 0;
}
}
if(row >= table->row_cnt) {
row = table->row_cnt - 1;
}
else if(row < 0) {
row = 0;
}
if(table->col_act != col || table->row_act != row) {
table->col_act = col;
table->row_act = row;
lv_obj_invalidate(obj);
res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL);
if(res != LV_RES_OK) return;
}
}
else if(code == LV_EVENT_DRAW_MAIN) {
draw_main(e);
}
}
static void draw_main(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_table_t * table = (lv_table_t *)obj;
const lv_area_t * clip_area_ori = lv_event_get_param(e);
lv_area_t clip_area;
if(!_lv_area_intersect(&clip_area, &obj->coords, clip_area_ori)) return;
lv_point_t txt_size;
lv_area_t cell_area;
lv_area_t txt_area;
lv_text_flag_t txt_flags;
lv_coord_t border_width = lv_obj_get_style_border_width(obj, LV_PART_MAIN);
lv_coord_t bg_top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_coord_t bg_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_MAIN);
lv_coord_t bg_left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t bg_right = lv_obj_get_style_pad_right(obj, LV_PART_MAIN);
lv_coord_t cell_left = lv_obj_get_style_pad_left(obj, LV_PART_ITEMS);
lv_coord_t cell_right = lv_obj_get_style_pad_right(obj, LV_PART_ITEMS);
lv_coord_t cell_top = lv_obj_get_style_pad_top(obj, LV_PART_ITEMS);
lv_coord_t cell_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_ITEMS);
lv_state_t state_ori = obj->state;
obj->state = LV_STATE_DEFAULT;
obj->skip_trans = 1;
lv_draw_rect_dsc_t rect_dsc_def;
lv_draw_rect_dsc_t rect_dsc_act; /*Passed to the event to modify it*/
lv_draw_rect_dsc_init(&rect_dsc_def);
lv_obj_init_draw_rect_dsc(obj, LV_PART_ITEMS, &rect_dsc_def);
lv_draw_label_dsc_t label_dsc_def;
lv_draw_label_dsc_t label_dsc_act; /*Passed to the event to modify it*/
lv_draw_label_dsc_init(&label_dsc_def);
lv_obj_init_draw_label_dsc(obj, LV_PART_ITEMS, &label_dsc_def);
obj->state = state_ori;
obj->skip_trans = 0;
uint16_t col;
uint16_t row;
uint16_t cell = 0;
cell_area.y2 = obj->coords.y1 + bg_top - 1 - lv_obj_get_scroll_y(obj) + border_width;
lv_coord_t scroll_x = lv_obj_get_scroll_x(obj) ;
bool rtl = lv_obj_get_style_base_dir(obj, LV_PART_MAIN) == LV_BASE_DIR_RTL ? true : false;
/*Handle custom drawer*/
lv_obj_draw_part_dsc_t part_draw_dsc;
lv_obj_draw_dsc_init(&part_draw_dsc, &clip_area);
part_draw_dsc.part = LV_PART_ITEMS;
part_draw_dsc.class_p = MY_CLASS;
part_draw_dsc.type = LV_TABLE_DRAW_PART_CELL;
part_draw_dsc.rect_dsc = &rect_dsc_act;
part_draw_dsc.label_dsc = &label_dsc_act;
for(row = 0; row < table->row_cnt; row++) {
lv_coord_t h_row = table->row_h[row];
cell_area.y1 = cell_area.y2 + 1;
cell_area.y2 = cell_area.y1 + h_row - 1;
if(cell_area.y1 > clip_area.y2) return;
if(rtl) cell_area.x1 = obj->coords.x2 - bg_right - 1 - scroll_x - border_width;
else cell_area.x2 = obj->coords.x1 + bg_left - 1 - scroll_x + border_width;
for(col = 0; col < table->col_cnt; col++) {
lv_table_cell_ctrl_t ctrl = 0;
if(table->cell_data[cell]) ctrl = table->cell_data[cell][0];
if(rtl) {
cell_area.x2 = cell_area.x1 - 1;
cell_area.x1 = cell_area.x2 - table->col_w[col] + 1;
}
else {
cell_area.x1 = cell_area.x2 + 1;
cell_area.x2 = cell_area.x1 + table->col_w[col] - 1;
}
uint16_t col_merge = 0;
for(col_merge = 0; col_merge + col < table->col_cnt - 1; col_merge++) {
if(table->cell_data[cell + col_merge]) {
char * next_cell_data = table->cell_data[cell + col_merge];
if(next_cell_data) ctrl = next_cell_data[0];
if(ctrl & LV_TABLE_CELL_CTRL_MERGE_RIGHT)
if(rtl) cell_area.x1 -= table->col_w[col + col_merge + 1];
else cell_area.x2 += table->col_w[col + col_merge + 1];
else {
break;
}
}
else {
break;
}
}
if(cell_area.y2 < clip_area.y1) {
cell += col_merge + 1;
col += col_merge;
continue;
}
/*Expand the cell area with a half border to avoid drawing 2 borders next to each other*/
lv_area_t cell_area_border;
lv_area_copy(&cell_area_border, &cell_area);
if((rect_dsc_def.border_side & LV_BORDER_SIDE_LEFT) && cell_area_border.x1 > obj->coords.x1 + bg_left) {
cell_area_border.x1 -= rect_dsc_def.border_width / 2;
}
if((rect_dsc_def.border_side & LV_BORDER_SIDE_TOP) && cell_area_border.y1 > obj->coords.y1 + bg_top) {
cell_area_border.y1 -= rect_dsc_def.border_width / 2;
}
if((rect_dsc_def.border_side & LV_BORDER_SIDE_RIGHT) && cell_area_border.x2 < obj->coords.x2 - bg_right - 1) {
cell_area_border.x2 += rect_dsc_def.border_width / 2 + (rect_dsc_def.border_width & 0x1);
}
if((rect_dsc_def.border_side & LV_BORDER_SIDE_BOTTOM) &&
cell_area_border.y2 < obj->coords.y2 - bg_bottom - 1) {
cell_area_border.y2 += rect_dsc_def.border_width / 2 + (rect_dsc_def.border_width & 0x1);
}
lv_state_t cell_state = LV_STATE_DEFAULT;
if(row == table->row_act && col == table->col_act) {
if(!(obj->state & LV_STATE_SCROLLED) && (obj->state & LV_STATE_PRESSED)) cell_state |= LV_STATE_PRESSED;
if(obj->state & LV_STATE_FOCUSED) cell_state |= LV_STATE_FOCUSED;
if(obj->state & LV_STATE_FOCUS_KEY) cell_state |= LV_STATE_FOCUS_KEY;
if(obj->state & LV_STATE_EDITED) cell_state |= LV_STATE_EDITED;
}
/*Set up the draw descriptors*/
if(cell_state == LV_STATE_DEFAULT) {
lv_memcpy(&rect_dsc_act, &rect_dsc_def, sizeof(lv_draw_rect_dsc_t));
lv_memcpy(&label_dsc_act, &label_dsc_def, sizeof(lv_draw_label_dsc_t));
}
/*In other cases get the styles directly without caching them*/
else {
obj->state = cell_state;
obj->skip_trans = 1;
lv_draw_rect_dsc_init(&rect_dsc_act);
lv_draw_label_dsc_init(&label_dsc_act);
lv_obj_init_draw_rect_dsc(obj, LV_PART_ITEMS, &rect_dsc_act);
lv_obj_init_draw_label_dsc(obj, LV_PART_ITEMS, &label_dsc_act);
obj->state = state_ori;
obj->skip_trans = 0;
}
part_draw_dsc.draw_area = &cell_area_border;
part_draw_dsc.id = row * table->col_cnt + col;
lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_draw_dsc);
lv_draw_rect(&cell_area_border, &clip_area, &rect_dsc_act);
if(table->cell_data[cell]) {
txt_area.x1 = cell_area.x1 + cell_left;
txt_area.x2 = cell_area.x2 - cell_right;
txt_area.y1 = cell_area.y1 + cell_top;
txt_area.y2 = cell_area.y2 - cell_bottom;
/*Align the content to the middle if not cropped*/
bool crop = ctrl & LV_TABLE_CELL_CTRL_TEXT_CROP ? true : false;
if(crop) txt_flags = LV_TEXT_FLAG_EXPAND;
else txt_flags = LV_TEXT_FLAG_NONE;
lv_txt_get_size(&txt_size, table->cell_data[cell] + 1, label_dsc_def.font,
label_dsc_act.letter_space, label_dsc_act.line_space,
lv_area_get_width(&txt_area), txt_flags);
/*Align the content to the middle if not cropped*/
if(!crop) {
txt_area.y1 = cell_area.y1 + h_row / 2 - txt_size.y / 2;
txt_area.y2 = cell_area.y1 + h_row / 2 + txt_size.y / 2;
}
lv_area_t label_mask;
bool label_mask_ok;
label_mask_ok = _lv_area_intersect(&label_mask, &clip_area, &cell_area);
if(label_mask_ok) {
lv_draw_label(&txt_area, &label_mask, &label_dsc_act, table->cell_data[cell] + 1, NULL);
}
}
lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_draw_dsc);
cell += col_merge + 1;
col += col_merge;
}
}
}
static void refr_size(lv_obj_t * obj, uint32_t strat_row)
{
lv_table_t * table = (lv_table_t *)obj;
uint32_t i;
lv_coord_t cell_left = lv_obj_get_style_pad_left(obj, LV_PART_ITEMS);
lv_coord_t cell_right = lv_obj_get_style_pad_right(obj, LV_PART_ITEMS);
lv_coord_t cell_top = lv_obj_get_style_pad_top(obj, LV_PART_ITEMS);
lv_coord_t cell_bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_ITEMS);
lv_coord_t letter_space = lv_obj_get_style_text_letter_space(obj, LV_PART_ITEMS);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_ITEMS);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_ITEMS);
lv_coord_t minh = lv_obj_get_style_min_height(obj, LV_PART_ITEMS);
lv_coord_t maxh = lv_obj_get_style_max_height(obj, LV_PART_ITEMS);
for(i = strat_row; i < table->row_cnt; i++) {
table->row_h[i] = get_row_height(obj, i, font, letter_space, line_space,
cell_left, cell_right, cell_top, cell_bottom);
table->row_h[i] = LV_CLAMP(minh, table->row_h[i], maxh);
}
lv_obj_refresh_self_size(obj) ;
}
static lv_coord_t get_row_height(lv_obj_t * obj, uint16_t row_id, const lv_font_t * font,
lv_coord_t letter_space, lv_coord_t line_space,
lv_coord_t cell_left, lv_coord_t cell_right, lv_coord_t cell_top, lv_coord_t cell_bottom)
{
lv_table_t * table = (lv_table_t *)obj;
lv_point_t txt_size;
lv_coord_t txt_w;
uint16_t row_start = row_id * table->col_cnt;
uint16_t cell;
uint16_t col;
lv_coord_t h_max = lv_font_get_line_height(font) + cell_top + cell_bottom;
for(cell = row_start, col = 0; cell < row_start + table->col_cnt; cell++, col++) {
if(table->cell_data[cell] != NULL) {
txt_w = table->col_w[col];
uint16_t col_merge = 0;
for(col_merge = 0; col_merge + col < table->col_cnt - 1; col_merge++) {
if(table->cell_data[cell + col_merge] != NULL) {
lv_table_cell_ctrl_t ctrl = 0;
char * next_cell_data = table->cell_data[cell + col_merge];
if(next_cell_data) ctrl = next_cell_data[0];
if(ctrl & LV_TABLE_CELL_CTRL_MERGE_RIGHT)
txt_w += table->col_w[col + col_merge + 1];
else
break;
}
else {
break;
}
}
lv_table_cell_ctrl_t ctrl = 0;
if(table->cell_data[cell]) ctrl = table->cell_data[cell][0];
/*With text crop assume 1 line*/
if(ctrl & LV_TABLE_CELL_CTRL_TEXT_CROP) {
h_max = LV_MAX(lv_font_get_line_height(font) + cell_top + cell_bottom,
h_max);
}
/*Without text crop calculate the height of the text in the cell*/
else {
txt_w -= cell_left + cell_right;
lv_txt_get_size(&txt_size, table->cell_data[cell] + 1, font,
letter_space, line_space, txt_w, LV_TEXT_FLAG_NONE);
h_max = LV_MAX(txt_size.y + cell_top + cell_bottom, h_max);
cell += col_merge;
col += col_merge;
}
}
}
return h_max;
}
static lv_res_t get_pressed_cell(lv_obj_t * obj, uint16_t * row, uint16_t * col)
{
lv_table_t * table = (lv_table_t *)obj;
lv_indev_type_t type = lv_indev_get_type(lv_indev_get_act());
if(type != LV_INDEV_TYPE_POINTER && type != LV_INDEV_TYPE_BUTTON) {
if(col) *col = LV_TABLE_CELL_NONE;
if(row) *row = LV_TABLE_CELL_NONE;
return LV_RES_INV;
}
lv_point_t p;
lv_indev_get_point(lv_indev_get_act(), &p);
lv_coord_t tmp;
if(col) {
lv_coord_t x = p.x + lv_obj_get_scroll_x(obj);
if(lv_obj_get_style_base_dir(obj, LV_PART_MAIN) == LV_BASE_DIR_RTL) {
x = obj->coords.x2 - lv_obj_get_style_pad_right(obj, LV_PART_MAIN) - x;
}
else {
x -= obj->coords.x1;
x -= lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
}
*col = 0;
tmp = 0;
for(*col = 0; *col < table->col_cnt; (*col)++) {
tmp += table->col_w[*col];
if(x < tmp) break;
}
}
if(row) {
lv_coord_t y = p.y + lv_obj_get_scroll_y(obj);;
y -= obj->coords.y1;
y -= lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
*row = 0;
tmp = 0;
for(*row = 0; *row < table->row_cnt; (*row)++) {
tmp += table->row_h[*row];
if(y < tmp) break;
}
}
return LV_RES_OK;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_table.c | C | apache-2.0 | 30,962 |
/**
* @file lv_table.h
*
*/
#ifndef LV_TABLE_H
#define LV_TABLE_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_TABLE != 0
/*Testing of dependencies*/
#if LV_USE_LABEL == 0
#error "lv_table: lv_label is required. Enable it in lv_conf.h (LV_USE_LABEL 1)"
#endif
#include "../core/lv_obj.h"
#include "lv_label.h"
/*********************
* DEFINES
*********************/
#define LV_TABLE_CELL_NONE 0XFFFF
LV_EXPORT_CONST_INT(LV_TABLE_CELL_NONE);
/**********************
* TYPEDEFS
**********************/
enum {
LV_TABLE_CELL_CTRL_MERGE_RIGHT = 1 << 0,
LV_TABLE_CELL_CTRL_TEXT_CROP = 1 << 1,
LV_TABLE_CELL_CTRL_CUSTOM_1 = 1 << 4,
LV_TABLE_CELL_CTRL_CUSTOM_2 = 1 << 5,
LV_TABLE_CELL_CTRL_CUSTOM_3 = 1 << 6,
LV_TABLE_CELL_CTRL_CUSTOM_4 = 1 << 7,
};
typedef uint8_t lv_table_cell_ctrl_t;
/*Data of table*/
typedef struct {
lv_obj_t obj;
uint16_t col_cnt;
uint16_t row_cnt;
char ** cell_data;
lv_coord_t * row_h;
lv_coord_t * col_w;
uint16_t col_act;
uint16_t row_act;
} lv_table_t;
extern const lv_obj_class_t lv_table_class;
/**
* `type` field in `lv_obj_draw_part_dsc_t` if `class_p = lv_table_class`
* Used in `LV_EVENT_DRAW_PART_BEGIN` and `LV_EVENT_DRAW_PART_END`
*/
typedef enum {
LV_TABLE_DRAW_PART_CELL, /**< A cell*/
} lv_table_draw_part_type_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a table object
* @param parent pointer to an object, it will be the parent of the new table
* @return pointer to the created table
*/
lv_obj_t * lv_table_create(lv_obj_t * parent);
/*=====================
* Setter functions
*====================*/
/**
* Set the value of a cell.
* @param obj pointer to a Table object
* @param row id of the row [0 .. row_cnt -1]
* @param col id of the column [0 .. col_cnt -1]
* @param txt text to display in the cell. It will be copied and saved so this variable is not required after this function call.
* @note New roes/columns are added automatically if required
*/
void lv_table_set_cell_value(lv_obj_t * obj, uint16_t row, uint16_t col, const char * txt);
/**
* Set the value of a cell. Memory will be allocated to store the text by the table.
* @param obj pointer to a Table object
* @param row id of the row [0 .. row_cnt -1]
* @param col id of the column [0 .. col_cnt -1]
* @param fmt `printf`-like format
* @note New roes/columns are added automatically if required
*/
void lv_table_set_cell_value_fmt(lv_obj_t * obj, uint16_t row, uint16_t col, const char * fmt, ...);
/**
* Set the number of rows
* @param obj table pointer to a Table object
* @param row_cnt number of rows
*/
void lv_table_set_row_cnt(lv_obj_t * obj, uint16_t row_cnt);
/**
* Set the number of columns
* @param obj table pointer to a Table object
* @param col_cnt number of columns.
*/
void lv_table_set_col_cnt(lv_obj_t * obj, uint16_t col_cnt);
/**
* Set the width of a column
* @param obj table pointer to a Table object
* @param col_id id of the column [0 .. LV_TABLE_COL_MAX -1]
* @param w width of the column
*/
void lv_table_set_col_width(lv_obj_t * obj, uint16_t col_id, lv_coord_t w);
/**
* Add control bits to the cell.
* @param obj pointer to a Table object
* @param row id of the row [0 .. row_cnt -1]
* @param col id of the column [0 .. col_cnt -1]
* @param ctrl OR-ed values from ::lv_table_cell_ctrl_t
*/
void lv_table_add_cell_ctrl(lv_obj_t * obj, uint16_t row, uint16_t col, lv_table_cell_ctrl_t ctrl);
/**
* Clear control bits of the cell.
* @param obj pointer to a Table object
* @param row id of the row [0 .. row_cnt -1]
* @param col id of the column [0 .. col_cnt -1]
* @param ctrl OR-ed values from ::lv_table_cell_ctrl_t
*/
void lv_table_clear_cell_ctrl(lv_obj_t * obj, uint16_t row, uint16_t col, lv_table_cell_ctrl_t ctrl);
/*=====================
* Getter functions
*====================*/
/**
* Get the value of a cell.
* @param obj pointer to a Table object
* @param row id of the row [0 .. row_cnt -1]
* @param col id of the column [0 .. col_cnt -1]
* @return text in the cell
*/
const char * lv_table_get_cell_value(lv_obj_t * obj, uint16_t row, uint16_t col);
/**
* Get the number of rows.
* @param obj table pointer to a Table object
* @return number of rows.
*/
uint16_t lv_table_get_row_cnt(lv_obj_t * obj);
/**
* Get the number of columns.
* @param obj table pointer to a Table object
* @return number of columns.
*/
uint16_t lv_table_get_col_cnt(lv_obj_t * obj);
/**
* Get the width of a column
* @param obj table pointer to a Table object
* @param col id of the column [0 .. LV_TABLE_COL_MAX -1]
* @return width of the column
*/
lv_coord_t lv_table_get_col_width(lv_obj_t * obj, uint16_t col);
/**
* Get whether a cell has the control bits
* @param obj pointer to a Table object
* @param row id of the row [0 .. row_cnt -1]
* @param col id of the column [0 .. col_cnt -1]
* @param ctrl OR-ed values from ::lv_table_cell_ctrl_t
* @return true: all control bits are set; false: not all control bits are set
*/
bool lv_table_has_cell_ctrl(lv_obj_t * obj, uint16_t row, uint16_t col, lv_table_cell_ctrl_t ctrl);
/**
* Get the selected cell (pressed and or focused)
* @param obj pointer to a table object
* @param row pointer to variable to store the selected row (LV_TABLE_CELL_NONE: if no cell selected)
* @param col pointer to variable to store the selected column (LV_TABLE_CELL_NONE: if no cell selected)
*/
void lv_table_get_selected_cell(lv_obj_t * obj, uint16_t * row, uint16_t * col);
/**********************
* MACROS
**********************/
#endif /*LV_USE_TABLE*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_TABLE_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_table.h | C | apache-2.0 | 6,188 |
/**
* @file lv_ta.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_textarea.h"
#if LV_USE_TEXTAREA != 0
#include <string.h>
#include "../misc/lv_assert.h"
#include "../core/lv_group.h"
#include "../core/lv_refr.h"
#include "../core/lv_indev.h"
#include "../draw/lv_draw.h"
#include "../misc/lv_anim.h"
#include "../misc/lv_txt.h"
#include "../misc/lv_math.h"
/*********************
* DEFINES
*********************/
#define MY_CLASS &lv_textarea_class
/*Test configuration*/
#ifndef LV_TEXTAREA_DEF_CURSOR_BLINK_TIME
#define LV_TEXTAREA_DEF_CURSOR_BLINK_TIME 400 /*ms*/
#endif
#ifndef LV_TEXTAREA_DEF_PWD_SHOW_TIME
#define LV_TEXTAREA_DEF_PWD_SHOW_TIME 1500 /*ms*/
#endif
#define LV_TEXTAREA_PWD_BULLET_UNICODE 0x2022
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void lv_textarea_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_textarea_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj);
static void lv_textarea_event(const lv_obj_class_t * class_p, lv_event_t * e);
static void label_event_cb(lv_event_t * e);
static void cursor_blink_anim_cb(void * obj, int32_t show);
static void pwd_char_hider_anim(void * obj, int32_t x);
static void pwd_char_hider_anim_ready(lv_anim_t * a);
static void pwd_char_hider(lv_obj_t * obj);
static bool char_is_accepted(lv_obj_t * obj, uint32_t c);
static void start_cursor_blink(lv_obj_t * obj);
static void refr_cursor_area(lv_obj_t * obj);
static void update_cursor_position_on_click(lv_event_t * e);
static lv_res_t insert_handler(lv_obj_t * obj, const char * txt);
static void draw_placeholder(lv_event_t * e);
static void draw_cursor(lv_event_t * e);
/**********************
* STATIC VARIABLES
**********************/
const lv_obj_class_t lv_textarea_class = {
.constructor_cb = lv_textarea_constructor,
.destructor_cb = lv_textarea_destructor,
.event_cb = lv_textarea_event,
.group_def = LV_OBJ_CLASS_GROUP_DEF_TRUE,
.width_def = LV_DPI_DEF * 2,
.height_def = LV_DPI_DEF,
.instance_size = sizeof(lv_textarea_t),
.base_class = &lv_obj_class
};
static const char * ta_insert_replace;
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
lv_obj_t * lv_textarea_create(lv_obj_t * parent)
{
LV_LOG_INFO("begin");
lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent);
lv_obj_class_init_obj(obj);
return obj;
}
/*======================
* Add/remove functions
*=====================*/
void lv_textarea_add_char(lv_obj_t * obj, uint32_t c)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
const char * letter_buf;
uint32_t u32_buf[2];
u32_buf[0] = c;
u32_buf[1] = 0;
letter_buf = (char *)&u32_buf;
#if LV_BIG_ENDIAN_SYSTEM
if(c != 0) while(*letter_buf == 0) ++letter_buf;
#endif
lv_res_t res = insert_handler(obj, letter_buf);
if(res != LV_RES_OK) return;
if(ta->one_line && (c == '\n' || c == '\r')) {
LV_LOG_INFO("Text area: line break ignored in one-line mode");
return;
}
uint32_t c_uni = _lv_txt_encoded_next((const char *)&c, NULL);
if(char_is_accepted(obj, c_uni) == false) {
LV_LOG_INFO("Character is not accepted by the text area (too long text or not in the accepted list)");
return;
}
if(ta->pwd_mode != 0) pwd_char_hider(obj); /*Make sure all the current text contains only '*'*/
/*If the textarea is empty, invalidate it to hide the placeholder*/
if(ta->placeholder_txt) {
const char * txt = lv_label_get_text(ta->label);
if(txt[0] == '\0') lv_obj_invalidate(obj);
}
lv_label_ins_text(ta->label, ta->cursor.pos, letter_buf); /*Insert the character*/
lv_textarea_clear_selection(obj); /*Clear selection*/
if(ta->pwd_mode != 0) {
ta->pwd_tmp = lv_mem_realloc(ta->pwd_tmp, strlen(ta->pwd_tmp) + strlen(letter_buf) + 1); /*+2: the new char + \0*/
LV_ASSERT_MALLOC(ta->pwd_tmp);
if(ta->pwd_tmp == NULL) return;
_lv_txt_ins(ta->pwd_tmp, ta->cursor.pos, (const char *)letter_buf);
/*Auto hide characters*/
if(ta->pwd_show_time == 0) {
pwd_char_hider(obj);
}
else {
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, ta);
lv_anim_set_exec_cb(&a, pwd_char_hider_anim);
lv_anim_set_time(&a, ta->pwd_show_time);
lv_anim_set_values(&a, 0, 1);
lv_anim_set_path_cb(&a, lv_anim_path_step);
lv_anim_set_ready_cb(&a, pwd_char_hider_anim_ready);
lv_anim_start(&a);
}
}
/*Move the cursor after the new character*/
lv_textarea_set_cursor_pos(obj, lv_textarea_get_cursor_pos(obj) + 1);
lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL);
}
void lv_textarea_add_text(lv_obj_t * obj, const char * txt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(txt);
lv_textarea_t * ta = (lv_textarea_t *)obj;
if(ta->pwd_mode != 0) pwd_char_hider(obj); /*Make sure all the current text contains only '*'*/
/*Add the character one-by-one if not all characters are accepted or there is character limit.*/
if(lv_textarea_get_accepted_chars(obj) || lv_textarea_get_max_length(obj)) {
uint32_t i = 0;
while(txt[i] != '\0') {
uint32_t c = _lv_txt_encoded_next(txt, &i);
lv_textarea_add_char(obj, _lv_txt_unicode_to_encoded(c));
}
return;
}
lv_res_t res = insert_handler(obj, txt);
if(res != LV_RES_OK) return;
/*If the textarea is empty, invalidate it to hide the placeholder*/
if(ta->placeholder_txt) {
const char * txt_act = lv_label_get_text(ta->label);
if(txt_act[0] == '\0') lv_obj_invalidate(obj);
}
/*Insert the text*/
lv_label_ins_text(ta->label, ta->cursor.pos, txt);
lv_textarea_clear_selection(obj);
if(ta->pwd_mode != 0) {
ta->pwd_tmp = lv_mem_realloc(ta->pwd_tmp, strlen(ta->pwd_tmp) + strlen(txt) + 1);
LV_ASSERT_MALLOC(ta->pwd_tmp);
if(ta->pwd_tmp == NULL) return;
_lv_txt_ins(ta->pwd_tmp, ta->cursor.pos, txt);
/*Auto hide characters*/
if(ta->pwd_show_time == 0) {
pwd_char_hider(obj);
}
else {
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, ta);
lv_anim_set_exec_cb(&a, pwd_char_hider_anim);
lv_anim_set_time(&a, ta->pwd_show_time);
lv_anim_set_values(&a, 0, 1);
lv_anim_set_path_cb(&a, lv_anim_path_step);
lv_anim_set_ready_cb(&a, pwd_char_hider_anim_ready);
lv_anim_start(&a);
}
}
/*Move the cursor after the new text*/
lv_textarea_set_cursor_pos(obj, lv_textarea_get_cursor_pos(obj) + _lv_txt_get_encoded_length(txt));
lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL);
}
void lv_textarea_del_char(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
uint32_t cur_pos = ta->cursor.pos;
if(cur_pos == 0) return;
char del_buf[2] = {LV_KEY_DEL, '\0'};
lv_res_t res = insert_handler(obj, del_buf);
if(res != LV_RES_OK) return;
char * label_txt = lv_label_get_text(ta->label);
/*Delete a character*/
_lv_txt_cut(label_txt, ta->cursor.pos - 1, 1);
/*Refresh the label*/
lv_label_set_text(ta->label, label_txt);
lv_textarea_clear_selection(obj);
/*If the textarea became empty, invalidate it to hide the placeholder*/
if(ta->placeholder_txt) {
const char * txt = lv_label_get_text(ta->label);
if(txt[0] == '\0') lv_obj_invalidate(obj);
}
if(ta->pwd_mode != 0) {
_lv_txt_cut(ta->pwd_tmp, ta->cursor.pos - 1, 1);
ta->pwd_tmp = lv_mem_realloc(ta->pwd_tmp, strlen(ta->pwd_tmp) + 1);
LV_ASSERT_MALLOC(ta->pwd_tmp);
if(ta->pwd_tmp == NULL) return;
}
/*Move the cursor to the place of the deleted character*/
lv_textarea_set_cursor_pos(obj, ta->cursor.pos - 1);
lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL);
}
void lv_textarea_del_char_forward(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
uint32_t cp = lv_textarea_get_cursor_pos(obj);
lv_textarea_set_cursor_pos(obj, cp + 1);
if(cp != lv_textarea_get_cursor_pos(obj)) lv_textarea_del_char(obj);
}
/*=====================
* Setter functions
*====================*/
void lv_textarea_set_text(lv_obj_t * obj, const char * txt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(txt);
lv_textarea_t * ta = (lv_textarea_t *)obj;
/*Clear the existing selection*/
lv_textarea_clear_selection(obj);
/*Add the character one-by-one if not all characters are accepted or there is character limit.*/
if(lv_textarea_get_accepted_chars(obj) || lv_textarea_get_max_length(obj)) {
lv_label_set_text(ta->label, "");
lv_textarea_set_cursor_pos(obj, LV_TEXTAREA_CURSOR_LAST);
if(ta->pwd_mode != 0) {
ta->pwd_tmp[0] = '\0'; /*Clear the password too*/
}
uint32_t i = 0;
while(txt[i] != '\0') {
uint32_t c = _lv_txt_encoded_next(txt, &i);
lv_textarea_add_char(obj, _lv_txt_unicode_to_encoded(c));
}
}
else {
lv_label_set_text(ta->label, txt);
lv_textarea_set_cursor_pos(obj, LV_TEXTAREA_CURSOR_LAST);
}
/*If the textarea is empty, invalidate it to hide the placeholder*/
if(ta->placeholder_txt) {
const char * txt_act = lv_label_get_text(ta->label);
if(txt_act[0] == '\0') lv_obj_invalidate(obj);
}
if(ta->pwd_mode != 0) {
ta->pwd_tmp = lv_mem_realloc(ta->pwd_tmp, strlen(txt) + 1);
LV_ASSERT_MALLOC(ta->pwd_tmp);
if(ta->pwd_tmp == NULL) return;
strcpy(ta->pwd_tmp, txt);
/*Auto hide characters*/
if(ta->pwd_show_time == 0) {
pwd_char_hider(obj);
}
else {
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, ta);
lv_anim_set_exec_cb(&a, pwd_char_hider_anim);
lv_anim_set_time(&a, ta->pwd_show_time);
lv_anim_set_values(&a, 0, 1);
lv_anim_set_path_cb(&a, lv_anim_path_step);
lv_anim_set_ready_cb(&a, pwd_char_hider_anim_ready);
lv_anim_start(&a);
}
}
lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL);
}
void lv_textarea_set_placeholder_text(lv_obj_t * obj, const char * txt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_ASSERT_NULL(txt);
lv_textarea_t * ta = (lv_textarea_t *)obj;
size_t txt_len = strlen(txt);
if(txt_len == 0) {
if(ta->placeholder_txt) {
lv_mem_free(ta->placeholder_txt);
ta->placeholder_txt = NULL;
}
}
else {
/*Allocate memory for the placeholder_txt text*/
if(ta->placeholder_txt == NULL) {
ta->placeholder_txt = lv_mem_alloc(txt_len + 1);
}
else {
ta->placeholder_txt = lv_mem_realloc(ta->placeholder_txt, txt_len + 1);
}
LV_ASSERT_MALLOC(ta->placeholder_txt);
if(ta->placeholder_txt == NULL) {
LV_LOG_ERROR("lv_textarea_set_placeholder_text: couldn't allocate memory for placeholder");
return;
}
strcpy(ta->placeholder_txt, txt);
}
lv_obj_invalidate(obj);
}
void lv_textarea_set_cursor_pos(lv_obj_t * obj, int32_t pos)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
if((uint32_t)ta->cursor.pos == (uint32_t)pos) return;
uint32_t len = _lv_txt_get_encoded_length(lv_label_get_text(ta->label));
if(pos < 0) pos = len + pos;
if(pos > (int32_t)len || pos == LV_TEXTAREA_CURSOR_LAST) pos = len;
ta->cursor.pos = pos;
/*Position the label to make the cursor visible*/
lv_obj_update_layout(obj);
lv_point_t cur_pos;
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_label_get_letter_pos(ta->label, pos, &cur_pos);
/*The text area needs to have it's final size to see if the cursor is out of the area or not*/
/*Check the top*/
lv_coord_t font_h = lv_font_get_line_height(font);
if(cur_pos.y < lv_obj_get_scroll_top(obj)) {
lv_obj_scroll_to_y(obj, cur_pos.y, LV_ANIM_ON);
}
/*Check the bottom*/
lv_coord_t h = lv_obj_get_content_height(obj);
if(cur_pos.y + font_h - lv_obj_get_scroll_top(obj) > h) {
lv_obj_scroll_to_y(obj, cur_pos.y - h + font_h, LV_ANIM_ON);
}
/*Check the left*/
if(cur_pos.x < lv_obj_get_scroll_left(obj)) {
lv_obj_scroll_to_x(obj, cur_pos.x, LV_ANIM_ON);
}
/*Check the right*/
lv_coord_t w = lv_obj_get_content_width(obj);
if(cur_pos.x + font_h - lv_obj_get_scroll_left(obj) > w) {
lv_obj_scroll_to_x(obj, cur_pos.x - w + font_h, LV_ANIM_ON);
}
ta->cursor.valid_x = cur_pos.x;
start_cursor_blink(obj);
refr_cursor_area(obj);
}
void lv_textarea_set_cursor_click_pos(lv_obj_t * obj, bool en)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
ta->cursor.click_pos = en ? 1 : 0;
}
void lv_textarea_set_password_mode(lv_obj_t * obj, bool en)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
if(ta->pwd_mode == en) return;
ta->pwd_mode = en == false ? 0 : 1;
/*Pwd mode is now enabled*/
if(en != false) {
char * txt = lv_label_get_text(ta->label);
size_t len = strlen(txt);
ta->pwd_tmp = lv_mem_alloc(len + 1);
LV_ASSERT_MALLOC(ta->pwd_tmp);
if(ta->pwd_tmp == NULL) return;
strcpy(ta->pwd_tmp, txt);
pwd_char_hider(obj);
lv_textarea_clear_selection(obj);
}
/*Pwd mode is now disabled*/
else {
lv_textarea_clear_selection(obj);
lv_label_set_text(ta->label, ta->pwd_tmp);
lv_mem_free(ta->pwd_tmp);
ta->pwd_tmp = NULL;
}
refr_cursor_area(obj);
}
void lv_textarea_set_one_line(lv_obj_t * obj, bool en)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
if(ta->one_line == en) return;
if(en) {
ta->one_line = 1;
lv_obj_set_width(ta->label, LV_SIZE_CONTENT);
lv_obj_set_style_min_width(ta->label, lv_pct(100), 0);
lv_obj_set_height(obj, LV_SIZE_CONTENT);
lv_obj_scroll_to(obj, 0, 0, LV_ANIM_OFF);
}
else {
ta->one_line = 0;
lv_obj_set_width(ta->label, lv_pct(100));
lv_obj_set_style_min_width(ta->label, 0, 0);
lv_obj_remove_local_style_prop(obj, LV_STYLE_HEIGHT, LV_PART_MAIN);
lv_obj_scroll_to(obj, 0, 0, LV_ANIM_OFF);
}
}
void lv_textarea_set_accepted_chars(lv_obj_t * obj, const char * list)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
ta->accepted_chars = list;
}
void lv_textarea_set_max_length(lv_obj_t * obj, uint32_t num)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
ta->max_length = num;
}
void lv_textarea_set_insert_replace(lv_obj_t * obj, const char * txt)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
LV_UNUSED(obj);
ta_insert_replace = txt;
}
void lv_textarea_set_text_selection(lv_obj_t * obj, bool en)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
#if LV_LABEL_TEXT_SELECTION
lv_textarea_t * ta = (lv_textarea_t *)obj;
ta->text_sel_en = en;
if(!en) lv_textarea_clear_selection(obj);
#else
LV_UNUSED(obj); /*Unused*/
LV_UNUSED(en); /*Unused*/
#endif
}
void lv_textarea_set_password_show_time(lv_obj_t * obj, uint16_t time)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
ta->pwd_show_time = time;
}
void lv_textarea_set_align(lv_obj_t * obj, lv_text_align_t align)
{
LV_LOG_WARN("Deprecated: use the normal text_align style property instead");
lv_obj_set_style_text_align(obj, align, 0);
switch(align) {
default:
case LV_TEXT_ALIGN_LEFT:
lv_obj_align(lv_textarea_get_label(obj), LV_ALIGN_TOP_LEFT, 0, 0);
break;
case LV_TEXT_ALIGN_RIGHT:
lv_obj_align(lv_textarea_get_label(obj), LV_ALIGN_TOP_RIGHT, 0, 0);
break;
case LV_TEXT_ALIGN_CENTER:
lv_obj_align(lv_textarea_get_label(obj), LV_ALIGN_TOP_MID, 0, 0);
break;
}
}
/*=====================
* Getter functions
*====================*/
const char * lv_textarea_get_text(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
const char * txt;
if(ta->pwd_mode == 0) {
txt = lv_label_get_text(ta->label);
}
else {
txt = ta->pwd_tmp;
}
return txt;
}
const char * lv_textarea_get_placeholder_text(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
if(ta->placeholder_txt) return ta->placeholder_txt;
else return "";
}
lv_obj_t * lv_textarea_get_label(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
return ta->label;
}
uint32_t lv_textarea_get_cursor_pos(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
return ta->cursor.pos;
}
bool lv_textarea_get_cursor_click_pos(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
return ta->cursor.click_pos ? true : false;
}
bool lv_textarea_get_password_mode(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
return ta->pwd_mode == 0 ? false : true;
}
bool lv_textarea_get_one_line(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
return ta->one_line == 0 ? false : true;
}
const char * lv_textarea_get_accepted_chars(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
return ta->accepted_chars;
}
uint32_t lv_textarea_get_max_length(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
return ta->max_length;
}
bool lv_textarea_text_is_selected(const lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
#if LV_LABEL_TEXT_SELECTION
lv_textarea_t * ta = (lv_textarea_t *)obj;
if((lv_label_get_text_selection_start(ta->label) != LV_DRAW_LABEL_NO_TXT_SEL ||
lv_label_get_text_selection_end(ta->label) != LV_DRAW_LABEL_NO_TXT_SEL)) {
return true;
}
else {
return false;
}
#else
LV_UNUSED(obj); /*Unused*/
return false;
#endif
}
bool lv_textarea_get_text_selection(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
#if LV_LABEL_TEXT_SELECTION
lv_textarea_t * ta = (lv_textarea_t *)obj;
return ta->text_sel_en;
#else
LV_UNUSED(obj); /*Unused*/
return false;
#endif
}
uint16_t lv_textarea_get_password_show_time(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
return ta->pwd_show_time;
}
/*=====================
* Other functions
*====================*/
void lv_textarea_clear_selection(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
#if LV_LABEL_TEXT_SELECTION
lv_textarea_t * ta = (lv_textarea_t *)obj;
if(lv_label_get_text_selection_start(ta->label) != LV_DRAW_LABEL_NO_TXT_SEL ||
lv_label_get_text_selection_end(ta->label) != LV_DRAW_LABEL_NO_TXT_SEL) {
lv_label_set_text_sel_start(ta->label, LV_DRAW_LABEL_NO_TXT_SEL);
lv_label_set_text_sel_end(ta->label, LV_DRAW_LABEL_NO_TXT_SEL);
}
#else
LV_UNUSED(obj); /*Unused*/
#endif
}
void lv_textarea_cursor_right(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
uint32_t cp = lv_textarea_get_cursor_pos(obj);
cp++;
lv_textarea_set_cursor_pos(obj, cp);
}
void lv_textarea_cursor_left(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
uint32_t cp = lv_textarea_get_cursor_pos(obj);
if(cp > 0) {
cp--;
lv_textarea_set_cursor_pos(obj, cp);
}
}
void lv_textarea_cursor_down(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
lv_point_t pos;
/*Get the position of the current letter*/
lv_label_get_letter_pos(ta->label, lv_textarea_get_cursor_pos(obj), &pos);
/*Increment the y with one line and keep the valid x*/
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t font_h = lv_font_get_line_height(font);
pos.y += font_h + line_space + 1;
pos.x = ta->cursor.valid_x;
/*Do not go below the last line*/
if(pos.y < lv_obj_get_height(ta->label)) {
/*Get the letter index on the new cursor position and set it*/
uint32_t new_cur_pos = lv_label_get_letter_on(ta->label, &pos);
lv_coord_t cur_valid_x_tmp = ta->cursor.valid_x; /*Cursor position set overwrites the valid position*/
lv_textarea_set_cursor_pos(obj, new_cur_pos);
ta->cursor.valid_x = cur_valid_x_tmp;
}
}
void lv_textarea_cursor_up(lv_obj_t * obj)
{
LV_ASSERT_OBJ(obj, MY_CLASS);
lv_textarea_t * ta = (lv_textarea_t *)obj;
lv_point_t pos;
/*Get the position of the current letter*/
lv_label_get_letter_pos(ta->label, lv_textarea_get_cursor_pos(obj), &pos);
/*Decrement the y with one line and keep the valid x*/
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t font_h = lv_font_get_line_height(font);
pos.y -= font_h + line_space - 1;
pos.x = ta->cursor.valid_x;
/*Get the letter index on the new cursor position and set it*/
uint32_t new_cur_pos = lv_label_get_letter_on(ta->label, &pos);
lv_coord_t cur_valid_x_tmp = ta->cursor.valid_x; /*Cursor position set overwrites the valid position*/
lv_textarea_set_cursor_pos(obj, new_cur_pos);
ta->cursor.valid_x = cur_valid_x_tmp;
}
/**********************
* STATIC FUNCTIONS
**********************/
static void lv_textarea_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
LV_TRACE_OBJ_CREATE("begin");
lv_textarea_t * ta = (lv_textarea_t *)obj;
ta->pwd_mode = 0;
ta->pwd_tmp = NULL;
ta->pwd_show_time = LV_TEXTAREA_DEF_PWD_SHOW_TIME;
ta->accepted_chars = NULL;
ta->max_length = 0;
ta->cursor.show = 1;
/*It will be set to zero later (with zero value lv_textarea_set_cursor_pos(obj, 0); woldn't do anything as there is no difference)*/
ta->cursor.pos = 1;
ta->cursor.click_pos = 1;
ta->cursor.valid_x = 0;
ta->one_line = 0;
#if LV_LABEL_TEXT_SELECTION
ta->text_sel_en = 0;
#endif
ta->label = NULL;
ta->placeholder_txt = NULL;
ta->label = lv_label_create(obj);
lv_obj_set_width(ta->label, lv_pct(100));
lv_label_set_text(ta->label, "");
lv_obj_add_event_cb(ta->label, label_event_cb, LV_EVENT_ALL, NULL);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
lv_textarea_set_cursor_pos(obj, 0);
start_cursor_blink(obj);
LV_TRACE_OBJ_CREATE("finished");
}
static void lv_textarea_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj)
{
LV_UNUSED(class_p);
lv_textarea_t * ta = (lv_textarea_t *)obj;
if(ta->pwd_tmp != NULL) {
lv_mem_free(ta->pwd_tmp);
ta->pwd_tmp = NULL;
}
if(ta->placeholder_txt != NULL) {
lv_mem_free(ta->placeholder_txt);
ta->placeholder_txt = NULL;
}
}
static void lv_textarea_event(const lv_obj_class_t * class_p, lv_event_t * e)
{
LV_UNUSED(class_p);
lv_res_t res;
/*Call the ancestor's event handler*/
res = lv_obj_event_base(MY_CLASS, e);
if(res != LV_RES_OK) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
if(code == LV_EVENT_FOCUSED) {
start_cursor_blink(obj);
}
else if(code == LV_EVENT_KEY) {
uint32_t c = *((uint32_t *)lv_event_get_param(e)); /*uint32_t because can be UTF-8*/
if(c == LV_KEY_RIGHT)
lv_textarea_cursor_right(obj);
else if(c == LV_KEY_LEFT)
lv_textarea_cursor_left(obj);
else if(c == LV_KEY_UP)
lv_textarea_cursor_up(obj);
else if(c == LV_KEY_DOWN)
lv_textarea_cursor_down(obj);
else if(c == LV_KEY_BACKSPACE)
lv_textarea_del_char(obj);
else if(c == LV_KEY_DEL)
lv_textarea_del_char_forward(obj);
else if(c == LV_KEY_HOME)
lv_textarea_set_cursor_pos(obj, 0);
else if(c == LV_KEY_END)
lv_textarea_set_cursor_pos(obj, LV_TEXTAREA_CURSOR_LAST);
else if(c == LV_KEY_ENTER && lv_textarea_get_one_line(obj))
lv_event_send(obj, LV_EVENT_READY, NULL);
else {
lv_textarea_add_char(obj, c);
}
}
else if(code == LV_EVENT_PRESSED || code == LV_EVENT_PRESSING || code == LV_EVENT_PRESS_LOST ||
code == LV_EVENT_RELEASED) {
update_cursor_position_on_click(e);
}
else if(code == LV_EVENT_DRAW_MAIN) {
draw_placeholder(e);
}
else if(code == LV_EVENT_DRAW_POST) {
draw_cursor(e);
}
}
static void label_event_cb(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * label = lv_event_get_target(e);
lv_obj_t * ta = lv_obj_get_parent(label);
if(code == LV_EVENT_STYLE_CHANGED || code == LV_EVENT_SIZE_CHANGED) {
lv_label_set_text(label, NULL);
refr_cursor_area(ta);
start_cursor_blink(ta);
}
}
/**
* Called to blink the cursor
* @param ta pointer to a text area
* @param hide 1: hide the cursor, 0: show it
*/
static void cursor_blink_anim_cb(void * obj, int32_t show)
{
lv_textarea_t * ta = (lv_textarea_t *)obj;
if(show != ta->cursor.show) {
ta->cursor.show = show == 0 ? 0 : 1;
lv_area_t area_tmp;
lv_area_copy(&area_tmp, &ta->cursor.area);
area_tmp.x1 += ta->label->coords.x1;
area_tmp.y1 += ta->label->coords.y1;
area_tmp.x2 += ta->label->coords.x1;
area_tmp.y2 += ta->label->coords.y1;
lv_obj_invalidate_area(obj, &area_tmp);
}
}
/**
* Dummy function to animate char hiding in pwd mode.
* Does nothing, but a function is required in car hiding anim.
* (pwd_char_hider callback do the real job)
* @param ta unused
* @param x unused
*/
static void pwd_char_hider_anim(void * obj, int32_t x)
{
LV_UNUSED(obj);
LV_UNUSED(x);
}
/**
* Call when an animation is ready to convert all characters to '*'
* @param a pointer to the animation
*/
static void pwd_char_hider_anim_ready(lv_anim_t * a)
{
lv_obj_t * obj = a->var;
pwd_char_hider(obj);
}
/**
* Hide all characters (convert them to '*')
* @param ta pointer to text area object
*/
static void pwd_char_hider(lv_obj_t * obj)
{
lv_textarea_t * ta = (lv_textarea_t *)obj;
if(ta->pwd_mode != 0) {
char * txt = lv_label_get_text(ta->label);
int32_t enc_len = _lv_txt_get_encoded_length(txt);
if(enc_len == 0) return;
/*If the textarea's font has "bullet" character use it else fallback to "*"*/
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_font_glyph_dsc_t g;
bool has_bullet;
has_bullet = lv_font_get_glyph_dsc(font, &g, LV_TEXTAREA_PWD_BULLET_UNICODE, 0);
const char * bullet;
if(has_bullet) bullet = LV_SYMBOL_BULLET;
else bullet = "*";
size_t bullet_len = strlen(bullet);
char * txt_tmp = lv_mem_buf_get(enc_len * bullet_len + 1);
int32_t i;
for(i = 0; i < enc_len; i++) {
lv_memcpy(&txt_tmp[i * bullet_len], bullet, bullet_len);
}
txt_tmp[i * bullet_len] = '\0';
lv_label_set_text(ta->label, txt_tmp);
lv_mem_buf_release(txt_tmp);
refr_cursor_area(obj);
}
}
/**
* Test an unicode character if it is accepted or not. Checks max length and accepted char list.
* @param ta pointer to a test area object
* @param c an unicode character
* @return true: accepted; false: rejected
*/
static bool char_is_accepted(lv_obj_t * obj, uint32_t c)
{
lv_textarea_t * ta = (lv_textarea_t *)obj;
/*If no restriction accept it*/
if((ta->accepted_chars == NULL || ta->accepted_chars[0] == '\0') && ta->max_length == 0) return true;
/*Too many characters?*/
if(ta->max_length > 0 && _lv_txt_get_encoded_length(lv_textarea_get_text(obj)) >= ta->max_length) {
return false;
}
/*Accepted character?*/
if(ta->accepted_chars) {
uint32_t i = 0;
while(ta->accepted_chars[i] != '\0') {
uint32_t a = _lv_txt_encoded_next(ta->accepted_chars, &i);
if(a == c) return true; /*Accepted*/
}
return false; /*The character wasn't in the list*/
}
else {
return true; /*If the accepted char list in not specified the accept the character*/
}
}
static void start_cursor_blink(lv_obj_t * obj)
{
lv_textarea_t * ta = (lv_textarea_t *)obj;
uint32_t blink_time = lv_obj_get_style_anim_time(obj, LV_PART_CURSOR);
if(blink_time == 0) {
lv_anim_del(obj, cursor_blink_anim_cb);
ta->cursor.show = 1;
}
else {
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, ta);
lv_anim_set_exec_cb(&a, cursor_blink_anim_cb);
lv_anim_set_time(&a, blink_time);
lv_anim_set_playback_time(&a, blink_time);
lv_anim_set_values(&a, 1, 0);
lv_anim_set_path_cb(&a, lv_anim_path_step);
lv_anim_set_repeat_count(&a, LV_ANIM_REPEAT_INFINITE);
lv_anim_start(&a);
}
}
static void refr_cursor_area(lv_obj_t * obj)
{
lv_textarea_t * ta = (lv_textarea_t *)obj;
const lv_font_t * font = lv_obj_get_style_text_font(obj, LV_PART_MAIN);
lv_coord_t line_space = lv_obj_get_style_text_line_space(obj, LV_PART_MAIN);
uint32_t cur_pos = lv_textarea_get_cursor_pos(obj);
const char * txt = lv_label_get_text(ta->label);
uint32_t byte_pos;
byte_pos = _lv_txt_encoded_get_byte_id(txt, cur_pos);
uint32_t letter = _lv_txt_encoded_next(&txt[byte_pos], NULL);
lv_coord_t letter_h = lv_font_get_line_height(font);
/*Set letter_w (set not 0 on non printable but valid chars)*/
lv_coord_t letter_w;
if(letter == '\0' || letter == '\n' || letter == '\r') {
letter_w = lv_font_get_glyph_width(font, ' ', '\0');
}
else {
/*`letter_next` parameter is '\0' to ignore kerning*/
letter_w = lv_font_get_glyph_width(font, letter, '\0');
}
lv_point_t letter_pos;
lv_label_get_letter_pos(ta->label, cur_pos, &letter_pos);
lv_text_align_t align = lv_obj_calculate_style_text_align(ta->label, LV_PART_MAIN, lv_label_get_text(ta->label));
/*If the cursor is out of the text (most right) draw it to the next line*/
if(letter_pos.x + ta->label->coords.x1 + letter_w > ta->label->coords.x2 && ta->one_line == 0 &&
align != LV_TEXT_ALIGN_RIGHT) {
letter_pos.x = 0;
letter_pos.y += letter_h + line_space;
if(letter != '\0') {
byte_pos += _lv_txt_encoded_size(&txt[byte_pos]);
letter = _lv_txt_encoded_next(&txt[byte_pos], NULL);
}
if(letter == '\0' || letter == '\n' || letter == '\r') {
letter_w = lv_font_get_glyph_width(font, ' ', '\0');
}
else {
letter_w = lv_font_get_glyph_width(font, letter, '\0');
}
}
/*Save the byte position. It is required to draw `LV_CURSOR_BLOCK`*/
ta->cursor.txt_byte_pos = byte_pos;
/*Calculate the cursor according to its type*/
lv_coord_t border_width = lv_obj_get_style_border_width(obj, LV_PART_CURSOR);
lv_coord_t top = lv_obj_get_style_pad_top(obj, LV_PART_CURSOR) + border_width;
lv_coord_t bottom = lv_obj_get_style_pad_bottom(obj, LV_PART_CURSOR) + border_width;
lv_coord_t left = lv_obj_get_style_pad_left(obj, LV_PART_CURSOR) + border_width;
lv_coord_t right = lv_obj_get_style_pad_right(obj, LV_PART_CURSOR) + border_width;
lv_area_t cur_area;
cur_area.x1 = letter_pos.x - left;
cur_area.y1 = letter_pos.y - top;
cur_area.x2 = letter_pos.x + right + letter_w - 1;
cur_area.y2 = letter_pos.y + bottom + letter_h - 1;
/*Save the new area*/
lv_area_t area_tmp;
lv_area_copy(&area_tmp, &ta->cursor.area);
area_tmp.x1 += ta->label->coords.x1;
area_tmp.y1 += ta->label->coords.y1;
area_tmp.x2 += ta->label->coords.x1;
area_tmp.y2 += ta->label->coords.y1;
lv_obj_invalidate_area(obj, &area_tmp);
lv_area_copy(&ta->cursor.area, &cur_area);
lv_area_copy(&area_tmp, &ta->cursor.area);
area_tmp.x1 += ta->label->coords.x1;
area_tmp.y1 += ta->label->coords.y1;
area_tmp.x2 += ta->label->coords.x1;
area_tmp.y2 += ta->label->coords.y1;
lv_obj_invalidate_area(obj, &area_tmp);
}
static void update_cursor_position_on_click(lv_event_t * e)
{
lv_indev_t * click_source = lv_indev_get_act();
if(click_source == NULL) return;
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
lv_textarea_t * ta = (lv_textarea_t *)obj;
if(ta->cursor.click_pos == 0) return;
if(lv_indev_get_type(click_source) == LV_INDEV_TYPE_KEYPAD ||
lv_indev_get_type(click_source) == LV_INDEV_TYPE_ENCODER) {
return;
}
lv_area_t label_coords;
lv_obj_get_coords(ta->label, &label_coords);
lv_point_t point_act, vect_act;
lv_indev_get_point(click_source, &point_act);
lv_indev_get_vect(click_source, &vect_act);
if(point_act.x < 0 || point_act.y < 0) return; /*Ignore event from keypad*/
lv_point_t rel_pos;
rel_pos.x = point_act.x - label_coords.x1;
rel_pos.y = point_act.y - label_coords.y1;
lv_coord_t label_width = lv_obj_get_width(ta->label);
uint16_t char_id_at_click;
#if LV_LABEL_TEXT_SELECTION
lv_label_t * label_data = (lv_label_t *)ta->label;
bool click_outside_label;
/*Check if the click happened on the left side of the area outside the label*/
if(rel_pos.x < 0) {
char_id_at_click = 0;
click_outside_label = true;
}
/*Check if the click happened on the right side of the area outside the label*/
else if(rel_pos.x >= label_width) {
char_id_at_click = LV_TEXTAREA_CURSOR_LAST;
click_outside_label = true;
}
else {
char_id_at_click = lv_label_get_letter_on(ta->label, &rel_pos);
click_outside_label = !lv_label_is_char_under_pos(ta->label, &rel_pos);
}
if(ta->text_sel_en) {
if(!ta->text_sel_in_prog && !click_outside_label && code == LV_EVENT_PRESSED) {
/*Input device just went down. Store the selection start position*/
ta->sel_start = char_id_at_click;
ta->sel_end = LV_LABEL_TEXT_SELECTION_OFF;
ta->text_sel_in_prog = 1;
lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLL_CHAIN);
}
else if(ta->text_sel_in_prog && code == LV_EVENT_PRESSING) {
/*Input device may be moving. Store the end position*/
ta->sel_end = char_id_at_click;
}
else if(ta->text_sel_in_prog && (code == LV_EVENT_PRESS_LOST || code == LV_EVENT_RELEASED)) {
/*Input device is released. Check if anything was selected.*/
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_CHAIN);
}
}
if(ta->text_sel_in_prog || code == LV_EVENT_PRESSED) lv_textarea_set_cursor_pos(obj, char_id_at_click);
if(ta->text_sel_in_prog) {
/*If the selected area has changed then update the real values and*/
/*Invalidate the text area.*/
if(ta->sel_start > ta->sel_end) {
if(label_data->sel_start != ta->sel_end || label_data->sel_end != ta->sel_start) {
label_data->sel_start = ta->sel_end;
label_data->sel_end = ta->sel_start;
lv_obj_invalidate(obj);
}
}
else if(ta->sel_start < ta->sel_end) {
if(label_data->sel_start != ta->sel_start || label_data->sel_end != ta->sel_end) {
label_data->sel_start = ta->sel_start;
label_data->sel_end = ta->sel_end;
lv_obj_invalidate(obj);
}
}
else {
if(label_data->sel_start != LV_DRAW_LABEL_NO_TXT_SEL || label_data->sel_end != LV_DRAW_LABEL_NO_TXT_SEL) {
label_data->sel_start = LV_DRAW_LABEL_NO_TXT_SEL;
label_data->sel_end = LV_DRAW_LABEL_NO_TXT_SEL;
lv_obj_invalidate(obj);
}
}
/*Finish selection if necessary*/
if(code == LV_EVENT_PRESS_LOST || code == LV_EVENT_RELEASED) {
ta->text_sel_in_prog = 0;
}
}
#else
/*Check if the click happened on the left side of the area outside the label*/
if(rel_pos.x < 0) {
char_id_at_click = 0;
}
/*Check if the click happened on the right side of the area outside the label*/
else if(rel_pos.x >= label_width) {
char_id_at_click = LV_TEXTAREA_CURSOR_LAST;
}
else {
char_id_at_click = lv_label_get_letter_on(ta->label, &rel_pos);
}
if(code == LV_EVENT_PRESSED) lv_textarea_set_cursor_pos(obj, char_id_at_click);
#endif
}
static lv_res_t insert_handler(lv_obj_t * obj, const char * txt)
{
ta_insert_replace = NULL;
lv_event_send(obj, LV_EVENT_INSERT, (char *)txt);
if(ta_insert_replace) {
if(ta_insert_replace[0] == '\0') return LV_RES_INV; /*Drop this text*/
/*Add the replaced text directly it's different from the original*/
if(strcmp(ta_insert_replace, txt)) {
lv_textarea_add_text(obj, ta_insert_replace);
return LV_RES_INV;
}
}
return LV_RES_OK;
}
static void draw_placeholder(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_textarea_t * ta = (lv_textarea_t *)obj;
const lv_area_t * clip_area = lv_event_get_param(e);
const char * txt = lv_label_get_text(ta->label);
/*Draw the place holder*/
if(txt[0] == '\0' && ta->placeholder_txt && ta->placeholder_txt[0] != 0) {
lv_draw_label_dsc_t ph_dsc;
lv_draw_label_dsc_init(&ph_dsc);
lv_obj_init_draw_label_dsc(obj, LV_PART_TEXTAREA_PLACEHOLDER, &ph_dsc);
if(ta->one_line) ph_dsc.flag |= LV_TEXT_FLAG_EXPAND;
lv_coord_t left = lv_obj_get_style_pad_left(obj, LV_PART_MAIN);
lv_coord_t top = lv_obj_get_style_pad_top(obj, LV_PART_MAIN);
lv_coord_t border_width = lv_obj_get_style_border_width(obj, LV_PART_MAIN);
lv_area_t ph_coords;
lv_area_copy(&ph_coords, &obj->coords);
lv_area_move(&ph_coords, left + border_width, top + border_width);
lv_draw_label(&ph_coords, clip_area, &ph_dsc, ta->placeholder_txt, NULL);
}
}
static void draw_cursor(lv_event_t * e)
{
lv_obj_t * obj = lv_event_get_target(e);
lv_textarea_t * ta = (lv_textarea_t *)obj;
const lv_area_t * clip_area = lv_event_get_param(e);
const char * txt = lv_label_get_text(ta->label);
if(ta->cursor.show == 0) return;
lv_draw_rect_dsc_t cur_dsc;
lv_draw_rect_dsc_init(&cur_dsc);
lv_obj_init_draw_rect_dsc(obj, LV_PART_CURSOR, &cur_dsc);
/*Draw he cursor according to the type*/
lv_area_t cur_area;
lv_area_copy(&cur_area, &ta->cursor.area);
cur_area.x1 += ta->label->coords.x1;
cur_area.y1 += ta->label->coords.y1;
cur_area.x2 += ta->label->coords.x1;
cur_area.y2 += ta->label->coords.y1;
lv_draw_rect(&cur_area, clip_area, &cur_dsc);
lv_coord_t border_width = lv_obj_get_style_border_width(obj, LV_PART_CURSOR);
lv_coord_t left = lv_obj_get_style_pad_left(obj, LV_PART_CURSOR) + border_width;
lv_coord_t top = lv_obj_get_style_pad_top(obj, LV_PART_CURSOR) + border_width;
char letter_buf[8] = {0};
lv_memcpy(letter_buf, &txt[ta->cursor.txt_byte_pos], _lv_txt_encoded_size(&txt[ta->cursor.txt_byte_pos]));
cur_area.x1 += left;
cur_area.y1 += top;
/*Draw the letter over the cursor only if
*the cursor has background or the letter has different color than the original.
*Else the original letter is drawn twice which makes it look bolder*/
lv_color_t label_color = lv_obj_get_style_text_color(ta->label, 0);
lv_draw_label_dsc_t cur_label_dsc;
lv_draw_label_dsc_init(&cur_label_dsc);
lv_obj_init_draw_label_dsc(obj, LV_PART_CURSOR, &cur_label_dsc);
if(cur_dsc.bg_opa > LV_OPA_MIN || cur_label_dsc.color.full != label_color.full) {
lv_draw_label(&cur_area, clip_area, &cur_label_dsc, letter_buf, NULL);
}
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_textarea.c | C | apache-2.0 | 41,357 |
/**
* @file lv_ta.h
*
*/
#ifndef LV_TEXTAREA_H
#define LV_TEXTAREA_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#if LV_USE_TEXTAREA != 0
/*Testing of dependencies*/
#if LV_USE_LABEL == 0
#error "lv_ta: lv_label is required. Enable it in lv_conf.h (LV_USE_LABEL 1)"
#endif
#include "../core/lv_obj.h"
#include "lv_label.h"
/*********************
* DEFINES
*********************/
#define LV_TEXTAREA_CURSOR_LAST (0x7FFF) /*Put the cursor after the last character*/
LV_EXPORT_CONST_INT(LV_TEXTAREA_CURSOR_LAST);
/**********************
* TYPEDEFS
**********************/
/*Data of text area*/
typedef struct {
lv_obj_t obj;
lv_obj_t * label; /*Label of the text area*/
char * placeholder_txt; /*Place holder label. only visible if text is an empty string*/
char * pwd_tmp; /*Used to store the original text in password mode*/
const char * accepted_chars; /*Only these characters will be accepted. NULL: accept all*/
uint32_t max_length; /*The max. number of characters. 0: no limit*/
uint16_t pwd_show_time; /*Time to show characters in password mode before change them to '*'*/
struct {
lv_coord_t valid_x; /*Used when stepping up/down to a shorter line.
*(Used by the library)*/
uint32_t pos; /*The current cursor position
*(0: before 1st letter; 1: before 2nd letter ...)*/
lv_area_t area; /*Cursor area relative to the Text Area*/
uint32_t txt_byte_pos; /*Byte index of the letter after (on) the cursor*/
uint8_t show : 1; /*Cursor is visible now or not (Handled by the library)*/
uint8_t click_pos : 1; /*1: Enable positioning the cursor by clicking the text area*/
} cursor;
#if LV_LABEL_TEXT_SELECTION
uint32_t sel_start; /*Temporary values for text selection*/
uint32_t sel_end;
uint8_t text_sel_in_prog : 1; /*User is in process of selecting*/
uint8_t text_sel_en : 1; /*Text can be selected on this text area*/
#endif
uint8_t pwd_mode : 1; /*Replace characters with '*'*/
uint8_t one_line : 1; /*One line mode (ignore line breaks)*/
} lv_textarea_t;
extern const lv_obj_class_t lv_textarea_class;
enum {
LV_PART_TEXTAREA_PLACEHOLDER = LV_PART_CUSTOM_FIRST,
};
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Create a text area objects
* @param parent pointer to an object, it will be the parent of the new text area
* @return pointer to the created text area
*/
lv_obj_t * lv_textarea_create(lv_obj_t * parent);
/*======================
* Add/remove functions
*=====================*/
/**
* Insert a character to the current cursor position.
* To add a wide char, e.g. 'Á' use `_lv_txt_encoded_conv_wc('Á')`
* @param obj pointer to a text area object
* @param c a character (e.g. 'a')
*/
void lv_textarea_add_char(lv_obj_t * obj, uint32_t c);
/**
* Insert a text to the current cursor position
* @param obj pointer to a text area object
* @param txt a '\0' terminated string to insert
*/
void lv_textarea_add_text(lv_obj_t * obj, const char * txt);
/**
* Delete a the left character from the current cursor position
* @param obj pointer to a text area object
*/
void lv_textarea_del_char(lv_obj_t * obj);
/**
* Delete the right character from the current cursor position
* @param obj pointer to a text area object
*/
void lv_textarea_del_char_forward(lv_obj_t * obj);
/*=====================
* Setter functions
*====================*/
/**
* Set the text of a text area
* @param obj pointer to a text area object
* @param txt pointer to the text
*/
void lv_textarea_set_text(lv_obj_t * obj, const char * txt);
/**
* Set the placeholder text of a text area
* @param obj pointer to a text area object
* @param txt pointer to the text
*/
void lv_textarea_set_placeholder_text(lv_obj_t * obj, const char * txt);
/**
* Set the cursor position
* @param obj pointer to a text area object
* @param pos the new cursor position in character index
* < 0 : index from the end of the text
* LV_TEXTAREA_CURSOR_LAST: go after the last character
*/
void lv_textarea_set_cursor_pos(lv_obj_t * obj, int32_t pos);
/**
* Enable/Disable the positioning of the cursor by clicking the text on the text area.
* @param obj pointer to a text area object
* @param en true: enable click positions; false: disable
*/
void lv_textarea_set_cursor_click_pos(lv_obj_t * obj, bool en);
/**
* Enable/Disable password mode
* @param obj pointer to a text area object
* @param en true: enable, false: disable
*/
void lv_textarea_set_password_mode(lv_obj_t * obj, bool en);
/**
* Configure the text area to one line or back to normal
* @param obj pointer to a text area object
* @param en true: one line, false: normal
*/
void lv_textarea_set_one_line(lv_obj_t * obj, bool en);
/**
* Set a list of characters. Only these characters will be accepted by the text area
* @param obj pointer to a text area object
* @param list list of characters. Only the pointer is saved. E.g. "+-.,0123456789"
*/
void lv_textarea_set_accepted_chars(lv_obj_t * obj, const char * list);
/**
* Set max length of a Text Area.
* @param obj pointer to a text area object
* @param num the maximal number of characters can be added (`lv_textarea_set_text` ignores it)
*/
void lv_textarea_set_max_length(lv_obj_t * obj, uint32_t num);
/**
* In `LV_EVENT_INSERT` the text which planned to be inserted can be replaced by an other text.
* It can be used to add automatic formatting to the text area.
* @param obj pointer to a text area object
* @param txt pointer to a new string to insert. If `""` no text will be added.
* The variable must be live after the `event_cb` exists. (Should be `global` or `static`)
*/
void lv_textarea_set_insert_replace(lv_obj_t * obj, const char * txt);
/**
* Enable/disable selection mode.
* @param obj pointer to a text area object
* @param en true or false to enable/disable selection mode
*/
void lv_textarea_set_text_selection(lv_obj_t * obj, bool en);
/**
* Set how long show the password before changing it to '*'
* @param obj pointer to a text area object
* @param time show time in milliseconds. 0: hide immediately.
*/
void lv_textarea_set_password_show_time(lv_obj_t * obj, uint16_t time);
/**
* Deprecated: use the normal text_align style property instead
* Set the label's alignment.
* It sets where the label is aligned (in one line mode it can be smaller than the text area)
* and how the lines of the area align in case of multiline text area
* @param obj pointer to a text area object
* @param align the align mode from ::lv_text_align_t
*/
void lv_textarea_set_align(lv_obj_t * obj, lv_text_align_t align);
/*=====================
* Getter functions
*====================*/
/**
* Get the text of a text area. In password mode it gives the real text (not '*'s).
* @param obj pointer to a text area object
* @return pointer to the text
*/
const char * lv_textarea_get_text(const lv_obj_t * obj);
/**
* Get the placeholder text of a text area
* @param obj pointer to a text area object
* @return pointer to the text
*/
const char * lv_textarea_get_placeholder_text(lv_obj_t * obj);
/**
* Get the label of a text area
* @param obj pointer to a text area object
* @return pointer to the label object
*/
lv_obj_t * lv_textarea_get_label(const lv_obj_t * obj);
/**
* Get the current cursor position in character index
* @param obj pointer to a text area object
* @return the cursor position
*/
uint32_t lv_textarea_get_cursor_pos(const lv_obj_t * obj);
/**
* Get whether the cursor click positioning is enabled or not.
* @param obj pointer to a text area object
* @return true: enable click positions; false: disable
*/
bool lv_textarea_get_cursor_click_pos(lv_obj_t * obj);
/**
* Get the password mode attribute
* @param obj pointer to a text area object
* @return true: password mode is enabled, false: disabled
*/
bool lv_textarea_get_password_mode(const lv_obj_t * obj);
/**
* Get the one line configuration attribute
* @param obj pointer to a text area object
* @return true: one line configuration is enabled, false: disabled
*/
bool lv_textarea_get_one_line(const lv_obj_t * obj);
/**
* Get a list of accepted characters.
* @param obj pointer to a text area object
* @return list of accented characters.
*/
const char * lv_textarea_get_accepted_chars(lv_obj_t * obj);
/**
* Get max length of a Text Area.
* @param obj pointer to a text area object
* @return the maximal number of characters to be add
*/
uint32_t lv_textarea_get_max_length(lv_obj_t * obj);
/**
* Find whether text is selected or not.
* @param obj pointer to a text area object
* @return whether text is selected or not
*/
bool lv_textarea_text_is_selected(const lv_obj_t * obj);
/**
* Find whether selection mode is enabled.
* @param obj pointer to a text area object
* @return true: selection mode is enabled, false: disabled
*/
bool lv_textarea_get_text_selection(lv_obj_t * obj);
/**
* Set how long show the password before changing it to '*'
* @param obj pointer to a text area object
* @return show time in milliseconds. 0: hide immediately.
*/
uint16_t lv_textarea_get_password_show_time(lv_obj_t * obj);
/*=====================
* Other functions
*====================*/
/**
* Clear the selection on the text area.
* @param obj pointer to a text area object
*/
void lv_textarea_clear_selection(lv_obj_t * obj);
/**
* Move the cursor one character right
* @param obj pointer to a text area object
*/
void lv_textarea_cursor_right(lv_obj_t * obj);
/**
* Move the cursor one character left
* @param obj pointer to a text area object
*/
void lv_textarea_cursor_left(lv_obj_t * obj);
/**
* Move the cursor one line down
* @param obj pointer to a text area object
*/
void lv_textarea_cursor_down(lv_obj_t * obj);
/**
* Move the cursor one line up
* @param obj pointer to a text area object
*/
void lv_textarea_cursor_up(lv_obj_t * obj);
/**********************
* MACROS
**********************/
#endif /*LV_USE_TEXTAREA_H*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_TEXTAREA_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_textarea.h | C | apache-2.0 | 10,828 |
CSRCS += lv_arc.c
CSRCS += lv_bar.c
CSRCS += lv_btn.c
CSRCS += lv_btnmatrix.c
CSRCS += lv_canvas.c
CSRCS += lv_checkbox.c
CSRCS += lv_dropdown.c
CSRCS += lv_img.c
CSRCS += lv_label.c
CSRCS += lv_line.c
CSRCS += lv_roller.c
CSRCS += lv_slider.c
CSRCS += lv_switch.c
CSRCS += lv_table.c
CSRCS += lv_textarea.c
DEPPATH += --dep-path $(LVGL_DIR)/$(LVGL_DIR_NAME)/src/widgets
VPATH += :$(LVGL_DIR)/$(LVGL_DIR_NAME)/src/widgets
CFLAGS += "-I$(LVGL_DIR)/$(LVGL_DIR_NAME)/src/widgets"
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/src/widgets/lv_widgets.mk | Makefile | apache-2.0 | 479 |
if(ESP_PLATFORM)
###################################
# Tests do not build for ESP-IDF. #
###################################
else()
cmake_minimum_required(VERSION 3.13)
project(lvgl_tests LANGUAGES C)
include(CTest)
set(LVGL_TEST_DIR ${CMAKE_CURRENT_SOURCE_DIR})
set(LVGL_TEST_OPTIONS_MINIMAL_MONOCHROME
-DLV_COLOR_DEPTH=1
-DLV_MEM_SIZE=65535
-DLV_DPI_DEF=40
-DLV_DRAW_COMPLEX=0
-DLV_USE_METER=0
-DLV_USE_LOG=1
-DLV_USE_ASSERT_NULL=0
-DLV_USE_ASSERT_MALLOC=0
-DLV_USE_ASSERT_MEM_INTEGRITY=0
-DLV_USE_ASSERT_OBJ=0
-DLV_USE_ASSERT_STYLE=0
-DLV_USE_USER_DATA=0
-DLV_FONT_UNSCII_8=1
-DLV_USE_BIDI=0
-DLV_USE_ARABIC_PERSIAN_CHARS=0
-DLV_BUILD_EXAMPLES=1
-DLV_FONT_DEFAULT=&lv_font_montserrat_14
-DLV_USE_PNG=1
-DLV_USE_BMP=1
-DLV_USE_GIF=1
-DLV_USE_QRCODE=1
)
set(LVGL_TEST_OPTIONS_NORMAL_8BIT
-DLV_COLOR_DEPTH=8
-DLV_MEM_SIZE=65535
-DLV_DPI_DEF=40
-DLV_DRAW_COMPLEX=1
-DLV_USE_LOG=1
-DLV_USE_ASSERT_NULL=0
-DLV_USE_ASSERT_MALLOC=0
-DLV_USE_ASSERT_MEM_INTEGRITY=0
-DLV_USE_ASSERT_OBJ=0
-DLV_USE_ASSERT_STYLE=0
-DLV_USE_USER_DATA=0
-DLV_FONT_UNSCII_8=1
-DLV_USE_FONT_SUBPX=1
-DLV_USE_BIDI=0
-DLV_USE_ARABIC_PERSIAN_CHARS=0
-DLV_BUILD_EXAMPLES=1
-DLV_FONT_DEFAULT=&lv_font_montserrat_14
-DLV_USE_PNG=1
-DLV_USE_BMP=1
-DLV_USE_SJPG=1
-DLV_USE_GIF=1
-DLV_USE_QRCODE=1
)
set(LVGL_TEST_OPTIONS_16BIT
-DLV_COLOR_DEPTH=16
-DLV_COLOR_16_SWAP=0
-DLV_MEM_SIZE=65536
-DLV_DPI_DEF=40
-DLV_DRAW_COMPLEX=1
-DLV_USE_LOG=1
-DLV_USE_ASSERT_NULL=0
-DLV_USE_ASSERT_MALLOC=0
-DLV_USE_ASSERT_MEM_INTEGRITY=0
-DLV_USE_ASSERT_OBJ=0
-DLV_USE_ASSERT_STYLE=0
-DLV_USE_USER_DATA=0
-DLV_FONT_UNSCII_8=1
-DLV_USE_FONT_SUBPX=1
-DLV_USE_BIDI=0
-DLV_USE_ARABIC_PERSIAN_CHARS=0
-DLV_BUILD_EXAMPLES=1
-DLV_FONT_DEFAULT=&lv_font_montserrat_14
-DLV_USE_PNG=1
-DLV_USE_BMP=1
-DLV_USE_SJPG=1
-DLV_USE_GIF=1
-DLV_USE_QRCODE=1
)
set(LVGL_TEST_OPTIONS_16BIT_SWAP
-DLV_COLOR_DEPTH=16
-DLV_COLOR_16_SWAP=1
-DLV_MEM_SIZE=65536
-DLV_DPI_DEF=40
-DLV_DRAW_COMPLEX=1
-DLV_USE_LOG=1
-DLV_USE_ASSERT_NULL=0
-DLV_USE_ASSERT_MALLOC=0
-DLV_USE_ASSERT_MEM_INTEGRITY=0
-DLV_USE_ASSERT_OBJ=0
-DLV_USE_ASSERT_STYLE=0
-DLV_USE_USER_DATA=0
-DLV_FONT_UNSCII_8=1
-DLV_USE_FONT_SUBPX=1
-DLV_USE_BIDI=0
-DLV_USE_ARABIC_PERSIAN_CHARS=0
-DLV_BUILD_EXAMPLES=1
-DLV_FONT_DEFAULT=&lv_font_montserrat_14
-DLV_USE_PNG=1
-DLV_USE_BMP=1
-DLV_USE_SJPG=1
-DLV_USE_GIF=1
-DLV_USE_QRCODE=1
)
set(LVGL_TEST_OPTIONS_FULL_32BIT
-DLV_COLOR_DEPTH=32
-DLV_MEM_SIZE=8388608
-DLV_DPI_DEF=160
-DLV_DRAW_COMPLEX=1
-DLV_SHADOW_CACHE_SIZE=1
-DLV_IMG_CACHE_DEF_SIZE=32
-DLV_USE_LOG=1
-DLV_LOG_LEVEL=LV_LOG_LEVEL_TRACE
-DLV_LOG_PRINTF=1
-DLV_USE_FONT_SUBPX=1
-DLV_FONT_SUBPX_BGR=1
-DLV_USE_PERF_MONITOR=1
-DLV_USE_ASSERT_NULL=1
-DLV_USE_ASSERT_MALLOC=1
-DLV_USE_ASSERT_MEM_INTEGRITY=1
-DLV_USE_ASSERT_OBJ=1
-DLV_USE_ASSERT_STYLE=1
-DLV_USE_USER_DATA=1
-DLV_USE_LARGE_COORD=1
-DLV_FONT_MONTSERRAT_8=1
-DLV_FONT_MONTSERRAT_10=1
-DLV_FONT_MONTSERRAT_12=1
-DLV_FONT_MONTSERRAT_14=1
-DLV_FONT_MONTSERRAT_16=1
-DLV_FONT_MONTSERRAT_18=1
-DLV_FONT_MONTSERRAT_20=1
-DLV_FONT_MONTSERRAT_22=1
-DLV_FONT_MONTSERRAT_24=1
-DLV_FONT_MONTSERRAT_26=1
-DLV_FONT_MONTSERRAT_28=1
-DLV_FONT_MONTSERRAT_30=1
-DLV_FONT_MONTSERRAT_32=1
-DLV_FONT_MONTSERRAT_34=1
-DLV_FONT_MONTSERRAT_36=1
-DLV_FONT_MONTSERRAT_38=1
-DLV_FONT_MONTSERRAT_40=1
-DLV_FONT_MONTSERRAT_42=1
-DLV_FONT_MONTSERRAT_44=1
-DLV_FONT_MONTSERRAT_46=1
-DLV_FONT_MONTSERRAT_48=1
-DLV_FONT_MONTSERRAT_12_SUBPX=1
-DLV_FONT_MONTSERRAT_28_COMPRESSED=1
-DLV_FONT_DEJAVU_16_PERSIAN_HEBREW=1
-DLV_FONT_SIMSUN_16_CJK=1
-DLV_FONT_UNSCII_8=1
-DLV_FONT_UNSCII_16=1
-DLV_FONT_FMT_TXT_LARGE=1
-DLV_USE_FONT_COMPRESSED=1
-DLV_USE_BIDI=1
-DLV_USE_ARABIC_PERSIAN_CHARS=1
-DLV_USE_PERF_MONITOR=1
-DLV_USE_MEM_MONITOR=1
-DLV_LABEL_TEXT_SELECTION=1
-DLV_BUILD_EXAMPLES=1
-DLV_FONT_DEFAULT=&lv_font_montserrat_24
-DLV_USE_FS_STDIO='A'
-DLV_USE_FS_POSIX='B'
-DLV_USE_PNG=1
-DLV_USE_BMP=1
-DLV_USE_SJPG=1
-DLV_USE_GIF=1
-DLV_USE_QRCODE=1
)
set(LVGL_TEST_OPTIONS_TEST
--coverage
-DLV_COLOR_DEPTH=32
-DLV_MEM_SIZE=2097152
-DLV_SHADOW_CACHE_SIZE=10240
-DLV_IMG_CACHE_DEF_SIZE=32
-DLV_USE_LOG=1
-DLV_LOG_PRINTF=1
-DLV_USE_FONT_SUBPX=1
-DLV_FONT_SUBPX_BGR=1
-DLV_USE_ASSERT_NULL=0
-DLV_USE_ASSERT_MALLOC=0
-DLV_USE_ASSERT_MEM_INTEGRITY=0
-DLV_USE_ASSERT_OBJ=0
-DLV_USE_ASSERT_STYLE=0
-DLV_USE_USER_DATA=1
-DLV_USE_LARGE_COORD=1
-DLV_FONT_MONTSERRAT_14=1
-DLV_FONT_MONTSERRAT_16=1
-DLV_FONT_MONTSERRAT_18=1
-DLV_FONT_MONTSERRAT_24=1
-DLV_FONT_MONTSERRAT_48=1
-DLV_FONT_MONTSERRAT_12_SUBPX=1
-DLV_FONT_MONTSERRAT_28_COMPRESSED=1
-DLV_FONT_DEJAVU_16_PERSIAN_HEBREW=1
-DLV_FONT_SIMSUN_16_CJK=1
-DLV_FONT_UNSCII_8=1
-DLV_FONT_UNSCII_16=1
-DLV_FONT_FMT_TXT_LARGE=1
-DLV_USE_FONT_COMPRESSED=1
-DLV_USE_BIDI=1
-DLV_USE_ARABIC_PERSIAN_CHARS=1
-DLV_LABEL_TEXT_SELECTION=1
-DLV_BUILD_EXAMPLES=1
-DLV_FONT_DEFAULT=&lv_font_montserrat_14
)
if (OPTIONS_MINIMAL_MONOCHROME)
set (BUILD_OPTIONS ${LVGL_TEST_OPTIONS_MINIMAL_MONOCHROME})
elseif (OPTIONS_NORMAL_8BIT)
set (BUILD_OPTIONS ${LVGL_TEST_OPTIONS_NORMAL_8BIT})
elseif (OPTIONS_16BIT)
set (BUILD_OPTIONS ${LVGL_TEST_OPTIONS_16BIT})
elseif (OPTIONS_16BIT_SWAP)
set (BUILD_OPTIONS ${LVGL_TEST_OPTIONS_16BIT_SWAP})
elseif (OPTIONS_FULL_32BIT)
set (BUILD_OPTIONS ${LVGL_TEST_OPTIONS_FULL_32BIT})
elseif (OPTIONS_TEST)
set (BUILD_OPTIONS ${LVGL_TEST_OPTIONS_TEST})
set (TEST_LIBS --coverage)
else()
message(FATAL_ERROR "Must provide an options value.")
endif()
# Options lvgl and examples are compiled with.
set(COMPILE_OPTIONS
-DLV_CONF_PATH=${LVGL_TEST_DIR}/src/lv_test_conf.h
-DLV_BUILD_TEST
-pedantic-errors
-Wall
-Wclobbered
-Wdeprecated
-Wdouble-promotion
-Wempty-body
-Werror
-Wextra
-Wformat-security
-Wmaybe-uninitialized
-Wmissing-prototypes
-Wpointer-arith
-Wmultichar
-Wno-discarded-qualifiers
-Wpedantic
-Wreturn-type
-Wshadow
-Wshift-negative-value
-Wsizeof-pointer-memaccess
-Wstack-usage=2048
-Wtype-limits
-Wundef
-Wuninitialized
-Wunreachable-code
${BUILD_OPTIONS}
)
# Options test cases are compiled with.
set(LVGL_TESTFILE_COMPILE_OPTIONS
${COMPILE_OPTIONS}
-Wno-missing-prototypes
)
get_filename_component(LVGL_DIR ${LVGL_TEST_DIR} DIRECTORY)
# Include lvgl project file.
include(${LVGL_DIR}/CMakeLists.txt)
target_compile_options(lvgl PUBLIC ${COMPILE_OPTIONS})
target_compile_options(lvgl_examples PUBLIC ${COMPILE_OPTIONS})
set(TEST_INCLUDE_DIRS
$<BUILD_INTERFACE:${LVGL_TEST_DIR}/src>
$<BUILD_INTERFACE:${LVGL_TEST_DIR}/unity>
$<BUILD_INTERFACE:${LVGL_TEST_DIR}>
)
add_library(test_common
STATIC
src/lv_test_indev.c
src/lv_test_init.c
src/test_fonts/font_1.c
src/test_fonts/font_2.c
src/test_fonts/font_3.c
unity/unity_support.c
unity/unity.c
)
target_include_directories(test_common PUBLIC ${TEST_INCLUDE_DIRS})
target_compile_options(test_common PUBLIC ${LVGL_TESTFILE_COMPILE_OPTIONS})
# Some examples `#include "lvgl/lvgl.h"` - which is a path which is not
# in this source repository. If this repo is in a directory names 'lvgl'
# then we can add our parent directory to the include path.
# TODO: This is not good practice and should be fixed.
get_filename_component(LVGL_PARENT_DIR ${LVGL_DIR} DIRECTORY)
target_include_directories(lvgl_examples PUBLIC $<BUILD_INTERFACE:${LVGL_PARENT_DIR}>)
# Generate one test executable for each source file pair.
# The sources in src/test_runners is auto-generated, the
# sources in src/test_cases is the actual test case.
file( GLOB TEST_CASE_FILES src/test_cases/*.c )
foreach( test_case_fname ${TEST_CASE_FILES} )
# If test file is foo/bar/baz.c then test_name is "baz".
get_filename_component(test_name ${test_case_fname} NAME_WLE)
if (${test_name} STREQUAL "_test_template")
continue()
endif()
# Create path to auto-generated source file.
set(test_runner_fname src/test_runners/${test_name}_Runner.c)
add_executable( ${test_name}
${test_case_fname}
${test_runner_fname}
)
target_link_libraries(${test_name} test_common lvgl_examples lvgl png ${TEST_LIBS})
target_include_directories(${test_name} PUBLIC ${TEST_INCLUDE_DIRS})
target_compile_options(${test_name} PUBLIC ${LVGL_TESTFILE_COMPILE_OPTIONS})
add_test(
NAME ${test_name}
WORKING_DIRECTORY ${LVGL_TEST_DIR}
COMMAND ${test_name})
endforeach( test_case_fname ${TEST_CASE_FILES} )
endif()
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/CMakeLists.txt | CMake | apache-2.0 | 9,496 |
#!/usr/bin/env python3
import argparse
import errno
import glob
import shutil
import subprocess
import sys
import os
lvgl_test_dir = os.path.dirname(os.path.realpath(__file__))
# Key values must match variable names in CMakeLists.txt.
build_only_options = {
'OPTIONS_MINIMAL_MONOCHROME': 'Minimal config monochrome',
'OPTIONS_NORMAL_8BIT': 'Normal config, 8 bit color depth',
'OPTIONS_16BIT': 'Minimal config, 16 bit color depth',
'OPTIONS_16BIT_SWAP': 'Normal config, 16 bit color depth swapped',
'OPTIONS_FULL_32BIT': 'Full config, 32 bit color depth',
}
test_options = {
'OPTIONS_TEST': 'Test config, 32 bit color depth',
}
def is_valid_option_name(option_name):
return option_name in build_only_options or option_name in test_options
def get_option_description(option_name):
if option_name in build_only_options:
return build_only_options[option_name]
return test_options[option_name]
def delete_dir_ignore_missing(dir_path):
'''Recursively delete a directory and ignore if missing.'''
try:
shutil.rmtree(dir_path)
except FileNotFoundError:
pass
def generate_test_runners():
'''Generate the test runner source code.'''
global lvgl_test_dir
os.chdir(lvgl_test_dir)
delete_dir_ignore_missing('src/test_runners')
os.mkdir('src/test_runners')
# TODO: Intermediate files should be in the build folders, not alongside
# the other repo source.
for f in glob.glob("./src/test_cases/test_*.c"):
r = f[:-2] + "_Runner.c"
r = r.replace("/test_cases/", "/test_runners/")
subprocess.check_call(['ruby', 'unity/generate_test_runner.rb',
f, r, 'config.yml'])
def options_abbrev(options_name):
'''Return an abbreviated version of the option name.'''
prefix = 'OPTIONS_'
assert options_name.startswith(prefix)
return options_name[len(prefix):].lower()
def get_base_buid_dir(options_name):
'''Given the build options name, return the build directory name.
Does not return the full path to the directory - just the base name.'''
return 'build_%s' % options_abbrev(options_name)
def get_build_dir(options_name):
'''Given the build options name, return the build directory name.
Returns absolute path to the build directory.'''
global lvgl_test_dir
return os.path.join(lvgl_test_dir, get_base_buid_dir(options_name))
def build_tests(options_name, build_type, clean):
'''Build all tests for the specified options name.'''
global lvgl_test_dir
print()
print()
label = 'Building: %s: %s' % (options_abbrev(
options_name), get_option_description(options_name))
print('=' * len(label))
print(label)
print('=' * len(label))
print(flush=True)
build_dir = get_build_dir(options_name)
if clean:
delete_dir_ignore_missing(build_dir)
os.chdir(lvgl_test_dir)
created_build_dir = False
if not os.path.isdir(build_dir):
os.mkdir(build_dir)
created_build_dir = True
os.chdir(build_dir)
if created_build_dir:
subprocess.check_call(['cmake', '-DCMAKE_BUILD_TYPE=%s' % build_type,
'-D%s=1' % options_name, '..'])
subprocess.check_call(['cmake', '--build', build_dir,
'--parallel', str(os.cpu_count())])
def run_tests(options_name):
'''Run the tests for the given options name.'''
print()
print()
label = 'Running tests for %s' % options_abbrev(options_name)
print('=' * len(label))
print(label)
print('=' * len(label), flush=True)
os.chdir(get_build_dir(options_name))
subprocess.check_call(
['ctest', '--parallel', str(os.cpu_count()), '--output-on-failure'])
def generate_code_coverage_report():
'''Produce code coverage test reports for the test execution.'''
global lvgl_test_dir
print()
print()
label = 'Generating code coverage reports'
print('=' * len(label))
print(label)
print('=' * len(label))
print(flush=True)
os.chdir(lvgl_test_dir)
delete_dir_ignore_missing('report')
os.mkdir('report')
root_dir = os.pardir
html_report_file = 'report/index.html'
cmd = ['gcovr', '--root', root_dir, '--html-details', '--output',
html_report_file, '--xml', 'report/coverage.xml',
'-j', str(os.cpu_count()), '--print-summary',
'--html-title', 'LVGL Test Coverage']
for d in ('.*\\bexamples/.*', '\\bsrc/test_.*', '\\bsrc/lv_test.*', '\\bunity\\b'):
cmd.extend(['--exclude', d])
subprocess.check_call(cmd)
print("Done: See %s" % html_report_file, flush=True)
if __name__ == "__main__":
epilog = '''This program builds and optionally runs the LVGL test programs.
There are two types of LVGL tests: "build", and "test". The build-only
tests, as their name suggests, only verify that the program successfully
compiles and links (with various build options). There are also a set of
tests that execute to verify correct LVGL library behavior.
'''
parser = argparse.ArgumentParser(
description='Build and/or run LVGL tests.', epilog=epilog)
parser.add_argument('--build-options', nargs=1,
help='''the build option name to build or run. When
omitted all build configurations are used.
''')
parser.add_argument('--clean', action='store_true', default=False,
help='clean existing build artifacts before operation.')
parser.add_argument('--report', action='store_true',
help='generate code coverage report for tests.')
parser.add_argument('actions', nargs='*', choices=['build', 'test'],
help='build: compile build tests, test: compile/run executable tests.')
args = parser.parse_args()
if args.build_options:
options_to_build = args.build_options
else:
if 'build' in args.actions:
if 'test' in args.actions:
options_to_build = {**build_only_options, **test_options}
else:
options_to_build = build_only_options
else:
options_to_build = test_options
for opt in options_to_build:
if not is_valid_option_name(opt):
print('Invalid build option "%s"' % opt, file=sys.stderr)
sys.exit(errno.EINVAL)
generate_test_runners()
for options_name in options_to_build:
is_test = options_name in test_options
build_type = 'Debug'
build_tests(options_name, build_type, args.clean)
if is_test:
try:
run_tests(options_name)
except subprocess.CalledProcessError as e:
sys.exit(e.returncode)
if args.report:
generate_code_coverage_report()
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/main.py | Python | apache-2.0 | 6,891 |
/**
* @file lv_test_conf.h
*
*/
#ifndef LV_TEST_CONF_H
#define LV_TEST_CONF_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
uint32_t custom_tick_get(void);
#define LV_TICK_CUSTOM_SYS_TIME_EXPR custom_tick_get()
typedef void * lv_user_data_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_TEST_CONF_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/lv_test_conf.h | C | apache-2.0 | 645 |
#if LV_BUILD_TEST
#include "../lvgl.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include "lv_test_indev.h"
#include "lv_test_init.h"
static lv_coord_t x_act;
static lv_coord_t y_act;
static uint32_t key_act;
static int32_t diff_act;
static bool mouse_pressed;
static bool key_pressed;
static bool enc_pressed;
void lv_test_mouse_read_cb(lv_indev_drv_t * drv, lv_indev_data_t * data)
{
LV_UNUSED(drv);
data->point.x = x_act;
data->point.y = y_act;
data->state = mouse_pressed ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED;
}
void lv_test_mouse_move_to(lv_coord_t x, lv_coord_t y)
{
x_act = x;
y_act = y;
}
void lv_test_mouse_move_by(lv_coord_t x, lv_coord_t y)
{
x_act += x;
y_act += y;
}
void lv_test_mouse_press(void)
{
mouse_pressed = true;
}
void lv_test_mouse_release(void)
{
mouse_pressed = false;
}
void lv_test_mouse_click_at(lv_coord_t x, lv_coord_t y)
{
lv_test_mouse_release();
lv_test_indev_wait(50);
lv_test_mouse_move_to(x, y);
lv_test_mouse_press();
lv_test_indev_wait(50);
lv_test_mouse_release();
lv_test_indev_wait(50);
}
void lv_test_keypad_read_cb(lv_indev_drv_t * drv, lv_indev_data_t * data)
{
LV_UNUSED(drv);
data->key = key_act;
data->state = key_pressed ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED;
}
void lv_test_key_press(uint32_t k)
{
key_act = k;
key_pressed = true;
}
void lv_test_key_release(void)
{
key_pressed = false;
}
void lv_test_key_hit(uint32_t k)
{
lv_test_key_release();
lv_test_indev_wait(50);
lv_test_key_press(k);
lv_test_mouse_press();
lv_test_indev_wait(50);
lv_test_key_release();
lv_test_indev_wait(50);
}
void lv_test_encoder_read_cb(lv_indev_drv_t * drv, lv_indev_data_t * data)
{
LV_UNUSED(drv);
data->enc_diff = diff_act;
data->state = enc_pressed ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED;
diff_act = 0;
}
void lv_test_encoder_add_diff(int32_t d)
{
diff_act += d;
}
void lv_test_encoder_turn(int32_t d)
{
diff_act += d;
lv_test_indev_wait(50);
}
void lv_test_encoder_press(void)
{
enc_pressed = true;
}
void lv_test_encoder_release(void)
{
enc_pressed = false;
}
void lv_test_encoder_click(void)
{
lv_test_encoder_release();
lv_test_indev_wait(50);
lv_test_encoder_press();
lv_test_indev_wait(50);
lv_test_encoder_release();
lv_test_indev_wait(50);
}
void lv_test_indev_wait(uint32_t ms)
{
uint32_t t = lv_tick_get();
while(lv_tick_elaps(t) < ms) {
lv_timer_handler();
lv_tick_inc(1);
}
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/lv_test_indev.c | C | apache-2.0 | 2,523 |
#ifndef LV_TEST_INDEV_H
#define LV_TEST_INDEV_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include "../lvgl.h"
void lv_test_mouse_read_cb(lv_indev_drv_t * drv, lv_indev_data_t * data);
void lv_test_mouse_move_to(lv_coord_t x, lv_coord_t y);
void lv_test_mouse_move_by(lv_coord_t x, lv_coord_t y);
void lv_test_mouse_press(void);
void lv_test_mouse_release(void);
void lv_test_mouse_click_at(lv_coord_t x, lv_coord_t y);
void lv_test_keypad_read_cb(lv_indev_drv_t * drv, lv_indev_data_t * data);
void lv_test_key_press(uint32_t k);
void lv_test_key_release(void);
void lv_test_key_hit(uint32_t k);
void lv_test_encoder_read_cb(lv_indev_drv_t * drv, lv_indev_data_t * data) ;
void lv_test_encoder_add_diff(int32_t d);
void lv_test_encoder_turn(int32_t d);
void lv_test_encoder_press(void);
void lv_test_encoder_release(void);
void lv_test_encoder_click(void);
void lv_test_indev_wait(uint32_t ms);
extern lv_indev_t * lv_test_mouse_indev;
extern lv_indev_t * lv_test_keypad_indev;
extern lv_indev_t * lv_test_encoder_indev;
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_TEST_INDEV_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/lv_test_indev.h | C | apache-2.0 | 1,124 |
#if LV_BUILD_TEST
#include "lv_test_init.h"
#include "lv_test_indev.h"
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#define HOR_RES 800
#define VER_RES 480
static void hal_init(void);
static void dummy_flush_cb(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p);
lv_indev_t * lv_test_mouse_indev;
lv_indev_t * lv_test_keypad_indev;
lv_indev_t * lv_test_encoder_indev;
lv_color_t test_fb[HOR_RES * VER_RES];
static lv_color_t disp_buf1[HOR_RES * VER_RES];
void lv_test_init(void)
{
lv_init();
hal_init();
}
void lv_test_deinit(void)
{
lv_mem_deinit();
}
static void * open_cb(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode)
{
(void) drv;
(void) mode;
FILE * fp = fopen(path, "rb"); // only reading is supported
return fp;
}
static lv_fs_res_t close_cb(lv_fs_drv_t * drv, void * file_p)
{
(void) drv;
fclose(file_p);
return LV_FS_RES_OK;
}
static lv_fs_res_t read_cb(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br)
{
(void) drv;
*br = fread(buf, 1, btr, file_p);
return (*br <= 0) ? LV_FS_RES_UNKNOWN : LV_FS_RES_OK;
}
static lv_fs_res_t seek_cb(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t w)
{
(void) drv;
uint32_t w2;
switch(w) {
case LV_FS_SEEK_SET:
w2 = SEEK_SET;
break;
case LV_FS_SEEK_CUR:
w2 = SEEK_CUR;
break;
case LV_FS_SEEK_END:
w2 = SEEK_END;
break;
default:
w2 = SEEK_SET;
}
fseek (file_p, pos, w2);
return LV_FS_RES_OK;
}
static lv_fs_res_t tell_cb(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p)
{
(void) drv;
*pos_p = ftell(file_p);
return LV_FS_RES_OK;
}
static void hal_init(void)
{
static lv_disp_draw_buf_t draw_buf;
lv_disp_draw_buf_init(&draw_buf, disp_buf1, NULL, HOR_RES * VER_RES);
static lv_disp_drv_t disp_drv;
lv_disp_drv_init(&disp_drv);
disp_drv.draw_buf = &draw_buf;
disp_drv.flush_cb = dummy_flush_cb;
disp_drv.hor_res = HOR_RES;
disp_drv.ver_res = VER_RES;
lv_disp_drv_register(&disp_drv);
static lv_indev_drv_t indev_mouse_drv;
lv_indev_drv_init(&indev_mouse_drv);
indev_mouse_drv.type = LV_INDEV_TYPE_POINTER;
indev_mouse_drv.read_cb = lv_test_mouse_read_cb;
lv_test_mouse_indev = lv_indev_drv_register(&indev_mouse_drv);
static lv_indev_drv_t indev_keypad_drv;
lv_indev_drv_init(&indev_keypad_drv);
indev_keypad_drv.type = LV_INDEV_TYPE_KEYPAD;
indev_keypad_drv.read_cb = lv_test_keypad_read_cb;
lv_test_keypad_indev = lv_indev_drv_register(&indev_keypad_drv);
static lv_indev_drv_t indev_encoder_drv;
lv_indev_drv_init(&indev_encoder_drv);
indev_encoder_drv.type = LV_INDEV_TYPE_ENCODER;
indev_encoder_drv.read_cb = lv_test_encoder_read_cb;
lv_test_encoder_indev = lv_indev_drv_register(&indev_encoder_drv);
static lv_fs_drv_t drv;
lv_fs_drv_init(&drv); /*Basic initialization*/
drv.letter = 'F'; /*An uppercase letter to identify the drive*/
drv.open_cb = open_cb; /*Callback to open a file*/
drv.close_cb = close_cb; /*Callback to close a file*/
drv.read_cb = read_cb; /*Callback to read a file*/
drv.seek_cb = seek_cb; /*Callback to seek in a file (Move cursor)*/
drv.tell_cb = tell_cb; /*Callback to tell the cursor position*/
lv_fs_drv_register(&drv); /*Finally register the drive*/
}
static void dummy_flush_cb(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p)
{
LV_UNUSED(area);
LV_UNUSED(color_p);
memcpy(test_fb, color_p, lv_area_get_size(area) * sizeof(lv_color_t));
lv_disp_flush_ready(disp_drv);
}
uint32_t custom_tick_get(void)
{
static uint64_t start_ms = 0;
if(start_ms == 0) {
struct timeval tv_start;
gettimeofday(&tv_start, NULL);
start_ms = (tv_start.tv_sec * 1000000 + tv_start.tv_usec) / 1000;
}
struct timeval tv_now;
gettimeofday(&tv_now, NULL);
uint64_t now_ms;
now_ms = (tv_now.tv_sec * 1000000 + tv_now.tv_usec) / 1000;
uint32_t time_ms = now_ms - start_ms;
return time_ms;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/lv_test_init.c | C | apache-2.0 | 4,313 |
#ifndef LV_TEST_INIT_H
#define LV_TEST_INIT_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include <../lvgl.h>
void lv_test_init(void);
void lv_test_deinit(void);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_TEST_INIT_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/lv_test_init.h | C | apache-2.0 | 253 |
#if LV_BUILD_TEST
#include "../lvgl.h"
#include "unity/unity.h"
void setUp(void);
void tearDown(void);
void test_func_1(void);
void setUp(void)
{
/* Function run before every test */
}
void tearDown(void)
{
/* Function run after every test */
}
void test_func_1(void)
{
TEST_ASSERT_EQUAL(actual, expected);
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/test_cases/_test_template.c | C | apache-2.0 | 333 |
#if LV_BUILD_TEST
#include "../lvgl.h"
#include "unity/unity.h"
#include "lv_test_indev.h"
/* This function runs before each test */
void setUp(void);
void test_arc_creation_successfull(void);
void test_arc_should_truncate_to_max_range_when_new_value_exceeds_it(void);
void test_arc_should_truncate_to_min_range_when_new_value_is_inferior(void);
void test_arc_should_update_value_after_updating_range(void);
void test_arc_should_update_angles_when_changing_to_symmetrical_mode(void);
void test_arc_should_update_angles_when_changing_to_symmetrical_mode_value_more_than_middle_range(void);
void test_arc_angles_when_reversed(void);
static lv_obj_t *active_screen = NULL;
static lv_obj_t *arc = NULL;
static uint32_t event_cnt;
static void dummy_event_cb(lv_event_t * e);
void setUp(void)
{
active_screen = lv_scr_act();
}
void test_arc_creation_successfull(void)
{
arc = lv_arc_create(active_screen);
TEST_ASSERT_NOT_NULL(arc);
}
void test_arc_should_truncate_to_max_range_when_new_value_exceeds_it(void)
{
/* Default max range is 100 */
int16_t value_after_truncation = 100;
arc = lv_arc_create(active_screen);
lv_arc_set_value(arc, 200);
TEST_ASSERT_EQUAL_INT16(value_after_truncation, lv_arc_get_value(arc));
}
void test_arc_should_truncate_to_min_range_when_new_value_is_inferior(void)
{
/* Default min range is 100 */
int16_t value_after_truncation = 0;
arc = lv_arc_create(active_screen);
lv_arc_set_value(arc, 0);
TEST_ASSERT_EQUAL_INT16(value_after_truncation, lv_arc_get_value(arc));
}
void test_arc_should_update_value_after_updating_range(void)
{
int16_t value_after_updating_max_range = 50;
int16_t value_after_updating_min_range = 30;
arc = lv_arc_create(active_screen);
lv_arc_set_value(arc, 80);
lv_arc_set_range(arc, 1, 50);
TEST_ASSERT_EQUAL_INT16(value_after_updating_max_range, lv_arc_get_value(arc));
lv_arc_set_value(arc, 10);
lv_arc_set_range(arc, 30, 50);
TEST_ASSERT_EQUAL_INT16(value_after_updating_min_range, lv_arc_get_value(arc));
}
void test_arc_should_update_angles_when_changing_to_symmetrical_mode(void)
{
int16_t expected_angle_start = 135;
int16_t expected_angle_end = 270;
/* start angle is 135, end angle is 45 at creation */
arc = lv_arc_create(active_screen);
lv_arc_set_mode(arc, LV_ARC_MODE_SYMMETRICAL);
TEST_ASSERT_EQUAL_INT16(expected_angle_start, lv_arc_get_angle_start(arc));
TEST_ASSERT_EQUAL_INT16(expected_angle_end, lv_arc_get_angle_end(arc));
}
void test_arc_should_update_angles_when_changing_to_symmetrical_mode_value_more_than_middle_range(void)
{
int16_t expected_angle_start = 270;
int16_t expected_angle_end = 45;
/* start angle is 135, end angle is 45 at creation */
arc = lv_arc_create(active_screen);
lv_arc_set_value(arc, 100);
lv_arc_set_mode(arc, LV_ARC_MODE_SYMMETRICAL);
TEST_ASSERT_EQUAL_INT16(expected_angle_start, lv_arc_get_angle_start(arc));
TEST_ASSERT_EQUAL_INT16(expected_angle_end, lv_arc_get_angle_end(arc));
}
/* See #2522 for more information */
void test_arc_angles_when_reversed(void)
{
uint16_t expected_start_angle = 36;
uint16_t expected_end_angle = 90;
int16_t expected_value = 40;
lv_obj_t *arcBlack;
arcBlack = lv_arc_create(lv_scr_act());
lv_arc_set_mode(arcBlack, LV_ARC_MODE_REVERSE);
lv_arc_set_bg_angles(arcBlack, 0, 90);
lv_arc_set_value(arcBlack, expected_value);
TEST_ASSERT_EQUAL_UINT16(expected_start_angle, lv_arc_get_angle_start(arcBlack));
TEST_ASSERT_EQUAL_UINT16(expected_end_angle, lv_arc_get_angle_end(arcBlack));
TEST_ASSERT_EQUAL_INT16(expected_value, lv_arc_get_value(arcBlack));
}
void test_arc_click_area_with_adv_hittest(void)
{
arc = lv_arc_create(lv_scr_act());
lv_obj_set_size(arc, 100, 100);
lv_obj_set_style_arc_width(arc, 10, 0);
lv_obj_add_flag(arc, LV_OBJ_FLAG_ADV_HITTEST);
lv_obj_add_event_cb(arc, dummy_event_cb, LV_EVENT_VALUE_CHANGED, NULL);
lv_obj_set_ext_click_area(arc, 5);
/*No click detected at the middle*/
event_cnt = 0;
lv_test_mouse_click_at(50, 50);
TEST_ASSERT_EQUAL_UINT32(0, event_cnt);
/*No click close to the radius - bg_arc - ext_click_area*/
event_cnt = 0;
lv_test_mouse_click_at(83, 50);
TEST_ASSERT_EQUAL_UINT32(0, event_cnt);
/*Click on the radius - bg_arc - ext_click_area*/
event_cnt = 0;
lv_test_mouse_click_at(86, 50);
TEST_ASSERT_GREATER_THAN(0, event_cnt);
/*Click on the radius + ext_click_area*/
event_cnt = 0;
lv_test_mouse_click_at(104, 50);
TEST_ASSERT_GREATER_THAN(0, event_cnt);
/*No click beyond to the radius + ext_click_area*/
event_cnt = 0;
lv_test_mouse_click_at(106, 50);
TEST_ASSERT_EQUAL_UINT32(0, event_cnt);
}
static void dummy_event_cb(lv_event_t * e)
{
LV_UNUSED(e);
event_cnt++;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/test_cases/test_arc.c | C | apache-2.0 | 4,918 |
#if LV_BUILD_TEST
#include "../lvgl.h"
#include "unity/unity.h"
#include "lv_test_indev.h"
void test_checkbox_creation_successfull(void);
void test_checkbox_should_call_event_handler_on_click_when_enabled(void);
void test_checkbox_should_have_default_text_when_created(void);
void test_checkbox_should_return_dinamically_allocated_text(void);
void test_checkbox_should_allocate_memory_for_static_text(void);
static lv_obj_t *active_screen = NULL;
static lv_obj_t *checkbox = NULL;
static volatile bool event_called = false;
static void event_handler(lv_event_t *e)
{
lv_event_code_t code = lv_event_get_code(e);
if (LV_EVENT_VALUE_CHANGED == code) {
event_called = true;
}
}
void test_checkbox_creation_successfull(void)
{
active_screen = lv_scr_act();
checkbox = lv_checkbox_create(active_screen);
TEST_ASSERT_NOT_NULL(checkbox);
}
void test_checkbox_should_call_event_handler_on_click_when_enabled(void)
{
active_screen = lv_scr_act();
checkbox = lv_checkbox_create(active_screen);
lv_obj_add_state(checkbox, LV_STATE_CHECKED);
lv_obj_add_event_cb(checkbox, event_handler, LV_EVENT_ALL, NULL);
lv_test_mouse_click_at(checkbox->coords.x1, checkbox->coords.y1);
TEST_ASSERT_TRUE(event_called);
event_called = false;
}
void test_checkbox_should_have_default_text_when_created(void)
{
const char *default_text = "Check box";
active_screen = lv_scr_act();
checkbox = lv_checkbox_create(active_screen);
TEST_ASSERT_EQUAL_STRING(default_text, lv_checkbox_get_text(checkbox));
TEST_ASSERT_NOT_NULL(lv_checkbox_get_text(checkbox));
}
void test_checkbox_should_return_dinamically_allocated_text(void)
{
const char *message = "Hello World!";
active_screen = lv_scr_act();
checkbox = lv_checkbox_create(active_screen);
lv_checkbox_set_text(checkbox, message);
TEST_ASSERT_EQUAL_STRING(message, lv_checkbox_get_text(checkbox));
TEST_ASSERT_NOT_NULL(lv_checkbox_get_text(checkbox));
}
void test_checkbox_should_allocate_memory_for_static_text(void)
{
uint32_t initial_available_memory = 0;
const char *static_text = "Keep me while you exist";
lv_mem_monitor_t m1;
lv_mem_monitor(&m1);
active_screen = lv_scr_act();
checkbox = lv_checkbox_create(active_screen);
initial_available_memory = m1.free_size;
lv_checkbox_set_text_static(checkbox, static_text);
lv_mem_monitor(&m1);
TEST_ASSERT_LESS_THAN(initial_available_memory, m1.free_size);
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/test_cases/test_checkbox.c | C | apache-2.0 | 2,516 |
#if LV_BUILD_TEST
#include "../lvgl.h"
#include "unity/unity.h"
void test_config(void);
void test_config(void)
{
TEST_ASSERT_EQUAL(130, LV_DPI_DEF);
TEST_ASSERT_EQUAL(130, lv_disp_get_dpi(NULL));
TEST_ASSERT_EQUAL(800, LV_HOR_RES);
TEST_ASSERT_EQUAL(800, lv_disp_get_hor_res(NULL));
TEST_ASSERT_EQUAL(480, LV_VER_RES);
TEST_ASSERT_EQUAL(480, lv_disp_get_ver_res(NULL));
TEST_ASSERT_EQUAL(32, LV_COLOR_DEPTH);
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/test_cases/test_config.c | C | apache-2.0 | 436 |
#if LV_BUILD_TEST
#include "../lvgl.h"
#include "unity/unity.h"
#include "lv_test_indev.h"
void test_dropdown_create_delete(void);
void test_dropdown_set_options(void);
void test_dropdown_select(void);
void test_dropdown_click(void);
void test_dropdown_keypad(void);
void test_dropdown_encoder(void);
void test_dropdown_render_1(void);
void test_dropdown_render_2(void);
void test_dropdown_create_delete(void)
{
lv_dropdown_create(lv_scr_act());
TEST_ASSERT_EQUAL(1, lv_obj_get_child_cnt(lv_scr_act()));
lv_obj_t * dd2 = lv_dropdown_create(lv_scr_act());
lv_obj_set_pos(dd2, 200, 0);
TEST_ASSERT_EQUAL(2, lv_obj_get_child_cnt(lv_scr_act()));
TEST_ASSERT_NULL(lv_dropdown_get_list(dd2));
lv_dropdown_open(dd2);
TEST_ASSERT_EQUAL(3, lv_obj_get_child_cnt(lv_scr_act()));
TEST_ASSERT_NOT_NULL(lv_dropdown_get_list(dd2));
lv_dropdown_open(dd2); /*Try to pen again*/
TEST_ASSERT_EQUAL(3, lv_obj_get_child_cnt(lv_scr_act()));
lv_obj_t * dd3 = lv_dropdown_create(lv_scr_act());
lv_obj_set_pos(dd3, 400, 0);
TEST_ASSERT_EQUAL(4, lv_obj_get_child_cnt(lv_scr_act()));
lv_dropdown_open(dd3);
TEST_ASSERT_EQUAL(5, lv_obj_get_child_cnt(lv_scr_act()));
lv_dropdown_close(dd3);
TEST_ASSERT_EQUAL(4, lv_obj_get_child_cnt(lv_scr_act()));
lv_dropdown_close(dd3); /*Try to close again*/
TEST_ASSERT_EQUAL(4, lv_obj_get_child_cnt(lv_scr_act()));
lv_obj_del(dd2);
TEST_ASSERT_EQUAL(2, lv_obj_get_child_cnt(lv_scr_act()));
lv_obj_clean(lv_scr_act());
TEST_ASSERT_EQUAL(0, lv_obj_get_child_cnt(lv_scr_act()));
}
void test_dropdown_set_options(void)
{
lv_mem_monitor_t m1;
lv_mem_monitor(&m1);
lv_obj_t * dd1 = lv_dropdown_create(lv_scr_act());
TEST_ASSERT_EQUAL_STRING("Option 1\nOption 2\nOption 3", lv_dropdown_get_options(dd1));
TEST_ASSERT_EQUAL(3, lv_dropdown_get_option_cnt(dd1));
lv_dropdown_set_options(dd1, "a1\nb2\nc3\nd4\ne5\nf6");
TEST_ASSERT_EQUAL_STRING("a1\nb2\nc3\nd4\ne5\nf6", lv_dropdown_get_options(dd1));
TEST_ASSERT_EQUAL(6, lv_dropdown_get_option_cnt(dd1));
lv_obj_set_width(dd1, 200);
lv_dropdown_open(dd1);
lv_obj_update_layout(dd1);
TEST_ASSERT_EQUAL(200, lv_obj_get_width(lv_dropdown_get_list(dd1)));
lv_dropdown_close(dd1);
lv_dropdown_add_option(dd1, "x0", 0);
TEST_ASSERT_EQUAL_STRING("x0\na1\nb2\nc3\nd4\ne5\nf6", lv_dropdown_get_options(dd1));
TEST_ASSERT_EQUAL(7, lv_dropdown_get_option_cnt(dd1));
lv_dropdown_add_option(dd1, "y0", 3);
TEST_ASSERT_EQUAL_STRING("x0\na1\nb2\ny0\nc3\nd4\ne5\nf6", lv_dropdown_get_options(dd1));
TEST_ASSERT_EQUAL(8, lv_dropdown_get_option_cnt(dd1));
lv_dropdown_add_option(dd1, "z0", LV_DROPDOWN_POS_LAST);
TEST_ASSERT_EQUAL_STRING("x0\na1\nb2\ny0\nc3\nd4\ne5\nf6\nz0", lv_dropdown_get_options(dd1));
TEST_ASSERT_EQUAL(9, lv_dropdown_get_option_cnt(dd1));
lv_dropdown_clear_options(dd1);
TEST_ASSERT_EQUAL_STRING("", lv_dropdown_get_options(dd1));
TEST_ASSERT_EQUAL(0, lv_dropdown_get_option_cnt(dd1));
lv_dropdown_set_options(dd1, "o1\no2"); /*Just to add some content before lv_dropdown_set_options_static*/
lv_dropdown_set_options_static(dd1, "a1\nb2\nc3\nd4\ne5\nf6");
TEST_ASSERT_EQUAL_STRING("a1\nb2\nc3\nd4\ne5\nf6", lv_dropdown_get_options(dd1));
TEST_ASSERT_EQUAL(6, lv_dropdown_get_option_cnt(dd1));
lv_dropdown_add_option(dd1, "x0", 0);
TEST_ASSERT_EQUAL_STRING("x0\na1\nb2\nc3\nd4\ne5\nf6", lv_dropdown_get_options(dd1));
TEST_ASSERT_EQUAL(7, lv_dropdown_get_option_cnt(dd1));
lv_dropdown_add_option(dd1, "y0", 3);
TEST_ASSERT_EQUAL_STRING("x0\na1\nb2\ny0\nc3\nd4\ne5\nf6", lv_dropdown_get_options(dd1));
TEST_ASSERT_EQUAL(8, lv_dropdown_get_option_cnt(dd1));
lv_dropdown_add_option(dd1, "z0", LV_DROPDOWN_POS_LAST);
TEST_ASSERT_EQUAL_STRING("x0\na1\nb2\ny0\nc3\nd4\ne5\nf6\nz0", lv_dropdown_get_options(dd1));
TEST_ASSERT_EQUAL(9, lv_dropdown_get_option_cnt(dd1));
lv_dropdown_clear_options(dd1);
TEST_ASSERT_EQUAL_STRING("", lv_dropdown_get_options(dd1));
TEST_ASSERT_EQUAL(0, lv_dropdown_get_option_cnt(dd1));
lv_obj_del(dd1);
lv_mem_monitor_t m2;
lv_mem_monitor(&m2);
TEST_ASSERT_UINT32_WITHIN(48, m1.free_size, m2.free_size);
}
void test_dropdown_select(void)
{
lv_obj_t * dd1 = lv_dropdown_create(lv_scr_act());
lv_dropdown_set_selected(dd1, 2);
TEST_ASSERT_EQUAL(2, lv_dropdown_get_selected(dd1));
char buf[32];
memset(buf, 0x00, sizeof(buf));
lv_dropdown_get_selected_str(dd1, buf, sizeof(buf));
TEST_ASSERT_EQUAL_STRING("Option 3", buf);
memset(buf, 0x00, sizeof(buf));
lv_dropdown_get_selected_str(dd1, buf, 4);
TEST_ASSERT_EQUAL_STRING("Opt", buf);
/*Out of range*/
lv_dropdown_set_selected(dd1, 3);
TEST_ASSERT_EQUAL(2, lv_dropdown_get_selected(dd1));
}
void test_dropdown_click(void)
{
lv_obj_clean(lv_scr_act());
lv_obj_t * dd1 = lv_dropdown_create(lv_scr_act());
lv_obj_update_layout(dd1);
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
lv_test_mouse_click_at(dd1->coords.x1 + 5, dd1->coords.y1 + 5);
TEST_ASSERT_NOT_NULL(lv_dropdown_get_list(dd1));
lv_obj_t * list = lv_dropdown_get_list(dd1);
TEST_ASSERT_EQUAL(0, lv_dropdown_get_selected(dd1));
lv_test_mouse_click_at(list->coords.x1 + 5, list->coords.y2 - 25);
TEST_ASSERT_EQUAL(2, lv_dropdown_get_selected(dd1));
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
}
static uint32_t event_cnt;
static void dd_event(lv_event_t * e)
{
LV_UNUSED(e);
event_cnt++;
}
void test_dropdown_keypad(void)
{
lv_obj_clean(lv_scr_act());
lv_group_t * g = lv_group_create();
lv_indev_set_group(lv_test_keypad_indev, g);
lv_obj_t * dd1 = lv_dropdown_create(lv_scr_act());
lv_obj_set_pos(dd1, 20, 20);
lv_dropdown_set_options(dd1, "1\n2\n3\n4\n5\n6\n7\n8");
lv_group_add_obj(g, dd1);
lv_obj_add_event_cb(dd1, dd_event, LV_EVENT_VALUE_CHANGED, NULL);
lv_obj_t * dd2 = lv_dropdown_create(lv_scr_act());
lv_obj_set_pos(dd2, 300, 20);
lv_group_add_obj(g, dd2);
event_cnt = 0;
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_NULL(lv_dropdown_get_list(dd2));
lv_test_key_hit(LV_KEY_ENTER);
TEST_ASSERT_NOT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_NULL(lv_dropdown_get_list(dd2));
lv_test_key_hit(LV_KEY_DOWN);
lv_test_key_hit(LV_KEY_RIGHT); /*Same as down*/
lv_test_key_hit(LV_KEY_ENTER);
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_EQUAL(2, lv_dropdown_get_selected(dd1));
TEST_ASSERT_EQUAL(1, event_cnt);
lv_test_key_hit(LV_KEY_DOWN); /*Open the list too*/
TEST_ASSERT_NOT_NULL(lv_dropdown_get_list(dd1));
lv_test_key_hit(LV_KEY_DOWN);
lv_test_key_hit(LV_KEY_ENTER);
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_EQUAL(3, lv_dropdown_get_selected(dd1));
TEST_ASSERT_EQUAL(2, event_cnt);
lv_test_key_hit(LV_KEY_RIGHT); /*Open the list too*/
TEST_ASSERT_NOT_NULL(lv_dropdown_get_list(dd1));
lv_test_key_hit(LV_KEY_RIGHT);
lv_test_key_hit(LV_KEY_ENTER);
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_EQUAL(4, lv_dropdown_get_selected(dd1));
TEST_ASSERT_EQUAL(3, event_cnt);
lv_test_key_hit(LV_KEY_LEFT); /*Open the list too*/
TEST_ASSERT_NOT_NULL(lv_dropdown_get_list(dd1));
lv_test_key_hit(LV_KEY_LEFT);
lv_test_key_hit(LV_KEY_ENTER);
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_EQUAL(3, lv_dropdown_get_selected(dd1));
TEST_ASSERT_EQUAL(4, event_cnt);
lv_test_key_hit(LV_KEY_UP); /*Open the list too*/
TEST_ASSERT_NOT_NULL(lv_dropdown_get_list(dd1));
lv_test_key_hit(LV_KEY_UP);
lv_test_key_hit(LV_KEY_ENTER);
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_EQUAL(2, lv_dropdown_get_selected(dd1));
TEST_ASSERT_EQUAL(5, event_cnt);
lv_test_key_hit(LV_KEY_UP);
lv_test_key_hit(LV_KEY_UP);
lv_test_key_hit(LV_KEY_UP);
lv_test_key_hit(LV_KEY_UP);
lv_test_key_hit(LV_KEY_ENTER);
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_EQUAL(0, lv_dropdown_get_selected(dd1));
TEST_ASSERT_EQUAL(6, event_cnt);
lv_test_key_hit(LV_KEY_DOWN);
lv_test_key_hit(LV_KEY_DOWN);
lv_test_key_hit(LV_KEY_DOWN);
lv_test_key_hit(LV_KEY_DOWN);
lv_test_key_hit(LV_KEY_DOWN);
lv_test_key_hit(LV_KEY_DOWN);
lv_test_key_hit(LV_KEY_DOWN);
lv_test_key_hit(LV_KEY_DOWN);
lv_test_key_hit(LV_KEY_DOWN);
lv_test_key_hit(LV_KEY_ENTER);
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_EQUAL(7, lv_dropdown_get_selected(dd1));
TEST_ASSERT_EQUAL(7, event_cnt);
lv_test_key_hit(LV_KEY_ENTER);
TEST_ASSERT_NOT_NULL(lv_dropdown_get_list(dd1));
lv_test_key_hit(LV_KEY_NEXT);
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_NULL(lv_dropdown_get_list(dd2));
lv_test_key_hit(LV_KEY_ENTER);
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_NOT_NULL(lv_dropdown_get_list(dd2));
lv_indev_set_group(lv_test_keypad_indev, NULL);
lv_group_del(g);
}
void test_dropdown_encoder(void)
{
lv_obj_clean(lv_scr_act());
lv_group_t * g = lv_group_create();
lv_indev_set_group(lv_test_encoder_indev, g);
lv_obj_t * dd1 = lv_dropdown_create(lv_scr_act());
lv_obj_set_pos(dd1, 20, 20);
lv_dropdown_set_options(dd1, "1\n2\n3\n4\n5\n6\n7\n8");
lv_group_add_obj(g, dd1);
lv_obj_add_event_cb(dd1, dd_event, LV_EVENT_VALUE_CHANGED, NULL);
lv_obj_t * dd2 = lv_dropdown_create(lv_scr_act());
lv_obj_set_pos(dd2, 300, 20);
lv_group_add_obj(g, dd2);
event_cnt = 0;
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_NULL(lv_dropdown_get_list(dd2));
lv_test_encoder_click();
TEST_ASSERT_NOT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_NULL(lv_dropdown_get_list(dd2));
lv_test_encoder_turn(5);
lv_test_encoder_click();
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_EQUAL(5, lv_dropdown_get_selected(dd1));
TEST_ASSERT_EQUAL(1, event_cnt);
lv_test_encoder_click();
lv_test_encoder_turn(-1);
lv_test_encoder_click();
TEST_ASSERT_EQUAL(4, lv_dropdown_get_selected(dd1));
TEST_ASSERT_EQUAL(2, event_cnt);
lv_test_encoder_click();
lv_test_encoder_turn(2);
lv_test_encoder_press();
lv_test_indev_wait(1000); //Long press
lv_test_encoder_release();
lv_test_indev_wait(50);
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_EQUAL(4, lv_dropdown_get_selected(dd1));
TEST_ASSERT_EQUAL(2, event_cnt);
lv_test_encoder_turn(1);
lv_test_encoder_click();
TEST_ASSERT_NULL(lv_dropdown_get_list(dd1));
TEST_ASSERT_NOT_NULL(lv_dropdown_get_list(dd2));
lv_indev_set_group(lv_test_encoder_indev, NULL);
lv_group_del(g);
}
void test_dropdown_render_1(void)
{
lv_obj_clean(lv_scr_act());
lv_obj_t * dd1 = lv_dropdown_create(lv_scr_act());
lv_obj_set_pos(dd1, 10, 10);
lv_dropdown_set_selected(dd1, 1);
lv_obj_t * dd2 = lv_dropdown_create(lv_scr_act());
lv_obj_set_pos(dd2, 200, 10);
lv_obj_set_width(dd2, 200);
lv_dropdown_set_selected(dd2, 2);
lv_dropdown_open(dd2);
TEST_ASSERT_TRUE(lv_dropdown_get_selected_highlight(dd2));
lv_dropdown_set_selected_highlight(dd2, false);
TEST_ASSERT_FALSE(lv_dropdown_get_selected_highlight(dd2));
lv_obj_t * dd3 = lv_dropdown_create(lv_scr_act());
lv_obj_set_style_pad_hor(dd3, 5, 0);
lv_obj_set_style_pad_ver(dd3, 20, 0);
lv_obj_set_pos(dd3, 500, 150);
TEST_ASSERT_EQUAL_PTR(NULL, lv_dropdown_get_text(dd3));
lv_dropdown_set_text(dd3, "A text");
TEST_ASSERT_EQUAL_STRING("A text", lv_dropdown_get_text(dd3));
lv_dropdown_set_selected(dd3, 2);
TEST_ASSERT_EQUAL(LV_DIR_BOTTOM, lv_dropdown_get_dir(dd3));
lv_dropdown_set_dir(dd3, LV_DIR_LEFT);
TEST_ASSERT_EQUAL(LV_DIR_LEFT, lv_dropdown_get_dir(dd3));
TEST_ASSERT_EQUAL_STRING(LV_SYMBOL_DOWN, lv_dropdown_get_symbol(dd3));
lv_dropdown_set_symbol(dd3, LV_SYMBOL_LEFT);
TEST_ASSERT_EQUAL_STRING(LV_SYMBOL_LEFT, lv_dropdown_get_symbol(dd3));
lv_dropdown_set_options(dd3, "a0\na1\na2\na3\na4\na5\na6\na7\na8\na9\na10\na11\na12\na13\na14\na15\na16");
lv_dropdown_open(dd3);
lv_dropdown_set_selected(dd3, 3);
lv_obj_t * list = lv_dropdown_get_list(dd3);
lv_obj_set_style_text_line_space(list, 5, 0);
lv_obj_set_style_bg_color(list, lv_color_hex3(0xf00), LV_PART_SELECTED | LV_STATE_CHECKED);
TEST_ASSERT_EQUAL_SCREENSHOT("dropdown_1.png");
}
void test_dropdown_render_2(void)
{
lv_obj_clean(lv_scr_act());
LV_IMG_DECLARE(img_caret_down);
lv_obj_t * dd1 = lv_dropdown_create(lv_scr_act());
lv_dropdown_set_text(dd1, "Short");
lv_dropdown_set_options(dd1, "1\n2");
lv_dropdown_set_symbol(dd1, &img_caret_down);
lv_dropdown_open(dd1);
lv_obj_t * dd2 = lv_dropdown_create(lv_scr_act());
lv_dropdown_set_text(dd2, "Go Up");
lv_dropdown_set_options(dd2, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15");
lv_dropdown_set_symbol(dd2, NULL);
lv_obj_align(dd2, LV_ALIGN_LEFT_MID, 150, 50);
lv_dropdown_open(dd2);
lv_obj_t * dd3 = lv_dropdown_create(lv_scr_act());
lv_dropdown_set_text(dd3, "Limit Down");
lv_dropdown_set_options(dd3, "1aaaaaaaaaaaaaaaa\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15");
lv_obj_align(dd3, LV_ALIGN_LEFT_MID, 300, -10);
lv_dropdown_open(dd3);
lv_obj_t * dd4 = lv_dropdown_create(lv_scr_act());
lv_dropdown_set_text(dd4, "Limit Top");
lv_dropdown_set_options(dd4, "1aaaaaaaaaaaaaaaa\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15");
lv_obj_align(dd4, LV_ALIGN_LEFT_MID, 450, 10);
lv_dropdown_set_dir(dd4, LV_DIR_TOP);
lv_dropdown_set_symbol(dd4, LV_SYMBOL_UP);
lv_dropdown_open(dd4);
lv_obj_t * dd5 = lv_dropdown_create(lv_scr_act());
lv_dropdown_set_text(dd5, "Go Down");
lv_dropdown_set_options(dd5, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15");
lv_dropdown_set_dir(dd5, LV_DIR_TOP);
lv_dropdown_set_symbol(dd5, LV_SYMBOL_UP);
lv_obj_align(dd5, LV_ALIGN_LEFT_MID, 650, -200);
lv_dropdown_open(dd5);
lv_obj_t * dd6 = lv_dropdown_create(lv_scr_act());
lv_dropdown_set_text(dd6, "Right");
lv_dropdown_set_options(dd6, "1aaa\n2aa\n3aa");
lv_dropdown_set_dir(dd6, LV_DIR_RIGHT);
lv_dropdown_set_symbol(dd6, LV_SYMBOL_RIGHT);
lv_obj_align(dd6, LV_ALIGN_BOTTOM_LEFT, 20, -20);
lv_dropdown_open(dd6);
lv_obj_set_style_text_align(lv_dropdown_get_list(dd6), LV_TEXT_ALIGN_RIGHT, 0);
lv_obj_t * dd7 = lv_dropdown_create(lv_scr_act());
lv_dropdown_set_text(dd7, "Left");
lv_dropdown_set_options(dd7, "1aaa\n2\n3");
lv_dropdown_set_dir(dd7, LV_DIR_LEFT);
lv_dropdown_set_symbol(dd7, LV_SYMBOL_LEFT);
lv_obj_align(dd7, LV_ALIGN_BOTTOM_RIGHT, -20, -20);
lv_dropdown_open(dd7);
TEST_ASSERT_EQUAL_SCREENSHOT("dropdown_2.png");
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/test_cases/test_dropdown.c | C | apache-2.0 | 14,575 |
/**
* @file test_font_loader.c
*
*/
/*********************
* INCLUDES
*********************/
#if LV_BUILD_TEST
#include "../../lvgl.h"
#include "unity/unity.h"
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static int compare_fonts(lv_font_t * f1, lv_font_t * f2);
void test_font_loader(void);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
extern lv_font_t font_1;
extern lv_font_t font_2;
extern lv_font_t font_3;
void test_font_loader(void)
{
lv_font_t * font_1_bin = lv_font_load("F:src/test_fonts/font_1.fnt");
lv_font_t * font_2_bin = lv_font_load("F:src/test_fonts/font_2.fnt");
lv_font_t * font_3_bin = lv_font_load("F:src/test_fonts/font_3.fnt");
compare_fonts(&font_1, font_1_bin);
compare_fonts(&font_2, font_2_bin);
compare_fonts(&font_3, font_3_bin);
lv_font_free(font_1_bin);
lv_font_free(font_2_bin);
lv_font_free(font_3_bin);
}
static int compare_fonts(lv_font_t * f1, lv_font_t * f2)
{
TEST_ASSERT_NOT_NULL_MESSAGE(f1, "font not null");
TEST_ASSERT_NOT_NULL_MESSAGE(f2, "font not null");
// Skip these test because -Wpedantic tells
// ISO C forbids passing argument 1 of ‘lv_test_assert_ptr_eq’ between function pointer and ‘void *’
// TEST_ASSERT_EQUAL_PTR_MESSAGE(f1->get_glyph_dsc, f2->get_glyph_dsc, "glyph_dsc");
// TEST_ASSERT_EQUAL_PTR_MESSAGE(f1->get_glyph_bitmap, f2->get_glyph_bitmap, "glyph_bitmap");
TEST_ASSERT_EQUAL_INT_MESSAGE(f1->line_height, f2->line_height, "line_height");
TEST_ASSERT_EQUAL_INT_MESSAGE(f1->base_line, f2->base_line, "base_line");
TEST_ASSERT_EQUAL_INT_MESSAGE(f1->subpx, f2->subpx, "subpx");
lv_font_fmt_txt_dsc_t * dsc1 = (lv_font_fmt_txt_dsc_t *)f1->dsc;
lv_font_fmt_txt_dsc_t * dsc2 = (lv_font_fmt_txt_dsc_t *)f2->dsc;
TEST_ASSERT_EQUAL_INT_MESSAGE(dsc1->kern_scale, dsc2->kern_scale, "kern_scale");
TEST_ASSERT_EQUAL_INT_MESSAGE(dsc1->cmap_num, dsc2->cmap_num, "cmap_num");
TEST_ASSERT_EQUAL_INT_MESSAGE(dsc1->bpp, dsc2->bpp, "bpp");
TEST_ASSERT_EQUAL_INT_MESSAGE(dsc1->kern_classes, dsc2->kern_classes, "kern_classes");
TEST_ASSERT_EQUAL_INT_MESSAGE(dsc1->bitmap_format, dsc2->bitmap_format, "bitmap_format");
// cmaps
int total_glyphs = 0;
for(int i = 0; i < dsc1->cmap_num; ++i) {
lv_font_fmt_txt_cmap_t * cmaps1 = (lv_font_fmt_txt_cmap_t *)&dsc1->cmaps[i];
lv_font_fmt_txt_cmap_t * cmaps2 = (lv_font_fmt_txt_cmap_t *)&dsc2->cmaps[i];
TEST_ASSERT_EQUAL_INT_MESSAGE(cmaps1->range_start, cmaps2->range_start, "range_start");
TEST_ASSERT_EQUAL_INT_MESSAGE(cmaps1->range_length, cmaps2->range_length, "range_length");
TEST_ASSERT_EQUAL_INT_MESSAGE(cmaps1->glyph_id_start, cmaps2->glyph_id_start, "glyph_id_start");
TEST_ASSERT_EQUAL_INT_MESSAGE(cmaps1->type, cmaps2->type, "type");
TEST_ASSERT_EQUAL_INT_MESSAGE(cmaps1->list_length, cmaps2->list_length, "list_length");
if(cmaps1->unicode_list != NULL && cmaps2->unicode_list != NULL) {
TEST_ASSERT_TRUE_MESSAGE(cmaps1->unicode_list && cmaps2->unicode_list, "unicode_list");
TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(
(uint8_t *)cmaps1->unicode_list,
(uint8_t *)cmaps2->unicode_list,
sizeof(uint16_t) * cmaps1->list_length,
"unicode_list");
total_glyphs += cmaps1->list_length;
}
else {
total_glyphs += cmaps1->range_length;
TEST_ASSERT_EQUAL_PTR_MESSAGE(cmaps1->unicode_list, cmaps2->unicode_list, "unicode_list");
}
if(cmaps1->glyph_id_ofs_list != NULL && cmaps2->glyph_id_ofs_list != NULL) {
uint8_t * ids1 = (uint8_t *)cmaps1->glyph_id_ofs_list;
uint8_t * ids2 = (uint8_t *)cmaps2->glyph_id_ofs_list;
TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(ids1, ids2, cmaps1->list_length, "glyph_id_ofs_list");
}
else {
TEST_ASSERT_EQUAL_PTR_MESSAGE(cmaps1->glyph_id_ofs_list, cmaps2->glyph_id_ofs_list, "glyph_id_ofs_list");
}
}
// kern_dsc
if (dsc1->kern_classes == 1 && dsc2->kern_classes == 1) {
lv_font_fmt_txt_kern_classes_t * kern1 = (lv_font_fmt_txt_kern_classes_t *)dsc1->kern_dsc;
lv_font_fmt_txt_kern_classes_t * kern2 = (lv_font_fmt_txt_kern_classes_t *)dsc2->kern_dsc;
if (kern1 != NULL && kern2 != NULL) {
TEST_ASSERT_EQUAL_INT_MESSAGE(kern1->right_class_cnt, kern2->right_class_cnt, "right_class_cnt");
TEST_ASSERT_EQUAL_INT_MESSAGE(kern1->left_class_cnt, kern2->left_class_cnt, "left_class_cnt");
TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(
(uint8_t *)kern1->left_class_mapping,
(uint8_t *)kern2->left_class_mapping,
kern1->left_class_cnt,
"left_class_mapping");
TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(
(uint8_t *)kern1->right_class_mapping,
(uint8_t *)kern2->right_class_mapping,
kern1->right_class_cnt,
"right_class_mapping");
TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(
(uint8_t *)kern1->class_pair_values,
(uint8_t *)kern2->class_pair_values,
kern1->right_class_cnt * kern1->left_class_cnt,
"class_pair_values");
}
else {
TEST_ASSERT_EQUAL_PTR_MESSAGE(kern1, kern2, "kern");
}
}
else if (dsc1->kern_classes == 0 && dsc2->kern_classes == 0) {
lv_font_fmt_txt_kern_pair_t * kern1 = (lv_font_fmt_txt_kern_pair_t *)dsc1->kern_dsc;
lv_font_fmt_txt_kern_pair_t * kern2 = (lv_font_fmt_txt_kern_pair_t *)dsc2->kern_dsc;
if (kern1 != NULL && kern2 != NULL) {
TEST_ASSERT_EQUAL_INT_MESSAGE(kern1->glyph_ids_size, kern2->glyph_ids_size, "glyph_ids_size");
TEST_ASSERT_EQUAL_INT_MESSAGE(kern1->pair_cnt, kern2->pair_cnt, "pair_cnt");
int ids_size;
if (kern1->glyph_ids_size == 0) {
ids_size = sizeof(int8_t) * 2 * kern1->pair_cnt;
}
else {
ids_size = sizeof(int16_t) * 2 * kern1->pair_cnt;
}
TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(kern1->glyph_ids, kern2->glyph_ids, ids_size, "glyph_ids");
TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(
(uint8_t * ) kern1->values,
(uint8_t * ) kern2->values,
kern1->pair_cnt,
"glyph_values");
}
}
lv_font_fmt_txt_glyph_dsc_t * glyph_dsc1 = (lv_font_fmt_txt_glyph_dsc_t *)dsc1->glyph_dsc;
lv_font_fmt_txt_glyph_dsc_t * glyph_dsc2 = (lv_font_fmt_txt_glyph_dsc_t *)dsc2->glyph_dsc;
for(int i = 0; i < total_glyphs; ++i) {
if (i < total_glyphs - 1) {
int size1 = glyph_dsc1[i+1].bitmap_index - glyph_dsc1[i].bitmap_index;
if (size1 > 0) {
TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(
dsc1->glyph_bitmap + glyph_dsc1[i].bitmap_index,
dsc2->glyph_bitmap + glyph_dsc2[i].bitmap_index,
size1 - 1, "glyph_bitmap");
}
}
TEST_ASSERT_EQUAL_INT_MESSAGE(glyph_dsc1[i].adv_w, glyph_dsc2[i].adv_w, "adv_w");
TEST_ASSERT_EQUAL_INT_MESSAGE(glyph_dsc1[i].box_w, glyph_dsc2[i].box_w, "box_w");
TEST_ASSERT_EQUAL_INT_MESSAGE(glyph_dsc1[i].box_h, glyph_dsc2[i].box_h, "box_h");
TEST_ASSERT_EQUAL_INT_MESSAGE(glyph_dsc1[i].ofs_x, glyph_dsc2[i].ofs_x, "ofs_x");
TEST_ASSERT_EQUAL_INT_MESSAGE(glyph_dsc1[i].ofs_y, glyph_dsc2[i].ofs_y, "ofs_y");
}
LV_LOG_INFO("No differences found!");
return 0;
}
/**********************
* STATIC FUNCTIONS
**********************/
#endif // LV_BUILD_TEST
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/test_cases/test_font_loader.c | C | apache-2.0 | 8,196 |
#if LV_BUILD_TEST
#include "../lvgl.h"
#include "unity/unity.h"
void test_obj_tree_1(void);
void test_obj_tree_2(void);
void test_obj_tree_1(void)
{
TEST_ASSERT_EQUAL(lv_obj_get_child_cnt(lv_scr_act()), 0);
}
void test_obj_tree_2(void)
{
lv_obj_create(lv_scr_act());
lv_obj_t * o2 = lv_obj_create(lv_scr_act());
lv_obj_create(lv_scr_act());
TEST_ASSERT_EQUAL(lv_obj_get_child_cnt(lv_scr_act()), 3);
lv_obj_del(o2);
TEST_ASSERT_EQUAL(lv_obj_get_child_cnt(lv_scr_act()), 2);
lv_obj_clean(lv_scr_act());
TEST_ASSERT_EQUAL(lv_obj_get_child_cnt(lv_scr_act()), 0);
lv_color_t c1 = lv_color_hex(0x444444);
lv_color_t c2 = lv_color_hex3(0x444);
TEST_ASSERT_EQUAL_COLOR(c1, c2);
lv_obj_remove_style_all(lv_scr_act());
lv_obj_set_style_bg_color(lv_scr_act(), lv_color_hex(0x112233), 0);
lv_obj_set_style_bg_opa(lv_scr_act(), LV_OPA_COVER, 0);
//TEST_ASSERT_EQUAL_SCREENSHOT("scr1.png")
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/test_cases/test_obj_tree.c | C | apache-2.0 | 929 |
#if LV_BUILD_TEST
#include "../lvgl.h"
#include "unity/unity.h"
//void test_func_1(void);
//void test_func_1(void)
//{
// TEST_ASSERT_EQUAL(actual, expected);
//}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/test_cases/test_style.c | C | apache-2.0 | 175 |
#if LV_BUILD_TEST
#include "../lvgl.h"
#include "unity/unity.h"
static const char color_cmd = LV_TXT_COLOR_CMD[0];
void test_txt_should_identify_valid_start_of_command(void)
{
uint32_t character = color_cmd;
lv_text_cmd_state_t state = LV_TEXT_CMD_STATE_WAIT;
bool is_cmd = _lv_txt_is_cmd(&state, character);
TEST_ASSERT_TRUE(is_cmd);
TEST_ASSERT_EQUAL_UINT8(state, LV_TEXT_CMD_STATE_PAR);
}
void test_txt_should_identify_invalid_start_of_command(void)
{
uint32_t character = '$';
lv_text_cmd_state_t state = LV_TEXT_CMD_STATE_WAIT;
bool is_cmd = _lv_txt_is_cmd(&state, character);
TEST_ASSERT_FALSE(is_cmd);
TEST_ASSERT_EQUAL_UINT8(state, LV_TEXT_CMD_STATE_WAIT);
}
void test_txt_should_identify_scaped_command_in_parameter(void)
{
uint32_t character = color_cmd;
lv_text_cmd_state_t state = LV_TEXT_CMD_STATE_PAR;
bool is_cmd = _lv_txt_is_cmd(&state, character);
TEST_ASSERT_FALSE(is_cmd);
TEST_ASSERT_EQUAL_UINT8(state, LV_TEXT_CMD_STATE_WAIT);
}
void test_txt_should_skip_color_parameter_in_parameter(void)
{
uint32_t character = '$';
lv_text_cmd_state_t state = LV_TEXT_CMD_STATE_PAR;
bool is_cmd = _lv_txt_is_cmd(&state, character);
TEST_ASSERT_TRUE(is_cmd);
TEST_ASSERT_EQUAL_UINT8(state, LV_TEXT_CMD_STATE_PAR);
}
void test_txt_should_reset_state_when_receiving_color_cmd_while_processing_commands(void)
{
uint32_t character = color_cmd;
lv_text_cmd_state_t state = LV_TEXT_CMD_STATE_IN;
bool is_cmd = _lv_txt_is_cmd(&state, character);
TEST_ASSERT_TRUE(is_cmd);
TEST_ASSERT_EQUAL_UINT8(state, LV_TEXT_CMD_STATE_WAIT);
}
void test_txt_should_identify_space_after_parameter(void)
{
uint32_t character = ' ';
lv_text_cmd_state_t state = LV_TEXT_CMD_STATE_PAR;
bool is_cmd = _lv_txt_is_cmd(&state, character);
TEST_ASSERT_TRUE(is_cmd);
TEST_ASSERT_EQUAL_UINT8(state, LV_TEXT_CMD_STATE_IN);
}
void test_txt_should_insert_string_into_another(void)
{
const char *msg = "Hello ";
const char *suffix = "World";
char target[20] = {0};
size_t msg_len = strlen(msg);
strcpy(target, msg);
_lv_txt_ins(target, msg_len, suffix);
TEST_ASSERT_EQUAL_STRING("Hello World", target);
}
void test_txt_should_handle_null_pointers_when_inserting(void)
{
const char *msg = "Hello ";
char target[20] = {0};
size_t msg_len = strlen(msg);
strcpy(target, msg);
_lv_txt_ins(target, msg_len, NULL);
TEST_ASSERT_EQUAL_STRING("Hello ", target);
}
void test_txt_cut_should_handle_null_pointer_to_txt(void)
{
_lv_txt_cut(NULL, 0, 6);
}
void test_txt_cut_happy_path(void)
{
char msg[] = "Hello World";
_lv_txt_cut(msg, 0, 6);
TEST_ASSERT_EQUAL_STRING("World", msg);
}
void test_txt_cut_should_handle_len_longer_than_string_length(void)
{
char msg[] = "Hello World";
_lv_txt_cut(msg, 0, 30);
TEST_ASSERT_EQUAL_UINT8(msg[0], 0x00);
}
void test_txt_get_encoded_next_should_decode_valid_ascii(void)
{
char msg[] = "Hello World!";
uint32_t result = 0;
result = _lv_txt_encoded_next(msg, NULL);
TEST_ASSERT_EQUAL_UINT32((uint32_t) 'H', result);
}
void test_txt_get_encoded_next_detect_valid_2_byte_input(void)
{
char msg[] = "\xc3\xb1";
uint32_t result = 0;
result = _lv_txt_encoded_next(msg, NULL);
TEST_ASSERT_EQUAL_UINT32(241, result);
}
void test_txt_get_encoded_next_detect_invalid_2_byte_input(void)
{
char msg[] = "\xc3\x28";
uint32_t result = 0;
result = _lv_txt_encoded_next(msg, NULL);
TEST_ASSERT_EQUAL_UINT32(0, result);
}
void test_txt_get_encoded_next_detect_valid_3_byte_input(void)
{
char msg[] = "\xe2\x82\xa1";
uint32_t result = 0;
result = _lv_txt_encoded_next(msg, NULL);
TEST_ASSERT_EQUAL_UINT32(8353, result);
}
void test_txt_get_encoded_next_detect_invalid_3_byte_input(void)
{
char msg[] = "\xe2\x28\xa1";
uint32_t result = 0;
result = _lv_txt_encoded_next(msg, NULL);
TEST_ASSERT_EQUAL_UINT32(0, result);
}
void test_txt_get_encoded_next_detect_valid_4_byte_input(void)
{
char msg[] = "\xf0\x90\x8c\xbc";
uint32_t result = 0;
result = _lv_txt_encoded_next(msg, NULL);
TEST_ASSERT_EQUAL_UINT32(66364, result);
}
void test_txt_get_encoded_next_detect_invalid_4_byte_input(void)
{
char msg[] = "\xf0\x28\x8c\x28";
uint32_t result = 0;
result = _lv_txt_encoded_next(msg, NULL);
TEST_ASSERT_EQUAL_UINT32(0, result);
}
/* See #2615 for more information */
void test_txt_next_line_should_handle_empty_string(void)
{
const lv_font_t *font_ptr = NULL;
lv_coord_t letter_space = 0;
lv_coord_t max_width = 0;
lv_text_flag_t flag = LV_TEXT_FLAG_NONE;
uint32_t next_line = _lv_txt_get_next_line("", font_ptr, letter_space, max_width, flag);
TEST_ASSERT_EQUAL_UINT32(0, next_line);
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/test_cases/test_txt.c | C | apache-2.0 | 4,865 |
#if LV_BUILD_TEST
#include "../../lvgl.h"
/*******************************************************************************
* Size: 8 px
* Bpp: 4
* Opts: --bpp 4 --size 8 --font ../Montserrat-Medium.ttf -r 0x20-0x7F,0xB0,0x2022 --font ../FontAwesome5-Solid+Brands+Regular.woff -r 61441,61448,61451,61452,61452,61453,61457,61459,61461,61465,61468,61473,61478,61479,61480,61502,61512,61515,61516,61517,61521,61522,61523,61524,61543,61544,61550,61552,61553,61556,61559,61560,61561,61563,61587,61589,61636,61637,61639,61671,61674,61683,61724,61732,61787,61931,62016,62017,62018,62019,62020,62087,62099,62212,62189,62810,63426,63650 --format lvgl -o ..\generated_fonts/font_1.c
******************************************************************************/
#ifndef FONT_1
#define FONT_1 1
#endif
#if FONT_1
/*-----------------
* BITMAPS
*----------------*/
/*Store the image of the glyphs*/
static LV_ATTRIBUTE_LARGE_CONST const uint8_t gylph_bitmap[] = {
/* U+20 " " */
/* U+21 "!" */
0x58, 0xf, 0x11, 0x32, 0xb2, 0x80,
/* U+22 "\"" */
0x73, 0x90, 0x10, 0x72, 0x90,
/* U+23 "#" */
0x4, 0x52, 0x60, 0x4f, 0xc9, 0xc3, 0x43, 0x9c,
0x83, 0x64, 0x8b, 0xa1, 0x65, 0x85, 0x81,
/* U+24 "$" */
0x0, 0x40, 0x0, 0xad, 0x68, 0x97, 0x56, 0x89,
0xf9, 0x60, 0x42, 0x17, 0x21, 0x69, 0x7e, 0x96,
0x96, 0xcc,
/* U+25 "%" */
0x58, 0x70, 0x63, 0xd, 0x8f, 0x30, 0x30, 0xa7,
0xdb, 0x7, 0x12, 0x7d, 0xa1, 0x57, 0x6, 0xa2,
0xfa, 0x40,
/* U+26 "&" */
0x9, 0x98, 0x2, 0x2a, 0x30, 0x0, 0x97, 0xc1,
0x4, 0xd6, 0xc4, 0x2, 0xe6, 0xc, 0xc4, 0x75,
0x33, 0x10,
/* U+27 "'" */
0x72, 0x0, 0x39, 0x0,
/* U+28 "(" */
0x8, 0x20, 0x32, 0x11, 0x1, 0x10, 0x8, 0x80,
0x22, 0x0, 0x19, 0x0,
/* U+29 ")" */
0x73, 0x6a, 0x12, 0x7, 0x7, 0x12, 0x6a,
/* U+2A "*" */
0x48, 0x40, 0x26, 0xc0, 0x7b, 0x90,
/* U+2B "+" */
0x0, 0x10, 0x6, 0x80, 0x2, 0x4b, 0xc8, 0xa4,
0xbc, 0x88,
/* U+2C "," */
0x0, 0x3a, 0x82, 0x0,
/* U+2D "-" */
0x5a, 0x60,
/* U+2E "." */
0x0, 0x3a, 0x0,
/* U+2F "/" */
0x0, 0xa8, 0x2, 0x22, 0x0, 0x55, 0x40, 0x8,
0x88, 0x0, 0x4c, 0x0, 0xb5, 0xc0, 0x2, 0x2,
0x0,
/* U+30 "0" */
0xa, 0xbb, 0x13, 0x65, 0xd4, 0xfa, 0x80, 0xbf,
0xa8, 0xb, 0xb6, 0x5d, 0x48,
/* U+31 "1" */
0x9e, 0x29, 0x40, 0xf, 0xf0,
/* U+32 "2" */
0x6a, 0xb9, 0x6, 0xab, 0x50, 0x9, 0x50, 0x1,
0x5, 0x1, 0x2d, 0xb4, 0x60,
/* U+33 "3" */
0x7a, 0xbe, 0x7, 0xa1, 0xc0, 0x2, 0x5, 0x80,
0x12, 0x8c, 0xa2, 0xa8, 0x64,
/* U+34 "4" */
0x0, 0x24, 0x80, 0x47, 0xd2, 0x0, 0x18, 0xa8,
0x20, 0x90, 0xa5, 0x92, 0x8b, 0xa4, 0x82,
/* U+35 "5" */
0x3d, 0xaa, 0x3, 0x5d, 0x50, 0x1, 0xb5, 0x0,
0xb7, 0x42, 0x6f, 0x54, 0x33, 0x0,
/* U+36 "6" */
0x9, 0xaa, 0x1b, 0x75, 0x50, 0xff, 0xd3, 0x45,
0xe1, 0x31, 0x6, 0x19, 0x8e,
/* U+37 "7" */
0xca, 0xa6, 0xb5, 0xd5, 0x5, 0x9c, 0x1a, 0xc0,
0x2a, 0x70, 0x3, 0x58, 0x0,
/* U+38 "8" */
0x1a, 0xa5, 0x92, 0x65, 0x7d, 0x25, 0xd4, 0xdc,
0xca, 0xb2, 0x2f, 0xa6, 0xfc,
/* U+39 "9" */
0x4a, 0x99, 0x7, 0xdc, 0x82, 0xc5, 0xc8, 0x69,
0xd4, 0x86, 0x9d, 0x58, 0xa8,
/* U+3A ":" */
0x74, 0x74, 0x0, 0x3a, 0x0,
/* U+3B ";" */
0x74, 0x74, 0x0, 0x3a, 0x8b, 0xb1, 0x0,
/* U+3C "<" */
0x0, 0x84, 0x0, 0x93, 0x20, 0x58, 0xa8, 0x5,
0xd5, 0x91, 0x1, 0x69, 0x10,
/* U+3D "=" */
0x49, 0x98, 0x52, 0x66, 0x14, 0x99, 0x84,
/* U+3E ">" */
0x10, 0xc, 0x53, 0x4, 0x7, 0x3d, 0xe2, 0x92,
0x5a, 0x29, 0x28, 0x0,
/* U+3F "?" */
0x6a, 0xb9, 0x6, 0xab, 0x50, 0xa, 0xa0, 0x2,
0x94, 0x0, 0x15, 0x80, 0x0,
/* U+40 "@" */
0x3, 0x87, 0x74, 0x28, 0x15, 0xe6, 0xf2, 0x12,
0xd4, 0x7d, 0x4b, 0x2e, 0x80, 0x7e, 0xa8, 0xf9,
0x91, 0xc7, 0x15, 0xe0, 0xf6, 0x53, 0x0,
/* U+41 "A" */
0x0, 0xae, 0x40, 0x31, 0x9c, 0x20, 0x14, 0x4c,
0xa0, 0x0, 0x8d, 0x14, 0x82, 0x1f, 0x93, 0x2e,
0x80,
/* U+42 "B" */
0x2d, 0x99, 0x58, 0x83, 0xcc, 0x8d, 0x41, 0xe6,
0x95, 0x40, 0xf3, 0x5d, 0x0, 0xf3, 0x28, 0xd0,
/* U+43 "C" */
0x7, 0xba, 0xa1, 0x2f, 0x5d, 0x50, 0xb2, 0x80,
0x36, 0x50, 0x6, 0x5e, 0xba, 0xa1, 0x0,
/* U+44 "D" */
0x2e, 0xab, 0xb1, 0x80, 0x12, 0xae, 0xbc, 0x3,
0x85, 0x48, 0x3, 0xa, 0x90, 0x25, 0x5d, 0x78,
0x0,
/* U+45 "E" */
0x2e, 0xaa, 0x40, 0x25, 0x52, 0x1, 0xea, 0x88,
0xf, 0x54, 0x40, 0x4a, 0xa4, 0x80,
/* U+46 "F" */
0x2e, 0xaa, 0x40, 0x25, 0x52, 0x1, 0x2a, 0x88,
0x9, 0x54, 0x40, 0xe,
/* U+47 "G" */
0x7, 0xba, 0xa1, 0x2f, 0x5d, 0x50, 0xb2, 0x80,
0x4, 0x79, 0x40, 0x6, 0x45, 0xeb, 0xae, 0x40,
/* U+48 "H" */
0x2a, 0x0, 0x15, 0x0, 0x7c, 0x95, 0x49, 0x0,
0x25, 0x52, 0x40, 0x3e,
/* U+49 "I" */
0x2a, 0x0, 0xfc,
/* U+4A "J" */
0x5, 0xad, 0x50, 0x5a, 0xa0, 0x7, 0xf7, 0x88,
0x4d, 0x1a, 0x0,
/* U+4B "K" */
0x2a, 0x1, 0xa2, 0x0, 0xd, 0x41, 0x3, 0x6e,
0x10, 0x0, 0x77, 0x94, 0x0, 0xe3, 0x3e, 0x80,
/* U+4C "L" */
0x2a, 0x0, 0xff, 0xe3, 0xa5, 0x51, 0xc0,
/* U+4D "M" */
0x2c, 0x0, 0x8f, 0x0, 0x5c, 0x1, 0x0, 0x4,
0xe2, 0x8f, 0x0, 0xa2, 0x45, 0x0, 0x21, 0x89,
0x0, 0x0,
/* U+4E "N" */
0x2d, 0x10, 0x2a, 0x1, 0xa0, 0xc, 0xdf, 0x60,
0x19, 0x3b, 0x80, 0x19, 0x6c, 0x0,
/* U+4F "O" */
0x7, 0xbb, 0x8c, 0x17, 0xae, 0xd5, 0xe3, 0x94,
0x0, 0x14, 0x5c, 0xa0, 0x0, 0xa2, 0xab, 0xae,
0xd5, 0xe2,
/* U+50 "P" */
0x2e, 0xaa, 0x48, 0x1, 0x2a, 0x82, 0x80, 0x18,
0x9c, 0x12, 0xa9, 0x86, 0x9, 0x54, 0x60,
/* U+51 "Q" */
0x7, 0xbb, 0x8c, 0x17, 0xae, 0xd5, 0xe3, 0x94,
0x0, 0x14, 0x5c, 0xa0, 0x9, 0x15, 0x5d, 0x77,
0x78, 0x83, 0xdc, 0x15, 0x18,
/* U+52 "R" */
0x2e, 0xaa, 0x48, 0x1, 0x2a, 0x82, 0x80, 0x18,
0x9c, 0x1e, 0xb0, 0x8c, 0x1e, 0xb4, 0x84,
/* U+53 "S" */
0x2a, 0xa8, 0x97, 0x2a, 0x84, 0xfd, 0x30, 0x21,
0x13, 0x90, 0xb5, 0x4e, 0xa0,
/* U+54 "T" */
0xaa, 0x75, 0x35, 0x50, 0xa9, 0x80, 0x3f, 0xf8,
0x60,
/* U+55 "U" */
0x39, 0x0, 0x24, 0x0, 0x7f, 0xf0, 0x9, 0x40,
0x5, 0xc3, 0x57, 0x58, 0xc0,
/* U+56 "V" */
0xb, 0x10, 0x2, 0xb8, 0x7c, 0x0, 0x39, 0xc1,
0x14, 0x57, 0x0, 0x28, 0x84, 0xb8, 0x4, 0x8b,
0x60, 0x0,
/* U+57 "W" */
0x94, 0x0, 0x78, 0x81, 0xcd, 0x70, 0x33, 0x41,
0x54, 0x36, 0xd, 0x9c, 0x2, 0x30, 0xb9, 0x30,
0x39, 0xc0, 0x3, 0x32, 0x82, 0x99, 0x80,
/* U+58 "X" */
0x58, 0x2, 0xa0, 0x50, 0x79, 0xb0, 0x4, 0x43,
0x84, 0x1, 0x57, 0xc2, 0xf, 0x89, 0x34, 0x0,
/* U+59 "Y" */
0xa, 0x20, 0x5, 0x80, 0x2e, 0x42, 0x60, 0x0,
0x3d, 0x62, 0x60, 0x12, 0xb4, 0x0, 0x70, 0x80,
0x40,
/* U+5A "Z" */
0x6a, 0xa6, 0x68, 0x35, 0x5b, 0xe0, 0x5, 0x52,
0x20, 0xb, 0x82, 0x0, 0x43, 0x4d, 0x50, 0x0,
/* U+5B "[" */
0x2d, 0x40, 0x44, 0x0, 0x7f, 0xf0, 0x51, 0x0,
/* U+5C "\\" */
0x19, 0x0, 0x84, 0xc0, 0x37, 0xa8, 0x4, 0xbe,
0x1, 0x8c, 0x40, 0x2a, 0x60, 0x8, 0xf4, 0x0,
/* U+5D "]" */
0x8c, 0x80, 0xf, 0xe8, 0x0,
/* U+5E "^" */
0x3, 0xc0, 0xa, 0xa1, 0x40, 0xb9, 0x30, 0x0,
/* U+5F "_" */
0x77, 0xc0,
/* U+60 "`" */
0x6, 0x60,
/* U+61 "a" */
0x29, 0x94, 0x0, 0x42, 0xa1, 0x5b, 0x2, 0x2b,
0xf9, 0x10,
/* U+62 "b" */
0x48, 0x0, 0xff, 0x92, 0xad, 0x40, 0xd, 0x57,
0x20, 0x1f, 0x9a, 0xa9, 0x20,
/* U+63 "c" */
0x1a, 0xa8, 0x67, 0xaa, 0x82, 0x1, 0xd3, 0xd5,
0x41,
/* U+64 "d" */
0x0, 0xd6, 0x1, 0xc3, 0x55, 0x4, 0x75, 0x48,
0x6, 0x10, 0x8e, 0x9b, 0x0,
/* U+65 "e" */
0x19, 0x98, 0x60, 0x4, 0x4e, 0x39, 0x12, 0xd3,
0xf5, 0x41,
/* U+66 "f" */
0xa, 0xa0, 0x10, 0x50, 0x5b, 0xb8, 0x2d, 0x1c,
0x3, 0xf8,
/* U+67 "g" */
0x1a, 0x99, 0x5c, 0x74, 0xc3, 0x80, 0x46, 0x11,
0xd5, 0xe, 0x4, 0x61, 0x0,
/* U+68 "h" */
0x48, 0x0, 0xfe, 0x49, 0xb4, 0x5, 0x9a, 0xf0,
0x10, 0x17, 0x0, 0xe0,
/* U+69 "i" */
0x37, 0x37, 0x48, 0x0, 0xf0,
/* U+6A "j" */
0x3, 0x70, 0x37, 0x3, 0x80, 0xf, 0xe6, 0x8c,
/* U+6B "k" */
0x48, 0x0, 0xff, 0xa9, 0x0, 0x72, 0x50, 0x12,
0xa4, 0x0, 0xad, 0xae,
/* U+6C "l" */
0x48, 0x0, 0xff, 0x0,
/* U+6D "m" */
0x4c, 0x9b, 0x89, 0xb4, 0x5, 0x98, 0x39, 0xbf,
0x1, 0x1, 0x10, 0x1, 0xc0, 0x3f, 0x0,
/* U+6E "n" */
0x4c, 0x9b, 0x40, 0x59, 0xaf, 0x1, 0x1, 0x70,
0xe,
/* U+6F "o" */
0x1a, 0xa8, 0x67, 0xaa, 0x6c, 0x3, 0xa7, 0xaa,
0x6c,
/* U+70 "p" */
0x4c, 0xab, 0x50, 0x3, 0x55, 0xc8, 0x7, 0xe6,
0xaa, 0x48, 0x1, 0x2a, 0x8a, 0x0,
/* U+71 "q" */
0x1a, 0xa4, 0xdc, 0x75, 0x50, 0x3, 0xd1, 0xd5,
0x40, 0x1a, 0xa4, 0x80,
/* U+72 "r" */
0x4b, 0xa0, 0x0, 0xd0, 0x0, 0x80, 0x3c,
/* U+73 "s" */
0x5b, 0x95, 0xdc, 0xa5, 0x84, 0x44, 0xbc, 0xef,
0x80,
/* U+74 "t" */
0x29, 0x0, 0x5a, 0x38, 0x5a, 0x38, 0x7, 0x11,
0x24, 0x0,
/* U+75 "u" */
0x57, 0x1, 0xb0, 0xe, 0x1f, 0x2, 0x4, 0x29,
0xa0,
/* U+76 "v" */
0xb, 0x0, 0x42, 0x7, 0x38, 0x1a, 0x2, 0xe3,
0xf0, 0x5, 0xb4, 0xa0,
/* U+77 "w" */
0xb0, 0x7, 0x10, 0x50, 0x72, 0xa9, 0xe8, 0x88,
0xb, 0xfe, 0x92, 0xaa, 0x0, 0xc, 0x83, 0xc,
0x80,
/* U+78 "x" */
0x67, 0x1b, 0x6, 0xea, 0xa0, 0x0, 0xc0, 0xc1,
0xfe, 0xa4, 0x0,
/* U+79 "y" */
0xb, 0x10, 0x83, 0x8, 0x91, 0x23, 0x3, 0x2b,
0x90, 0xb, 0x80, 0xc0, 0x15, 0xf0, 0x0,
/* U+7A "z" */
0x59, 0xbb, 0x2c, 0x5, 0x5, 0x48, 0xcb, 0xdc,
0x0,
/* U+7B "{" */
0xa, 0x60, 0x66, 0x0, 0x4a, 0xe0, 0xae, 0x1,
0xcc, 0xc0,
/* U+7C "|" */
0x28, 0x0, 0xff, 0xe0, 0x0,
/* U+7D "}" */
0x97, 0x9, 0xc0, 0xe, 0x63, 0x6, 0x30, 0xa,
0x70, 0x0,
/* U+7E "~" */
0x29, 0x35, 0x17, 0x95, 0xd1,
/* U+B0 "°" */
0x26, 0x45, 0x63, 0x57, 0x20,
/* U+2022 "•" */
0x0, 0x2e, 0xaf, 0x80,
/* U+F001 "" */
0x0, 0xff, 0xe0, 0x13, 0x5f, 0x0, 0x23, 0x75,
0x28, 0x20, 0x7, 0x21, 0x6a, 0x0, 0xd9, 0xd2,
0xa0, 0x18, 0xc0, 0x3f, 0xab, 0xc2, 0xbc, 0x3,
0x94, 0x0, 0xa0, 0xa, 0xfa,
/* U+F008 "" */
0xbd, 0xcc, 0xba, 0xac, 0xdb, 0x32, 0x9f, 0x34,
0x66, 0xdb, 0xe8, 0x1, 0xf9, 0x19, 0xb6, 0xfa,
0x1b, 0x66, 0x53, 0xe6,
/* U+F00B "" */
0x34, 0x14, 0x4c, 0x79, 0x6d, 0x77, 0xb1, 0x50,
0xd1, 0x32, 0x8b, 0x8b, 0xbe, 0x14, 0x32, 0x33,
0xc9, 0x30, 0xd0, 0xef, 0x4c, 0xa1, 0xa1, 0xde,
0x95, 0x43, 0x44, 0xca,
/* U+F00C "" */
0x0, 0xf4, 0xd0, 0x7, 0x4b, 0x5, 0x48, 0x2,
0x59, 0x68, 0x1a, 0x64, 0xcb, 0x41, 0x4a, 0xcc,
0x5a, 0x0, 0xa9, 0x99, 0x40, 0x10,
/* U+F00D "" */
0x63, 0x0, 0x41, 0x56, 0x25, 0x3b, 0x69, 0x5a,
0xca, 0xb, 0x80, 0x14, 0x29, 0x60, 0xb0, 0xc2,
0x5f, 0x10, 0x0,
/* U+F011 "" */
0x0, 0xb1, 0x44, 0x0, 0x3a, 0xe2, 0x7e, 0xe1,
0x20, 0xe0, 0xb, 0x81, 0x4a, 0x0, 0x94, 0x5c,
0x40, 0x16, 0x80, 0x12, 0x50, 0x31, 0x20, 0xa4,
0x1e, 0x3c, 0x5b, 0x90, 0xfa, 0xd2, 0x4c, 0x0,
/* U+F013 "" */
0x0, 0xb3, 0x0, 0x10, 0xc4, 0xc, 0xd1, 0x1,
0x97, 0x70, 0x89, 0xdd, 0x34, 0x3, 0xdc, 0x10,
0xa0, 0xf, 0xd4, 0x3, 0xdc, 0x10, 0xa9, 0x77,
0x8, 0x9d, 0xd2, 0x31, 0x3, 0x34, 0x40, 0x40,
/* U+F015 "" */
0x0, 0xc6, 0x4, 0x40, 0xd, 0x59, 0x51, 0x0,
0x0, 0xe8, 0x48, 0x28, 0x0, 0xfd, 0x46, 0x45,
0xd0, 0xe2, 0xa, 0x80, 0x8b, 0x10, 0xbe, 0x20,
0x40, 0x2e, 0xb0, 0x8, 0xec, 0xc0, 0x36, 0xa2,
0x1, 0x11, 0xa0,
/* U+F019 "" */
0x0, 0xbf, 0xc0, 0x1f, 0xfc, 0x87, 0xf0, 0x7,
0xb8, 0x1, 0xd8, 0x0, 0xce, 0xf, 0x1c, 0xaa,
0xe8, 0x78, 0x78, 0x11, 0x43, 0xc0, 0x4, 0x89,
0x80,
/* U+F01C "" */
0x5, 0xff, 0xe5, 0x1, 0xbc, 0xff, 0xb2, 0xc6,
0xd8, 0xc0, 0x23, 0x6b, 0x57, 0xf6, 0x6, 0xf7,
0x50, 0xa, 0x7e, 0x40, 0x22, 0x0, 0xf8, 0x80,
/* U+F021 "" */
0x0, 0xf8, 0xc0, 0xaf, 0xfd, 0x67, 0x85, 0x85,
0xdc, 0x3c, 0xb, 0x49, 0x17, 0x40, 0x5, 0x58,
0x1, 0x22, 0xec, 0xea, 0x84, 0x44, 0x57, 0xbb,
0x42, 0x0, 0x2a, 0x80, 0x2c, 0x6b, 0x6d, 0x1,
0x85, 0x32, 0x3c, 0x1c, 0x28, 0xcc, 0x40, 0x80,
/* U+F026 "" */
0x0, 0xa4, 0xd3, 0x1b, 0x2c, 0xc0, 0x39, 0x50,
0x1, 0x57, 0x60, 0x9, 0x38,
/* U+F027 "" */
0x0, 0xa4, 0x0, 0x69, 0x8c, 0x3, 0x96, 0x60,
0x34, 0x1, 0xe4, 0x40, 0x0, 0x6a, 0xee, 0x0,
0x8, 0x1, 0x38, 0x0,
/* U+F028 "" */
0x0, 0xf2, 0xa0, 0x6, 0x90, 0x26, 0xf3, 0x32,
0x63, 0x0, 0x3e, 0x21, 0x96, 0x60, 0x33, 0x25,
0x70, 0xf, 0xe5, 0x40, 0x0, 0xcc, 0x95, 0xaa,
0xec, 0x1, 0x7c, 0x48, 0x1, 0x38, 0x9, 0xbc,
0xc0,
/* U+F03E "" */
0xdf, 0xff, 0x69, 0x7c, 0x0, 0x62, 0x8, 0xb0,
0x4e, 0x40, 0x1, 0xca, 0x58, 0xd8, 0x2, 0xd6,
0xc0, 0x31, 0x7f, 0xf8, 0x80,
/* U+F048 "" */
0x40, 0x8, 0xac, 0x82, 0x34, 0x1, 0x2e, 0x0,
0xe6, 0x0, 0x8c, 0x3, 0x50, 0x80, 0x4f, 0x82,
0x8, 0x65, 0xec,
/* U+F04B "" */
0x0, 0xfb, 0x68, 0x40, 0x31, 0x2f, 0x38, 0x7,
0xa3, 0x50, 0x3, 0x8a, 0xe8, 0x3, 0xfe, 0x2b,
0xa0, 0xa, 0x35, 0x0, 0x97, 0x9c, 0x2, 0xda,
0x10, 0xc,
/* U+F04C "" */
0x9b, 0x90, 0x9b, 0x96, 0x46, 0x6, 0x46, 0x0,
0xff, 0xeb, 0xed, 0xe8, 0x6d, 0xe8,
/* U+F04D "" */
0x24, 0x4e, 0x2d, 0xbb, 0xed, 0x0, 0xff, 0xeb,
0xba, 0x27, 0x38,
/* U+F051 "" */
0x20, 0x9, 0x36, 0x0, 0xac, 0x1e, 0x40, 0x33,
0x70, 0x6, 0x30, 0x8, 0x68, 0x0, 0x58, 0xe0,
0xd8, 0x46, 0x80,
/* U+F052 "" */
0x0, 0xc4, 0x1, 0xf4, 0x6c, 0x0, 0x73, 0xb8,
0x1d, 0xc0, 0x12, 0xc0, 0x5, 0xa, 0x0, 0xb0,
0xe, 0xb0, 0x5, 0xbb, 0xf5, 0x80, 0x29, 0xdf,
0xa8, 0x0, 0xa8, 0x9c, 0xa0,
/* U+F053 "" */
0x0, 0x98, 0x80, 0xf, 0x2c, 0xf, 0x14, 0x8b,
0x12, 0xa0, 0x83, 0xa0, 0x1, 0xc5, 0xb0, 0x1,
0x62, 0xb0, 0x0, 0xbd, 0x80,
/* U+F054 "" */
0x26, 0x0, 0x9a, 0x5c, 0x0, 0x95, 0xe, 0x0,
0x59, 0x85, 0x0, 0x68, 0xa0, 0x5a, 0xe0, 0xb2,
0xe1, 0x3, 0x79, 0x0, 0x0,
/* U+F067 "" */
0x0, 0x90, 0x3, 0x8e, 0xcc, 0x3, 0x38, 0x38,
0x1, 0xe3, 0x83, 0xa1, 0xe5, 0xd4, 0x15, 0xe7,
0xbe, 0xc2, 0xff, 0x80, 0x3f, 0x95, 0x14, 0x0,
/* U+F068 "" */
0x78, 0x8e, 0x79, 0x77, 0xe9,
/* U+F06E "" */
0x0, 0x46, 0x65, 0x0, 0x1, 0xd5, 0xda, 0xf5,
0xd1, 0xd2, 0x84, 0x8e, 0x82, 0xd7, 0x0, 0x40,
0x80, 0x6a, 0x28, 0xe8, 0xe8, 0x2d, 0x1d, 0x5e,
0xbf, 0x5c, 0x10,
/* U+F070 "" */
0x1d, 0x30, 0xf, 0xc3, 0x1b, 0x19, 0x95, 0x10,
0x4, 0xb8, 0xaf, 0x10, 0x3d, 0x40, 0x3, 0xc6,
0xd, 0xda, 0x82, 0x84, 0x0, 0xb7, 0x52, 0x8,
0x2, 0x0, 0x75, 0x51, 0xb6, 0x48, 0x58, 0x80,
0x2a, 0x7f, 0x13, 0xd3, 0xc4, 0x2, 0x6c, 0xc3,
0x8d, 0x9c, 0x0,
/* U+F071 "" */
0x0, 0xc7, 0xc6, 0x1, 0xfb, 0xc7, 0xc0, 0x3e,
0x63, 0x39, 0x80, 0x3d, 0x5, 0x85, 0x0, 0x1d,
0x2, 0x60, 0x63, 0x0, 0x11, 0x38, 0xb, 0x8,
0x39, 0x0, 0x24, 0x0, 0x28, 0x20, 0x8, 0x0,
0x30, 0x0, 0x74, 0x40, 0xe, 0x0,
/* U+F074 "" */
0x0, 0xf1, 0x2, 0x20, 0x2, 0x4d, 0x5a, 0xbb,
0xe, 0x58, 0x47, 0x70, 0xf4, 0x78, 0xf0, 0x0,
0xa0, 0xa0, 0x17, 0x70, 0x74, 0xf8, 0xf2, 0xaf,
0x6, 0xec, 0x10, 0x88, 0x0, 0x93, 0x54,
/* U+F077 "" */
0x0, 0xfe, 0x4e, 0x40, 0x9, 0x2c, 0xad, 0x1,
0x2d, 0xf1, 0xed, 0x3d, 0xe0, 0x21, 0xfe, 0xe0,
0x2, 0x8b,
/* U+F078 "" */
0x0, 0xfa, 0xe0, 0x2, 0x8b, 0xf7, 0x80, 0x87,
0xf4, 0xb7, 0xc7, 0xb4, 0x4, 0xb2, 0xb4, 0x0,
0x93, 0x90, 0x0,
/* U+F079 "" */
0x0, 0x4a, 0xa, 0x26, 0x0, 0xad, 0xae, 0x7f,
0xeb, 0x10, 0x1, 0xa4, 0x75, 0xdc, 0x20, 0x14,
0x1, 0xb0, 0x0, 0x40, 0xc0, 0x31, 0xa2, 0x17,
0xc7, 0xd4, 0x1, 0x98, 0xff, 0x6d, 0x82, 0xa8,
0x0, 0xf7, 0x74, 0x2e, 0xc0, 0x0,
/* U+F07B "" */
0xdf, 0xf5, 0x80, 0x62, 0x0, 0x27, 0xfd, 0xa0,
0x1f, 0x10, 0x7, 0xff, 0x10, 0x80, 0x3c, 0x40,
/* U+F093 "" */
0x0, 0xa6, 0x40, 0x1d, 0x2c, 0xc9, 0x0, 0x9d,
0x80, 0xc, 0xe0, 0x7, 0xf0, 0x7, 0xb8, 0x7,
0xf3, 0xc2, 0x0, 0x12, 0x1e, 0x1e, 0x9d, 0xd4,
0xf0, 0x0, 0x17, 0x72, 0xa0, 0x0,
/* U+F095 "" */
0x0, 0xff, 0xe1, 0xbf, 0x50, 0x7, 0xa4, 0x50,
0x3, 0xc4, 0x4, 0x1, 0xe8, 0xb, 0x0, 0xe1,
0x91, 0x70, 0x7d, 0xc4, 0xc2, 0xd0, 0x4, 0x91,
0xd9, 0xe1, 0x80, 0x10, 0x4e, 0x38, 0xc0, 0x0,
/* U+F0C4 "" */
0x3, 0x0, 0xf6, 0x76, 0x1, 0x6e, 0x1, 0x51,
0x96, 0x1f, 0x5, 0x60, 0x68, 0x61, 0x2, 0x78,
0x1, 0x8, 0x1, 0x92, 0xc, 0xb2, 0x0, 0x2a,
0x19, 0x86, 0x90, 0xad, 0xa0, 0x7b, 0xc0,
/* U+F0C5 "" */
0x0, 0x7f, 0xce, 0x8e, 0x80, 0x11, 0x9a, 0x30,
0x2, 0xb8, 0x0, 0xff, 0xe5, 0x1c, 0x3b, 0xd0,
0x9, 0xe, 0xe8, 0x70,
/* U+F0C7 "" */
0x24, 0x4c, 0x21, 0xbf, 0xfc, 0x41, 0x77, 0x87,
0xc1, 0x13, 0x1, 0x5, 0xda, 0x2c, 0x3, 0x36,
0x30, 0x6, 0x45, 0x40, 0x3, 0xa3, 0x73, 0x23,
0x80,
/* U+F0E7 "" */
0x7, 0xff, 0x30, 0x5, 0xa0, 0x4, 0x0, 0x98,
0x1, 0x4e, 0x0, 0x20, 0x3, 0xe0, 0x2, 0x5c,
0x42, 0x40, 0xf, 0x2, 0xe4, 0x1, 0x18, 0xc0,
0x6, 0x5b, 0x0, 0x80,
/* U+F0EA "" */
0x79, 0xb9, 0x70, 0x4, 0x33, 0xb4, 0x0, 0x6a,
0x77, 0x18, 0x5, 0xce, 0xeb, 0xb0, 0x7, 0x8c,
0x3, 0x9d, 0xd0, 0xe0, 0x1c, 0xf1, 0xe0, 0x18,
/* U+F0F3 "" */
0x0, 0xb4, 0x3, 0x27, 0x17, 0x18, 0x2, 0x44,
0x7, 0x80, 0x4, 0x1, 0x10, 0x18, 0x7, 0x1c,
0x0, 0x74, 0x63, 0xbf, 0x6b, 0xc6, 0x3e, 0x43,
0x0,
/* U+F11C "" */
0xdf, 0xff, 0xb4, 0xb9, 0xdd, 0xce, 0xee, 0x20,
0xf2, 0x26, 0x91, 0x3c, 0x3, 0xfe, 0xf2, 0xac,
0xa2, 0xf0, 0x2e, 0x7f, 0xf9, 0xf8, 0x80,
/* U+F124 "" */
0x0, 0xff, 0xe2, 0x25, 0xe0, 0x7, 0x2e, 0x5a,
0x38, 0x4, 0xdd, 0x46, 0x0, 0xf0, 0x6, 0xc8,
0x80, 0x46, 0x80, 0xb, 0x77, 0x18, 0x2, 0x40,
0x26, 0x88, 0x20, 0xa, 0x80, 0x7e, 0x80, 0xf,
0xb4, 0x98, 0x3, 0xe5, 0xd0, 0xc,
/* U+F15B "" */
0xff, 0xa2, 0xc0, 0x39, 0x2c, 0x2, 0x47, 0x30,
0x8, 0xdd, 0xc0, 0x1f, 0xfc, 0xc0,
/* U+F1EB "" */
0x0, 0x91, 0xdc, 0x80, 0x1a, 0x7e, 0xef, 0x7c,
0x86, 0x25, 0xfe, 0x63, 0xed, 0x33, 0xb4, 0x2f,
0xfd, 0x61, 0xbc, 0x43, 0x63, 0x54, 0x1b, 0x12,
0x1, 0xfa, 0x74, 0xaf, 0x10, 0xe, 0xcf, 0x0,
0xfc, 0xd2, 0x1, 0x80,
/* U+F240 "" */
0x24, 0x4f, 0xc1, 0xbf, 0xff, 0x4d, 0x6, 0x2a,
0xfa, 0x14, 0x3c, 0x47, 0xce, 0x0, 0xd9, 0x9f,
0x42, 0x3f, 0x6e, 0xf8, 0x60,
/* U+F241 "" */
0x24, 0x4f, 0xc1, 0xbf, 0xff, 0x4d, 0x6, 0x2a,
0xec, 0xb8, 0x50, 0xf1, 0x1d, 0xe0, 0xe0, 0xd,
0x99, 0xda, 0x90, 0x8f, 0xdb, 0xbb, 0xbc, 0x60,
/* U+F242 "" */
0x24, 0x4f, 0xc1, 0xbf, 0xff, 0x4d, 0x6, 0x2a,
0xd7, 0x74, 0x28, 0x78, 0x8c, 0x1, 0x38, 0x3,
0x66, 0x64, 0x4a, 0x11, 0xfb, 0x76, 0xff, 0x86,
0x0,
/* U+F243 "" */
0x24, 0x4f, 0xc1, 0xbf, 0xff, 0x4d, 0x6, 0x2e,
0x5d, 0xe8, 0x50, 0xf1, 0xf0, 0xc, 0xe0, 0xd,
0x9d, 0x44, 0xd0, 0x8f, 0xdb, 0xdf, 0xf8, 0x60,
/* U+F244 "" */
0x24, 0x4f, 0xc1, 0xbf, 0xff, 0x4c, 0x5, 0xdf,
0xd0, 0xe0, 0x1f, 0x9c, 0x0, 0x89, 0xf4, 0x13,
0xff, 0xfc, 0x3c,
/* U+F287 "" */
0x0, 0xff, 0xe1, 0xbe, 0xc0, 0x7, 0xce, 0x97,
0x80, 0x1a, 0x6c, 0x78, 0x9d, 0x45, 0xc8, 0x1d,
0x24, 0x72, 0x66, 0xab, 0xc, 0xd8, 0x85, 0xe0,
0x7e, 0xc8, 0x11, 0x0, 0xc, 0x4d, 0x60, 0x1f,
0x9b, 0xb0, 0x2,
/* U+F293 "" */
0x6, 0xdd, 0x61, 0x82, 0x49, 0x71, 0x70, 0x69,
0xa3, 0x59, 0x14, 0x78, 0x9e, 0xc, 0x0, 0xf0,
0x10, 0x72, 0x31, 0x7f, 0x1, 0xd3, 0x65, 0x91,
0x24, 0x92, 0xd0, 0xd0,
/* U+F2ED "" */
0x78, 0xdf, 0xd8, 0x70, 0x2, 0xba, 0x80, 0x3d,
0xdf, 0xbc, 0xc, 0xce, 0x66, 0x0, 0xff, 0xe5,
0x69, 0x99, 0xcc, 0xda,
/* U+F304 "" */
0x0, 0xf3, 0xf1, 0x80, 0x72, 0x60, 0xe8, 0x6,
0x8b, 0x24, 0x90, 0xa, 0x1c, 0x1b, 0xdc, 0x1,
0xe, 0x0, 0x74, 0x0, 0x3b, 0x80, 0xf, 0x0,
0x14, 0x80, 0x1e, 0x0, 0x38, 0x62, 0x0, 0x1d,
0xdc, 0x70, 0xe,
/* U+F55A "" */
0x0, 0x57, 0xff, 0xb0, 0x2d, 0x41, 0x8c, 0xcc,
0x7, 0x48, 0x0, 0x5d, 0xd2, 0x80, 0x7f, 0xf0,
0x29, 0x0, 0xb, 0xba, 0x50, 0xa, 0xd4, 0x18,
0xcc, 0xc0, 0x60,
/* U+F7C2 "" */
0x7, 0xff, 0xb8, 0x5f, 0x27, 0x60, 0x89, 0xb,
0xb7, 0x84, 0x0, 0x14, 0x64, 0x10, 0xf, 0xfe,
0x51, 0x80, 0x61, 0x20,
/* U+F8A2 "" */
0x0, 0xf8, 0xc0, 0x4, 0x60, 0x11, 0x60, 0x16,
0x51, 0x14, 0xe0, 0xf, 0x16, 0xdd, 0xa8, 0x1,
0xe2, 0xdb, 0xbb, 0x80, 0xb2, 0x88, 0xb0, 0x80
};
/*---------------------
* GLYPH DESCRIPTION
*--------------------*/
static const lv_font_fmt_txt_glyph_dsc_t glyph_dsc[] = {
{.bitmap_index = 0, .adv_w = 0, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0} /* id = 0 reserved */,
{.bitmap_index = 0, .adv_w = 34, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 0, .adv_w = 34, .box_w = 2, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 6, .adv_w = 50, .box_w = 3, .box_h = 3, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 11, .adv_w = 90, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 26, .adv_w = 79, .box_w = 5, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 44, .adv_w = 108, .box_w = 7, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 62, .adv_w = 88, .box_w = 6, .box_h = 6, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 80, .adv_w = 27, .box_w = 2, .box_h = 3, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 84, .adv_w = 43, .box_w = 3, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 96, .adv_w = 43, .box_w = 2, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 103, .adv_w = 51, .box_w = 4, .box_h = 3, .ofs_x = 0, .ofs_y = 3},
{.bitmap_index = 109, .adv_w = 74, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 119, .adv_w = 29, .box_w = 2, .box_h = 3, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 123, .adv_w = 49, .box_w = 3, .box_h = 1, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 125, .adv_w = 29, .box_w = 2, .box_h = 2, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 128, .adv_w = 45, .box_w = 5, .box_h = 7, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 145, .adv_w = 85, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 158, .adv_w = 47, .box_w = 3, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 163, .adv_w = 73, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 176, .adv_w = 73, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 189, .adv_w = 86, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 204, .adv_w = 73, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 218, .adv_w = 79, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 231, .adv_w = 77, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 244, .adv_w = 82, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 257, .adv_w = 79, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 270, .adv_w = 29, .box_w = 2, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 275, .adv_w = 29, .box_w = 2, .box_h = 6, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 282, .adv_w = 74, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 295, .adv_w = 74, .box_w = 5, .box_h = 3, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 302, .adv_w = 74, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 314, .adv_w = 73, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 327, .adv_w = 132, .box_w = 8, .box_h = 6, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 350, .adv_w = 94, .box_w = 7, .box_h = 5, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 367, .adv_w = 97, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 383, .adv_w = 93, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 398, .adv_w = 106, .box_w = 7, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 415, .adv_w = 86, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 429, .adv_w = 81, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 441, .adv_w = 99, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 457, .adv_w = 104, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 469, .adv_w = 40, .box_w = 2, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 472, .adv_w = 66, .box_w = 5, .box_h = 5, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 483, .adv_w = 92, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 499, .adv_w = 76, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 506, .adv_w = 122, .box_w = 7, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 524, .adv_w = 104, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 538, .adv_w = 108, .box_w = 7, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 556, .adv_w = 92, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 571, .adv_w = 108, .box_w = 7, .box_h = 6, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 592, .adv_w = 93, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 607, .adv_w = 79, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 620, .adv_w = 75, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 629, .adv_w = 101, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 642, .adv_w = 91, .box_w = 7, .box_h = 5, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 660, .adv_w = 144, .box_w = 9, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 683, .adv_w = 86, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 699, .adv_w = 83, .box_w = 7, .box_h = 5, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 716, .adv_w = 84, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 732, .adv_w = 43, .box_w = 3, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 740, .adv_w = 45, .box_w = 5, .box_h = 7, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 756, .adv_w = 43, .box_w = 2, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 761, .adv_w = 75, .box_w = 5, .box_h = 3, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 769, .adv_w = 64, .box_w = 4, .box_h = 1, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 771, .adv_w = 77, .box_w = 3, .box_h = 1, .ofs_x = 0, .ofs_y = 5},
{.bitmap_index = 773, .adv_w = 77, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 783, .adv_w = 87, .box_w = 6, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 796, .adv_w = 73, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 805, .adv_w = 87, .box_w = 5, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 818, .adv_w = 78, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 828, .adv_w = 45, .box_w = 4, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 838, .adv_w = 88, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 851, .adv_w = 87, .box_w = 5, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 863, .adv_w = 36, .box_w = 2, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 868, .adv_w = 36, .box_w = 3, .box_h = 7, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 876, .adv_w = 79, .box_w = 5, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 888, .adv_w = 36, .box_w = 2, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 892, .adv_w = 135, .box_w = 8, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 907, .adv_w = 87, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 916, .adv_w = 81, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 925, .adv_w = 87, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 939, .adv_w = 87, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 951, .adv_w = 52, .box_w = 4, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 958, .adv_w = 64, .box_w = 4, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 967, .adv_w = 53, .box_w = 4, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 977, .adv_w = 87, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 986, .adv_w = 72, .box_w = 6, .box_h = 4, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 998, .adv_w = 115, .box_w = 8, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1015, .adv_w = 71, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1026, .adv_w = 72, .box_w = 6, .box_h = 5, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 1041, .adv_w = 67, .box_w = 4, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1050, .adv_w = 45, .box_w = 3, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1060, .adv_w = 38, .box_w = 2, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1065, .adv_w = 45, .box_w = 3, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1075, .adv_w = 74, .box_w = 5, .box_h = 2, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 1080, .adv_w = 54, .box_w = 3, .box_h = 3, .ofs_x = 0, .ofs_y = 3},
{.bitmap_index = 1085, .adv_w = 40, .box_w = 2, .box_h = 3, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 1089, .adv_w = 128, .box_w = 8, .box_h = 9, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1118, .adv_w = 128, .box_w = 8, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1138, .adv_w = 128, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1166, .adv_w = 128, .box_w = 8, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1188, .adv_w = 88, .box_w = 6, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1207, .adv_w = 128, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1239, .adv_w = 128, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1271, .adv_w = 144, .box_w = 9, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1306, .adv_w = 128, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1331, .adv_w = 144, .box_w = 9, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1355, .adv_w = 128, .box_w = 8, .box_h = 10, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 1395, .adv_w = 64, .box_w = 4, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1408, .adv_w = 96, .box_w = 6, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1428, .adv_w = 144, .box_w = 9, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1461, .adv_w = 128, .box_w = 8, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1482, .adv_w = 112, .box_w = 5, .box_h = 8, .ofs_x = 1, .ofs_y = -1},
{.bitmap_index = 1501, .adv_w = 112, .box_w = 7, .box_h = 10, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 1527, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1541, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1552, .adv_w = 112, .box_w = 5, .box_h = 8, .ofs_x = 1, .ofs_y = -1},
{.bitmap_index = 1571, .adv_w = 112, .box_w = 9, .box_h = 8, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 1600, .adv_w = 80, .box_w = 5, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1621, .adv_w = 80, .box_w = 5, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1642, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1666, .adv_w = 112, .box_w = 7, .box_h = 2, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 1671, .adv_w = 144, .box_w = 9, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1698, .adv_w = 160, .box_w = 11, .box_h = 8, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 1741, .adv_w = 144, .box_w = 11, .box_h = 8, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 1779, .adv_w = 128, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1810, .adv_w = 112, .box_w = 7, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1828, .adv_w = 112, .box_w = 7, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1847, .adv_w = 160, .box_w = 11, .box_h = 7, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 1885, .adv_w = 128, .box_w = 8, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1901, .adv_w = 128, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1931, .adv_w = 128, .box_w = 9, .box_h = 9, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 1963, .adv_w = 112, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1994, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2014, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2039, .adv_w = 80, .box_w = 7, .box_h = 8, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 2067, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2091, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2116, .adv_w = 144, .box_w = 9, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2139, .adv_w = 128, .box_w = 10, .box_h = 10, .ofs_x = -1, .ofs_y = -2},
{.bitmap_index = 2177, .adv_w = 96, .box_w = 6, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2191, .adv_w = 160, .box_w = 10, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2227, .adv_w = 160, .box_w = 10, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2248, .adv_w = 160, .box_w = 10, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2272, .adv_w = 160, .box_w = 10, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2297, .adv_w = 160, .box_w = 10, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2321, .adv_w = 160, .box_w = 10, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2340, .adv_w = 160, .box_w = 11, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2375, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2403, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2423, .adv_w = 128, .box_w = 9, .box_h = 9, .ofs_x = -1, .ofs_y = -2},
{.bitmap_index = 2458, .adv_w = 160, .box_w = 10, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2485, .adv_w = 96, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2505, .adv_w = 129, .box_w = 9, .box_h = 6, .ofs_x = 0, .ofs_y = 0}
};
/*---------------------
* CHARACTER MAPPING
*--------------------*/
static const uint16_t unicode_list_1[] = {
0x0, 0x1f72, 0xef51, 0xef58, 0xef5b, 0xef5c, 0xef5d, 0xef61,
0xef63, 0xef65, 0xef69, 0xef6c, 0xef71, 0xef76, 0xef77, 0xef78,
0xef8e, 0xef98, 0xef9b, 0xef9c, 0xef9d, 0xefa1, 0xefa2, 0xefa3,
0xefa4, 0xefb7, 0xefb8, 0xefbe, 0xefc0, 0xefc1, 0xefc4, 0xefc7,
0xefc8, 0xefc9, 0xefcb, 0xefe3, 0xefe5, 0xf014, 0xf015, 0xf017,
0xf037, 0xf03a, 0xf043, 0xf06c, 0xf074, 0xf0ab, 0xf13b, 0xf190,
0xf191, 0xf192, 0xf193, 0xf194, 0xf1d7, 0xf1e3, 0xf23d, 0xf254,
0xf4aa, 0xf712, 0xf7f2
};
/*Collect the unicode lists and glyph_id offsets*/
static const lv_font_fmt_txt_cmap_t cmaps[] =
{
{
.range_start = 32, .range_length = 95, .glyph_id_start = 1,
.unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
},
{
.range_start = 176, .range_length = 63475, .glyph_id_start = 96,
.unicode_list = unicode_list_1, .glyph_id_ofs_list = NULL, .list_length = 59, .type = LV_FONT_FMT_TXT_CMAP_SPARSE_TINY
}
};
/*-----------------
* KERNING
*----------------*/
/*Map glyph_ids to kern left classes*/
static const uint8_t kern_left_class_mapping[] =
{
0, 0, 1, 2, 0, 3, 4, 5,
2, 6, 7, 8, 9, 10, 9, 10,
11, 12, 0, 13, 14, 15, 16, 17,
18, 19, 12, 20, 20, 0, 0, 0,
21, 22, 23, 24, 25, 22, 26, 27,
28, 29, 29, 30, 31, 32, 29, 29,
22, 33, 34, 35, 3, 36, 30, 37,
37, 38, 39, 40, 41, 42, 43, 0,
44, 0, 45, 46, 47, 48, 49, 50,
51, 45, 52, 52, 53, 48, 45, 45,
46, 46, 54, 55, 56, 57, 51, 58,
58, 59, 58, 60, 41, 0, 0, 9,
61, 9, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0
};
/*Map glyph_ids to kern right classes*/
static const uint8_t kern_right_class_mapping[] =
{
0, 0, 1, 2, 0, 3, 4, 5,
2, 6, 7, 8, 9, 10, 9, 10,
11, 12, 13, 14, 15, 16, 17, 12,
18, 19, 20, 21, 21, 0, 0, 0,
22, 23, 24, 25, 23, 25, 25, 25,
23, 25, 25, 26, 25, 25, 25, 25,
23, 25, 23, 25, 3, 27, 28, 29,
29, 30, 31, 32, 33, 34, 35, 0,
36, 0, 37, 38, 39, 39, 39, 0,
39, 38, 40, 41, 38, 38, 42, 42,
39, 42, 39, 42, 43, 44, 45, 46,
46, 47, 46, 48, 0, 0, 35, 9,
49, 9, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0
};
/*Kern values between classes*/
static const int8_t kern_class_values[] =
{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6, 0, 3, -3, 0, 0,
0, 0, -7, -8, 1, 6, 3, 2,
-5, 1, 6, 0, 5, 1, 4, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 8, 1, -1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 3, 0, -4, 0, 0, 0, 0,
0, -3, 2, 3, 0, 0, -1, 0,
-1, 1, 0, -1, 0, -1, -1, -3,
0, 0, 0, 0, -1, 0, 0, -2,
-2, 0, 0, -1, 0, -3, 0, 0,
0, 0, 0, 0, 0, 0, 0, -1,
-1, 0, -2, 0, -3, 0, -15, 0,
0, -3, 0, 3, 4, 0, 0, -3,
1, 1, 4, 3, -2, 3, 0, 0,
-7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -5, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, -3, -2, -6, 0, -5,
-1, 0, 0, 0, 0, 0, 5, 0,
-4, -1, 0, 0, 0, -2, 0, 0,
-1, -9, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -10, -1, 5,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -5, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 4,
0, 1, 0, 0, -3, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 5, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-5, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1,
3, 1, 4, -1, 0, 0, 3, -1,
-4, -18, 1, 3, 3, 0, -2, 0,
5, 0, 4, 0, 4, 0, -12, 0,
-2, 4, 0, 4, -1, 3, 1, 0,
0, 0, -1, 0, 0, -2, 10, 0,
10, 0, 4, 0, 5, 2, 2, 4,
0, 0, 0, -5, 0, 0, 0, 0,
0, -1, 0, 1, -2, -2, -3, 1,
0, -1, 0, 0, 0, -5, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -8, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, -7, 0, -8, 0, 0, 0,
0, -1, 0, 13, -2, -2, 1, 1,
-1, 0, -2, 1, 0, 0, -7, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, -12, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -8, 0, 8, 0, 0, -5, 0,
4, 0, -9, -12, -9, -3, 4, 0,
0, -9, 0, 2, -3, 0, -2, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 3, 4, -16, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6, 0, 1, 0, 0, 0,
0, 0, 1, 1, -2, -3, 0, 0,
0, -1, 0, 0, -1, 0, 0, 0,
-3, 0, -1, 0, -3, -3, 0, -3,
-4, -4, -2, 0, -3, 0, -3, 0,
0, 0, 0, -1, 0, 0, 1, 0,
1, -1, 0, 0, 0, 0, 0, 1,
-1, 0, 0, 0, -1, 1, 1, 0,
0, 0, 0, -2, 0, 0, 0, 0,
0, 0, 0, 0, 0, 2, -1, 0,
-2, 0, -2, 0, 0, -1, 0, 4,
0, 0, -1, 0, 0, 0, 0, 0,
0, 0, -1, -1, 0, 0, -1, 0,
-1, 0, 0, 0, 0, 0, 0, 0,
0, 0, -1, -1, 0, -1, -2, 0,
0, 0, 0, 0, 0, 0, 0, -1,
0, -1, -1, -1, 0, 0, 0, 0,
0, 0, 0, 0, 0, -1, 0, 0,
0, 0, -1, -2, 0, -2, 0, -4,
-1, -4, 3, 0, 0, -3, 1, 3,
3, 0, -3, 0, -2, 0, 0, -6,
1, -1, 1, -7, 1, 0, 0, 0,
-7, 0, -7, -1, -11, -1, 0, -6,
0, 3, 4, 0, 2, 0, 0, 0,
0, 0, 0, -2, -2, 0, -4, 0,
0, 0, -1, 0, 0, 0, -1, 0,
0, 0, 0, 0, -1, -1, 0, -1,
-2, 0, 0, 0, 0, 0, 0, 0,
-1, -1, 0, -1, -2, -1, 0, 0,
-1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -1, -1, 0, -2,
0, -1, 0, -3, 1, 0, 0, -2,
1, 1, 1, 0, 0, 0, 0, 0,
0, -1, 0, 0, 0, 0, 0, 1,
0, 0, -1, 0, -1, -1, -2, 0,
0, 0, 0, 0, 0, 0, 1, 0,
-1, 0, 0, 0, 0, -1, -2, 0,
-2, 0, 4, -1, 0, -4, 0, 0,
3, -6, -7, -5, -3, 1, 0, -1,
-8, -2, 0, -2, 0, -3, 2, -2,
-8, 0, -3, 0, 0, 1, 0, 1,
-1, 0, 1, 0, -4, -5, 0, -6,
-3, -3, -3, -4, -2, -3, 0, -2,
-3, 1, 0, 0, 0, -1, 0, 0,
0, 1, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, -1,
0, -1, 0, 0, -1, 0, -2, -3,
-3, 0, 0, -4, 0, 0, 0, 0,
0, 0, -1, 0, 0, 0, 0, 1,
-1, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 6, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
-1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -2, 0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -1, 0, 0, 0,
-2, 0, 0, 0, 0, -6, -4, 0,
0, 0, -2, -6, 0, 0, -1, 1,
0, -3, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -2, 0, 0, -2,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, -2, 0,
0, 0, 0, 2, 0, 1, -3, -3,
0, -1, -1, -2, 0, 0, 0, 0,
0, 0, -4, 0, -1, 0, -2, -1,
0, -3, -3, -4, -1, 0, -3, 0,
-4, 0, 0, 0, 0, 10, 0, 0,
1, 0, 0, -2, 0, 1, 0, -6,
0, 0, 0, 0, 0, -12, -2, 4,
4, -1, -5, 0, 1, -2, 0, -6,
-1, -2, 1, -9, -1, 2, 0, 2,
-4, -2, -5, -4, -5, 0, 0, -8,
0, 7, 0, 0, -1, 0, 0, 0,
-1, -1, -1, -3, -4, 0, -12, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -1, 0, -1, -1, -2, 0, 0,
-3, 0, -1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -3, 0, 0, 3,
0, 2, 0, -3, 1, -1, 0, -3,
-1, 0, -2, -1, -1, 0, -2, -2,
0, 0, -1, 0, -1, -2, -2, 0,
0, -1, 0, 1, -1, 0, -3, 0,
0, 0, -3, 0, -2, 0, -2, -2,
1, 0, 0, 0, 0, 0, 0, 0,
0, -3, 1, 0, -2, 0, -1, -2,
-4, -1, -1, -1, 0, -1, -2, 0,
0, 0, 0, 0, 0, -1, -1, -1,
0, 0, 0, 0, 2, -1, 0, -1,
0, 0, 0, -1, -2, -1, -1, -2,
-1, 0, 1, 5, 0, 0, -3, 0,
-1, 3, 0, -1, -5, -2, 2, 0,
0, -6, -2, 1, -2, 1, 0, -1,
-1, -4, 0, -2, 1, 0, 0, -2,
0, 0, 0, 1, 1, -3, -2, 0,
-2, -1, -2, -1, -1, 0, -2, 1,
-2, -2, 4, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -2, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, -1, -1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -2, 0, 0, -2,
0, 0, -1, -1, 0, 0, 0, 0,
-1, 0, 0, 0, 0, -1, 0, 0,
0, 0, 0, -1, 0, 0, 0, 0,
-2, 0, -3, 0, 0, 0, -4, 0,
1, -3, 3, 0, -1, -6, 0, 0,
-3, -1, 0, -5, -3, -4, 0, 0,
-6, -1, -5, -5, -6, 0, -3, 0,
1, 9, -2, 0, -3, -1, 0, -1,
-2, -3, -2, -5, -5, -3, -1, 0,
0, -1, 0, 0, 0, 0, -9, -1,
4, 3, -3, -5, 0, 0, -4, 0,
-6, -1, -1, 3, -12, -2, 0, 0,
0, -8, -2, -7, -1, -9, 0, 0,
-9, 0, 8, 0, 0, -1, 0, 0,
0, 0, -1, -1, -5, -1, 0, -8,
0, 0, 0, 0, -4, 0, -1, 0,
0, -4, -6, 0, 0, -1, -2, -4,
-1, 0, -1, 0, 0, 0, 0, -6,
-1, -4, -4, -1, -2, -3, -1, -2,
0, -3, -1, -4, -2, 0, -2, -2,
-1, -2, 0, 1, 0, -1, -4, 0,
3, 0, -2, 0, 0, 0, 0, 2,
0, 1, -3, 5, 0, -1, -1, -2,
0, 0, 0, 0, 0, 0, -4, 0,
-1, 0, -2, -1, 0, -3, -3, -4,
-1, 0, -3, 1, 5, 0, 0, 0,
0, 10, 0, 0, 1, 0, 0, -2,
0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-1, -3, 0, 0, 0, 0, 0, -1,
0, 0, 0, -1, -1, 0, 0, -3,
-1, 0, 0, -3, 0, 2, -1, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 2, 3, 1, -1, 0, -4,
-2, 0, 4, -4, -4, -3, -3, 5,
2, 1, -11, -1, 3, -1, 0, -1,
1, -1, -4, 0, -1, 1, -2, -1,
-4, -1, 0, 0, 4, 3, 0, -4,
0, -7, -2, 4, -2, -5, 0, -2,
-4, -4, -1, 5, 1, 0, -2, 0,
-3, 0, 1, 4, -3, -5, -5, -3,
4, 0, 0, -9, -1, 1, -2, -1,
-3, 0, -3, -5, -2, -2, -1, 0,
0, -3, -3, -1, 0, 4, 3, -1,
-7, 0, -7, -2, 0, -4, -7, 0,
-4, -2, -4, -4, 3, 0, 0, -2,
0, -3, -1, 0, -1, -2, 0, 2,
-4, 1, 0, 0, -7, 0, -1, -3,
-2, -1, -4, -3, -4, -3, 0, -4,
-1, -3, -2, -4, -1, 0, 0, 0,
6, -2, 0, -4, -1, 0, -1, -3,
-3, -3, -4, -5, -2, -3, 3, 0,
-2, 0, -6, -2, 1, 3, -4, -5,
-3, -4, 4, -1, 1, -12, -2, 3,
-3, -2, -5, 0, -4, -5, -2, -1,
-1, -1, -3, -4, 0, 0, 0, 4,
4, -1, -8, 0, -8, -3, 3, -5,
-9, -3, -4, -5, -6, -4, 3, 0,
0, 0, 0, -2, 0, 0, 1, -2,
3, 1, -2, 3, 0, 0, -4, 0,
0, 0, 0, 0, 0, -1, 0, 0,
0, 0, 0, 0, -1, 0, 0, 0,
0, 1, 4, 0, 0, -2, 0, 0,
0, 0, -1, -1, -2, 0, 0, 0,
0, 1, 0, 0, 0, 0, 1, 0,
-1, 0, 5, 0, 2, 0, 0, -2,
0, 3, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 4, 0, 4, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, -8, 0, -1, 2, 0, 4,
0, 0, 13, 2, -3, -3, 1, 1,
-1, 0, -6, 0, 0, 6, -8, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, -9, 5, 18, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -8, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -2, 0, 0, -2,
-1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -1, 0, -3, 0,
0, 0, 0, 0, 1, 17, -3, -1,
4, 3, -3, 1, 0, 0, 1, 1,
-2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -17, 4, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, -4,
0, 0, 0, -3, 0, 0, 0, 0,
-3, -1, 0, 0, 0, -3, 0, -2,
0, -6, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -9, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -1, 0, 0, -2, 0, -2, 0,
-3, 0, 0, 0, -2, 1, -2, 0,
0, -3, -1, -3, 0, 0, -3, 0,
-1, 0, -6, 0, -1, 0, 0, -10,
-2, -5, -1, -5, 0, 0, -9, 0,
-3, -1, 0, 0, 0, 0, 0, 0,
0, 0, -2, -2, -1, -2, 0, 0,
0, 0, -3, 0, -3, 2, -1, 3,
0, -1, -3, -1, -2, -2, 0, -2,
-1, -1, 1, -3, 0, 0, 0, 0,
-11, -1, -2, 0, -3, 0, -1, -6,
-1, 0, 0, -1, -1, 0, 0, 0,
0, 1, 0, -1, -2, -1, 2, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 2, 0, 0, 0, 0, 0,
0, -3, 0, -1, 0, 0, 0, -3,
1, 0, 0, 0, -3, -1, -3, 0,
0, -4, 0, -1, 0, -6, 0, 0,
0, 0, -12, 0, -3, -5, -6, 0,
0, -9, 0, -1, -2, 0, 0, 0,
0, 0, 0, 0, 0, -1, -2, -1,
-2, 0, 0, 0, 2, -2, 0, 4,
6, -1, -1, -4, 2, 6, 2, 3,
-3, 2, 5, 2, 4, 3, 3, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 8, 6, -2, -1, 0, -1,
10, 6, 10, 0, 0, 0, 1, 0,
0, 5, 0, 0, -2, 0, 0, 0,
0, 0, 0, 0, 0, 0, -1, 0,
0, 0, 0, 0, 0, 0, 0, 2,
0, 0, 0, 0, -11, -2, -1, -5,
-6, 0, 0, -9, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -2, 0, 0,
0, 0, 0, 0, 0, 0, 0, -1,
0, 0, 0, 0, 0, 0, 0, 0,
2, 0, 0, 0, 0, -11, -2, -1,
-5, -6, 0, 0, -5, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-1, 0, 0, 0, -3, 1, 0, -1,
1, 2, 1, -4, 0, 0, -1, 1,
0, 1, 0, 0, 0, 0, -3, 0,
-1, -1, -3, 0, -1, -5, 0, 8,
-1, 0, -3, -1, 0, -1, -2, 0,
-1, -4, -3, -2, 0, 0, 0, -2,
0, 0, 0, 0, 0, 0, 0, 0,
0, -1, 0, 0, 0, 0, 0, 0,
0, 0, 2, 0, 0, 0, 0, -11,
-2, -1, -5, -6, 0, 0, -9, 0,
0, 0, 0, 0, 0, 6, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-2, 0, -4, -2, -1, 4, -1, -1,
-5, 0, -1, 0, -1, -3, 0, 3,
0, 1, 0, 1, -3, -5, -2, 0,
-5, -2, -3, -5, -5, 0, -2, -3,
-2, -2, -1, -1, -2, -1, 0, -1,
0, 2, 0, 2, -1, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, -1, -1, -1, 0, 0,
-3, 0, -1, 0, -2, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-8, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -1, -1, 0, -2,
0, 0, 0, 0, -1, 0, 0, -2,
-1, 1, 0, -2, -2, -1, 0, -4,
-1, -3, -1, -2, 0, -2, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -9, 0, 4, 0, 0, -2, 0,
0, 0, 0, -2, 0, -1, 0, 0,
-1, 0, 0, -1, 0, -3, 0, 0,
5, -2, -4, -4, 1, 1, 1, 0,
-4, 1, 2, 1, 4, 1, 4, -1,
-3, 0, 0, -5, 0, 0, -4, -3,
0, 0, -3, 0, -2, -2, 0, -2,
0, -2, 0, -1, 2, 0, -1, -4,
-1, 5, 0, 0, -1, 0, -3, 0,
0, 2, -3, 0, 1, -1, 1, 0,
0, -4, 0, -1, 0, 0, -1, 1,
-1, 0, 0, 0, -5, -2, -3, 0,
-4, 0, 0, -6, 0, 5, -1, 0,
-2, 0, 1, 0, -1, 0, -1, -4,
0, -1, 1, 0, 0, 0, 0, -1,
0, 0, 1, -2, 0, 0, 0, -2,
-1, 0, -2, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -8, 0, 3, 0,
0, -1, 0, 0, 0, 0, 0, 0,
-1, -1, 0, 0, 0, 3, 0, 3,
0, 0, 0, 0, 0, -8, -7, 0,
6, 4, 2, -5, 1, 5, 0, 5,
0, 3, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 7, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0
};
/*Collect the kern class' data in one place*/
static const lv_font_fmt_txt_kern_classes_t kern_classes =
{
.class_pair_values = kern_class_values,
.left_class_mapping = kern_left_class_mapping,
.right_class_mapping = kern_right_class_mapping,
.left_class_cnt = 61,
.right_class_cnt = 49,
};
/*--------------------
* ALL CUSTOM DATA
*--------------------*/
/*Store all the custom data of the font*/
static lv_font_fmt_txt_dsc_t font_dsc = {
.glyph_bitmap = gylph_bitmap,
.glyph_dsc = glyph_dsc,
.cmaps = cmaps,
.kern_dsc = &kern_classes,
.kern_scale = 16,
.cmap_num = 2,
.bpp = 4,
.kern_classes = 1,
.bitmap_format = 1
};
/*-----------------
* PUBLIC FONT
*----------------*/
/*Initialize a public general font descriptor*/
lv_font_t font_1 = {
.get_glyph_dsc = lv_font_get_glyph_dsc_fmt_txt, /*Function pointer to get glyph's data*/
.get_glyph_bitmap = lv_font_get_bitmap_fmt_txt, /*Function pointer to get glyph's bitmap*/
.line_height = 10, /*The maximum line height required by the font*/
.base_line = 2, /*Baseline measured from the bottom of the line*/
#if !(LVGL_VERSION_MAJOR == 6 && LVGL_VERSION_MINOR == 0)
.subpx = LV_FONT_SUBPX_NONE,
#endif
.dsc = &font_dsc /*The custom font data. Will be accessed by `get_glyph_bitmap/dsc` */
};
#endif /*#if FONT_1*/
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/test_fonts/font_1.c | C | apache-2.0 | 49,822 |
#if LV_BUILD_TEST
#include "../../lvgl.h"
/*******************************************************************************
* Size: 8 px
* Bpp: 4
* Opts: --bpp 4 --size 8 --font ../Montserrat-Medium.ttf -r 0x20-0x7F,0xB0,0x2022 --font ../FontAwesome5-Solid+Brands+Regular.woff -r 61441,61448,61451,61452,61452,61453,61457,61459,61461,61465,61468,61473,61478,61479,61480,61502,61512,61515,61516,61517,61521,61522,61523,61524,61543,61544,61550,61552,61553,61556,61559,61560,61561,61563,61587,61589,61636,61637,61639,61671,61674,61683,61724,61732,61787,61931,62016,62017,62018,62019,62020,62087,62099,62212,62189,62810,63426,63650 --no-compress --no-prefilter --force-fast-kern-format --format lvgl -o ..\generated_fonts/font_2.c
******************************************************************************/
#ifndef FONT_2
#define FONT_2 1
#endif
#if FONT_2
/*-----------------
* BITMAPS
*----------------*/
/*Store the image of the glyphs*/
static LV_ATTRIBUTE_LARGE_CONST const uint8_t gylph_bitmap[] = {
/* U+20 " " */
/* U+21 "!" */
0x58, 0x57, 0x46, 0x23, 0x46,
/* U+22 "\"" */
0x73, 0x97, 0x29, 0x0, 0x0,
/* U+23 "#" */
0x4, 0x52, 0x60, 0x4b, 0x9b, 0xa3, 0x8, 0x7,
0x20, 0x6c, 0x8c, 0x81, 0x9, 0x9, 0x0,
/* U+24 "$" */
0x0, 0x80, 0x2, 0xbd, 0xa2, 0x76, 0x80, 0x0,
0x8d, 0x81, 0x0, 0x84, 0x95, 0xad, 0xb3, 0x0,
0x80, 0x0,
/* U+25 "%" */
0x58, 0x70, 0x63, 0x8, 0x8, 0x36, 0x0, 0x27,
0x58, 0x67, 0x10, 0x8, 0x27, 0x26, 0x6, 0x20,
0x88, 0x20,
/* U+26 "&" */
0x9, 0x99, 0x0, 0xb, 0x3a, 0x0, 0x19, 0xc2,
0x20, 0x83, 0x1a, 0xa0, 0x3a, 0x99, 0x92, 0x0,
0x0, 0x0,
/* U+27 "'" */
0x72, 0x72, 0x0,
/* U+28 "(" */
0x8, 0x20, 0xb0, 0x1a, 0x3, 0x80, 0x1a, 0x0,
0xb0, 0x8, 0x20,
/* U+29 ")" */
0x73, 0x19, 0xb, 0xc, 0xb, 0x19, 0x73,
/* U+2A "*" */
0x48, 0x40, 0x6e, 0x80, 0x15, 0x10,
/* U+2B "+" */
0x0, 0x20, 0x0, 0xa, 0x0, 0x49, 0xd9, 0x10,
0xa, 0x0,
/* U+2C "," */
0x0, 0x75, 0x71,
/* U+2D "-" */
0x5a, 0x60,
/* U+2E "." */
0x0, 0x74,
/* U+2F "/" */
0x0, 0xa, 0x0, 0x2, 0x80, 0x0, 0x82, 0x0,
0xa, 0x0, 0x4, 0x60, 0x0, 0x91, 0x0, 0x19,
0x0, 0x0,
/* U+30 "0" */
0xa, 0xbb, 0x26, 0x60, 0x1b, 0x93, 0x0, 0xc6,
0x60, 0x1b, 0xa, 0xbb, 0x20,
/* U+31 "1" */
0x9e, 0x20, 0xa2, 0xa, 0x20, 0xa2, 0xa, 0x20,
/* U+32 "2" */
0x6a, 0xb9, 0x0, 0x0, 0xc0, 0x0, 0x58, 0x0,
0x87, 0x0, 0x9e, 0xaa, 0x30,
/* U+33 "3" */
0x7a, 0xbe, 0x0, 0xa, 0x20, 0x4, 0xa9, 0x0,
0x0, 0xa2, 0x8a, 0xa9, 0x0,
/* U+34 "4" */
0x0, 0x49, 0x0, 0x3, 0xa0, 0x0, 0x1b, 0x8,
0x20, 0x8b, 0xad, 0xb2, 0x0, 0x9, 0x30,
/* U+35 "5" */
0x3d, 0xaa, 0x5, 0x60, 0x0, 0x5b, 0xa8, 0x0,
0x0, 0x93, 0x7a, 0xaa, 0x0,
/* U+36 "6" */
0x9, 0xaa, 0x36, 0x70, 0x0, 0x98, 0x9a, 0x26,
0x80, 0x2a, 0x9, 0x9a, 0x40,
/* U+37 "7" */
0xca, 0xad, 0x67, 0x0, 0xc0, 0x0, 0x67, 0x0,
0xc, 0x0, 0x6, 0x70, 0x0,
/* U+38 "8" */
0x1a, 0xab, 0x25, 0x60, 0x48, 0x1d, 0xad, 0x38,
0x40, 0x1b, 0x3a, 0x9a, 0x40,
/* U+39 "9" */
0x4a, 0x99, 0xb, 0x10, 0x95, 0x3a, 0x99, 0x80,
0x0, 0x95, 0x3a, 0xb8, 0x0,
/* U+3A ":" */
0x74, 0x0, 0x0, 0x74,
/* U+3B ";" */
0x74, 0x0, 0x0, 0x75, 0x62, 0x0,
/* U+3C "<" */
0x0, 0x1, 0x0, 0x49, 0x80, 0x5c, 0x30, 0x0,
0x16, 0x91, 0x0, 0x0, 0x0,
/* U+3D "=" */
0x49, 0x99, 0x10, 0x0, 0x0, 0x49, 0x99, 0x10,
/* U+3E ">" */
0x10, 0x0, 0x3, 0x98, 0x20, 0x0, 0x6d, 0x14,
0x94, 0x0, 0x0, 0x0, 0x0,
/* U+3F "?" */
0x6a, 0xb9, 0x0, 0x0, 0xc0, 0x0, 0xa4, 0x0,
0x3, 0x0, 0x2, 0x80, 0x0,
/* U+40 "@" */
0x3, 0x87, 0x78, 0x50, 0x28, 0x4a, 0x9c, 0x75,
0x80, 0xb0, 0xa, 0x28, 0x80, 0xb0, 0xa, 0x28,
0x28, 0x49, 0x99, 0xa6, 0x3, 0x88, 0x75, 0x0,
/* U+41 "A" */
0x0, 0xb, 0x90, 0x0, 0x3, 0x8a, 0x10, 0x0,
0xb1, 0x39, 0x0, 0x4d, 0x99, 0xd1, 0xb, 0x10,
0x3, 0x90,
/* U+42 "B" */
0x2d, 0x99, 0xb1, 0x2a, 0x0, 0x84, 0x2d, 0x9a,
0xd1, 0x2a, 0x0, 0x39, 0x2d, 0x99, 0xb4,
/* U+43 "C" */
0x7, 0xba, 0xa2, 0x59, 0x0, 0x0, 0x93, 0x0,
0x0, 0x59, 0x0, 0x0, 0x7, 0xba, 0xa2,
/* U+44 "D" */
0x2e, 0xab, 0xb3, 0x2, 0xa0, 0x1, 0xc0, 0x2a,
0x0, 0x9, 0x22, 0xa0, 0x1, 0xc0, 0x2e, 0xab,
0xb3, 0x0,
/* U+45 "E" */
0x2e, 0xaa, 0x82, 0xa0, 0x0, 0x2d, 0xaa, 0x42,
0xa0, 0x0, 0x2e, 0xaa, 0x90,
/* U+46 "F" */
0x2e, 0xaa, 0x82, 0xa0, 0x0, 0x2e, 0xaa, 0x42,
0xa0, 0x0, 0x2a, 0x0, 0x0,
/* U+47 "G" */
0x7, 0xba, 0xa2, 0x59, 0x0, 0x0, 0x93, 0x0,
0x23, 0x59, 0x0, 0x47, 0x7, 0xba, 0xa3,
/* U+48 "H" */
0x2a, 0x0, 0x2a, 0x2a, 0x0, 0x2a, 0x2e, 0xaa,
0xba, 0x2a, 0x0, 0x2a, 0x2a, 0x0, 0x2a,
/* U+49 "I" */
0x2a, 0x2a, 0x2a, 0x2a, 0x2a,
/* U+4A "J" */
0x5, 0xad, 0x50, 0x0, 0x75, 0x0, 0x7, 0x50,
0x0, 0x84, 0x9, 0xab, 0x0,
/* U+4B "K" */
0x2a, 0x1, 0xa2, 0x2a, 0x1b, 0x20, 0x2c, 0xc7,
0x0, 0x2d, 0x19, 0x50, 0x2a, 0x0, 0xa4,
/* U+4C "L" */
0x2a, 0x0, 0x2, 0xa0, 0x0, 0x2a, 0x0, 0x2,
0xa0, 0x0, 0x2e, 0xaa, 0x70,
/* U+4D "M" */
0x2c, 0x0, 0x3, 0xc2, 0xd7, 0x0, 0xbc, 0x29,
0x92, 0x84, 0xc2, 0x91, 0xb9, 0xc, 0x29, 0x3,
0x0, 0xc0,
/* U+4E "N" */
0x2d, 0x10, 0x2a, 0x2c, 0xb0, 0x2a, 0x2a, 0x4b,
0x2a, 0x2a, 0x5, 0xca, 0x2a, 0x0, 0x7a,
/* U+4F "O" */
0x7, 0xbb, 0xb3, 0x5, 0x90, 0x1, 0xc1, 0x93,
0x0, 0x8, 0x45, 0x90, 0x1, 0xc1, 0x7, 0xbb,
0xb3, 0x0,
/* U+50 "P" */
0x2e, 0xaa, 0x90, 0x2a, 0x0, 0x84, 0x2a, 0x0,
0xa3, 0x2e, 0xaa, 0x60, 0x2a, 0x0, 0x0,
/* U+51 "Q" */
0x7, 0xbb, 0xb3, 0x5, 0x90, 0x1, 0xc1, 0x93,
0x0, 0x8, 0x45, 0x90, 0x0, 0xc1, 0x7, 0xbb,
0xb3, 0x0, 0x0, 0x39, 0x93,
/* U+52 "R" */
0x2e, 0xaa, 0x90, 0x2a, 0x0, 0x84, 0x2a, 0x0,
0xa3, 0x2d, 0xac, 0x80, 0x2a, 0x1, 0xa1,
/* U+53 "S" */
0x2a, 0xaa, 0x27, 0x60, 0x0, 0x8, 0x98, 0x10,
0x0, 0x49, 0x5a, 0xaa, 0x30,
/* U+54 "T" */
0xaa, 0xea, 0x60, 0xc, 0x0, 0x0, 0xc0, 0x0,
0xc, 0x0, 0x0, 0xc0, 0x0,
/* U+55 "U" */
0x39, 0x0, 0x48, 0x39, 0x0, 0x48, 0x39, 0x0,
0x48, 0x1c, 0x0, 0x66, 0x6, 0xba, 0xa0,
/* U+56 "V" */
0xb, 0x10, 0x5, 0x70, 0x49, 0x0, 0xb0, 0x0,
0xc1, 0x57, 0x0, 0x4, 0x9c, 0x0, 0x0, 0xc,
0x70, 0x0,
/* U+57 "W" */
0x94, 0x0, 0xf1, 0x3, 0x93, 0xa0, 0x69, 0x70,
0x93, 0xc, 0xb, 0xb, 0xb, 0x0, 0x79, 0x80,
0x89, 0x70, 0x1, 0xf2, 0x2, 0xf1, 0x0,
/* U+58 "X" */
0x58, 0x2, 0xa0, 0x8, 0x7b, 0x10, 0x0, 0xf5,
0x0, 0xa, 0x4b, 0x10, 0x76, 0x2, 0xb0,
/* U+59 "Y" */
0xa, 0x20, 0xb, 0x0, 0x1b, 0x9, 0x30, 0x0,
0x5b, 0x80, 0x0, 0x0, 0xd0, 0x0, 0x0, 0xc,
0x0, 0x0,
/* U+5A "Z" */
0x6a, 0xac, 0xd0, 0x0, 0x1b, 0x10, 0x0, 0xb2,
0x0, 0xb, 0x30, 0x0, 0x8d, 0xaa, 0xa0,
/* U+5B "[" */
0x2d, 0x42, 0x90, 0x29, 0x2, 0x90, 0x29, 0x2,
0x90, 0x2d, 0x40,
/* U+5C "\\" */
0x19, 0x0, 0x0, 0xa0, 0x0, 0x5, 0x50, 0x0,
0xa, 0x0, 0x0, 0x91, 0x0, 0x3, 0x70, 0x0,
0xa, 0x0,
/* U+5D "]" */
0x8c, 0xc, 0xc, 0xc, 0xc, 0xc, 0x8c,
/* U+5E "^" */
0x3, 0xc0, 0x0, 0x94, 0x50, 0x27, 0x9, 0x0,
/* U+5F "_" */
0x77, 0x77,
/* U+60 "`" */
0x6, 0x60,
/* U+61 "a" */
0x29, 0x98, 0x2, 0x98, 0xd0, 0x84, 0xc, 0x13,
0xb9, 0xd1,
/* U+62 "b" */
0x48, 0x0, 0x0, 0x48, 0x0, 0x0, 0x4c, 0xab,
0x50, 0x4a, 0x0, 0xc0, 0x4a, 0x0, 0xc0, 0x4c,
0xaa, 0x50,
/* U+63 "c" */
0x1a, 0xaa, 0x18, 0x40, 0x0, 0x84, 0x0, 0x1,
0xaa, 0xa1,
/* U+64 "d" */
0x0, 0x0, 0xb0, 0x0, 0xb, 0x1a, 0xaa, 0xb9,
0x40, 0x3b, 0x94, 0x2, 0xb1, 0xa9, 0x9b,
/* U+65 "e" */
0x19, 0x99, 0x19, 0x98, 0x86, 0x85, 0x1, 0x1,
0xaa, 0xb1,
/* U+66 "f" */
0xa, 0xa0, 0x2a, 0x0, 0x9d, 0x70, 0x29, 0x0,
0x29, 0x0, 0x29, 0x0,
/* U+67 "g" */
0x1a, 0x99, 0xb9, 0x40, 0x1c, 0x94, 0x2, 0xc1,
0xaa, 0xab, 0x18, 0x9a, 0x30,
/* U+68 "h" */
0x48, 0x0, 0x4, 0x80, 0x0, 0x4c, 0x9b, 0x44,
0x90, 0x1b, 0x48, 0x0, 0xc4, 0x80, 0xc,
/* U+69 "i" */
0x37, 0x0, 0x48, 0x48, 0x48, 0x48,
/* U+6A "j" */
0x3, 0x70, 0x0, 0x3, 0x80, 0x38, 0x3, 0x80,
0x38, 0x6b, 0x40,
/* U+6B "k" */
0x48, 0x0, 0x4, 0x80, 0x0, 0x48, 0xa, 0x44,
0x9c, 0x30, 0x4d, 0x6a, 0x4, 0x80, 0x77,
/* U+6C "l" */
0x48, 0x48, 0x48, 0x48, 0x48, 0x48,
/* U+6D "m" */
0x4c, 0x9b, 0x89, 0xb4, 0x49, 0x3, 0xb0, 0xb,
0x48, 0x2, 0xa0, 0xc, 0x48, 0x2, 0xa0, 0xc,
/* U+6E "n" */
0x4c, 0x9b, 0x44, 0x90, 0x1b, 0x48, 0x0, 0xc4,
0x80, 0xc,
/* U+6F "o" */
0x1a, 0xaa, 0x18, 0x40, 0x3a, 0x84, 0x3, 0xa1,
0xaa, 0xa1,
/* U+70 "p" */
0x4c, 0xab, 0x50, 0x4a, 0x0, 0xc0, 0x4a, 0x0,
0xc0, 0x4c, 0xaa, 0x50, 0x48, 0x0, 0x0,
/* U+71 "q" */
0x1a, 0xa9, 0xb9, 0x40, 0x3b, 0x94, 0x3, 0xb1,
0xaa, 0x9b, 0x0, 0x0, 0xb0,
/* U+72 "r" */
0x4b, 0xa0, 0x4a, 0x0, 0x48, 0x0, 0x48, 0x0,
/* U+73 "s" */
0x5b, 0x95, 0x87, 0x30, 0x3, 0x79, 0x7a, 0xa6,
/* U+74 "t" */
0x29, 0x0, 0x9d, 0x70, 0x29, 0x0, 0x29, 0x0,
0xb, 0x90,
/* U+75 "u" */
0x57, 0x1, 0xb5, 0x70, 0x1b, 0x48, 0x3, 0xb0,
0xa9, 0x9b,
/* U+76 "v" */
0xb, 0x0, 0x84, 0x5, 0x70, 0xb0, 0x0, 0xb7,
0x50, 0x0, 0x6d, 0x0,
/* U+77 "w" */
0xb0, 0xe, 0x20, 0xa0, 0x55, 0x59, 0x82, 0x80,
0xa, 0xa0, 0xa8, 0x20, 0x9, 0x80, 0x6b, 0x0,
/* U+78 "x" */
0x67, 0x1b, 0x0, 0x9b, 0x10, 0xa, 0xb2, 0x7,
0x51, 0xb0,
/* U+79 "y" */
0xb, 0x10, 0x83, 0x3, 0x81, 0xa0, 0x0, 0xaa,
0x30, 0x0, 0x4a, 0x0, 0xa, 0xb2, 0x0,
/* U+7A "z" */
0x59, 0xbb, 0x1, 0xb1, 0xb, 0x20, 0x9c, 0x98,
/* U+7B "{" */
0xa, 0x60, 0xc0, 0xc, 0x5, 0xb0, 0xc, 0x0,
0xc0, 0xa, 0x60,
/* U+7C "|" */
0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28,
/* U+7D "}" */
0x97, 0x0, 0xb0, 0xb, 0x0, 0xd3, 0xb, 0x0,
0xb0, 0x97, 0x0,
/* U+7E "~" */
0x29, 0x35, 0x15, 0x6, 0x80,
/* U+B0 "°" */
0x26, 0x47, 0x7, 0x27, 0x50,
/* U+2022 "•" */
0x0, 0x5d, 0x2,
/* U+F001 "" */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x26, 0xbe,
0x0, 0x8d, 0xff, 0xff, 0x0, 0xff, 0xe9, 0x5f,
0x0, 0xf3, 0x0, 0xf, 0x0, 0xf0, 0x0, 0xf,
0x0, 0xf0, 0xa, 0xff, 0xaf, 0xf0, 0xa, 0xfa,
0xaf, 0xa0, 0x0, 0x0,
/* U+F008 "" */
0xbd, 0xcc, 0xce, 0xab, 0x8b, 0x0, 0x7, 0x58,
0xcd, 0x66, 0x6a, 0xac, 0xcd, 0x66, 0x6a, 0xac,
0x8b, 0x0, 0x7, 0x58, 0xbd, 0xcc, 0xce, 0xab,
/* U+F00B "" */
0x34, 0x14, 0x44, 0x43, 0xff, 0x7f, 0xff, 0xff,
0xab, 0x4b, 0xbb, 0xba, 0xbc, 0x5c, 0xcc, 0xcb,
0xff, 0x7f, 0xff, 0xff, 0x67, 0x17, 0x88, 0x86,
0xff, 0x7f, 0xff, 0xff, 0xab, 0x4b, 0xbb, 0xba,
/* U+F00C "" */
0x0, 0x0, 0x0, 0x9a, 0x0, 0x0, 0x9, 0xfa,
0xa9, 0x0, 0x9f, 0xa0, 0xaf, 0x99, 0xfa, 0x0,
0xa, 0xff, 0xa0, 0x0, 0x0, 0x99, 0x0, 0x0,
/* U+F00D "" */
0x63, 0x0, 0x82, 0xcf, 0x4a, 0xf4, 0x1d, 0xff,
0x60, 0xa, 0xff, 0x30, 0xaf, 0x7d, 0xf3, 0xa6,
0x1, 0xb3,
/* U+F011 "" */
0x0, 0xc, 0x51, 0x0, 0x1d, 0x7d, 0x6e, 0x70,
0x8d, 0xd, 0x65, 0xf1, 0xc7, 0xd, 0x60, 0xe6,
0xd7, 0x6, 0x20, 0xe6, 0x9d, 0x0, 0x4, 0xf2,
0x1e, 0xc7, 0x8f, 0x80, 0x1, 0x9d, 0xc6, 0x0,
/* U+F013 "" */
0x0, 0xc, 0xc0, 0x0, 0x18, 0x8f, 0xf8, 0x81,
0x8f, 0xfe, 0xef, 0xf8, 0x2f, 0xe0, 0xe, 0xf2,
0x2f, 0xe0, 0xe, 0xf2, 0x8f, 0xfe, 0xef, 0xf8,
0x18, 0x8f, 0xf8, 0x81, 0x0, 0xc, 0xc0, 0x0,
/* U+F015 "" */
0x0, 0x0, 0x30, 0x22, 0x0, 0x0, 0xaf, 0xaa,
0xa0, 0x1, 0xda, 0x6a, 0xfa, 0x3, 0xe8, 0xbf,
0xb8, 0xe3, 0xb6, 0xdf, 0xff, 0xd6, 0xb0, 0x8f,
0xfb, 0xff, 0x80, 0x8, 0xfc, 0xc, 0xf8, 0x0,
0x5b, 0x80, 0x8b, 0x50,
/* U+F019 "" */
0x0, 0xf, 0xf0, 0x0, 0x0, 0xf, 0xf0, 0x0,
0x0, 0xf, 0xf0, 0x0, 0x7, 0xff, 0xff, 0x70,
0x0, 0x9f, 0xf9, 0x0, 0x78, 0x7a, 0xa7, 0x87,
0xff, 0xfb, 0xbf, 0xff, 0xff, 0xff, 0xfb, 0xbf,
/* U+F01C "" */
0x5, 0xff, 0xff, 0xf5, 0x1, 0xe3, 0x0, 0x3,
0xe1, 0xa8, 0x0, 0x0, 0x8, 0xaf, 0xff, 0x60,
0x6f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfd, 0xff,
0xff, 0xff, 0xfd,
/* U+F021 "" */
0x0, 0x0, 0x0, 0x3, 0x2, 0xbf, 0xfb, 0x3f,
0x2e, 0x91, 0x18, 0xff, 0x9a, 0x0, 0x6c, 0xff,
0x31, 0x0, 0x24, 0x44, 0x44, 0x42, 0x0, 0x13,
0xff, 0xc6, 0x0, 0xb9, 0xfe, 0xa5, 0x5b, 0xd1,
0xf2, 0x8c, 0xc8, 0x10, 0x30, 0x0, 0x0, 0x0,
/* U+F026 "" */
0x0, 0x9, 0x34, 0xcf, 0xff, 0xff, 0xff, 0xff,
0xab, 0xff, 0x0, 0x4f, 0x0, 0x1,
/* U+F027 "" */
0x0, 0x9, 0x0, 0x34, 0xcf, 0x1, 0xff, 0xff,
0x1b, 0xff, 0xff, 0x1b, 0xbb, 0xff, 0x1, 0x0,
0x4f, 0x0, 0x0, 0x1, 0x0,
/* U+F028 "" */
0x0, 0x0, 0x0, 0x54, 0x0, 0x0, 0x90, 0x23,
0xb3, 0x34, 0xcf, 0x2, 0xc3, 0xbf, 0xff, 0xf1,
0xb5, 0x6c, 0xff, 0xff, 0x1b, 0x56, 0xca, 0xbf,
0xf0, 0x2c, 0x3a, 0x0, 0x4f, 0x2, 0x3b, 0x30,
0x0, 0x10, 0x5, 0x40,
/* U+F03E "" */
0xdf, 0xff, 0xff, 0xfd, 0xf0, 0x7f, 0xff, 0xff,
0xf8, 0xcf, 0xb1, 0xbf, 0xfb, 0x5b, 0x0, 0xf,
0xf0, 0x0, 0x0, 0xf, 0xdf, 0xff, 0xff, 0xfd,
/* U+F048 "" */
0x40, 0x0, 0x2f, 0x20, 0x8f, 0xf2, 0x9f, 0xff,
0xcf, 0xff, 0xff, 0xff, 0xff, 0x5e, 0xff, 0xf2,
0x2e, 0xfb, 0x10, 0x19,
/* U+F04B "" */
0x0, 0x0, 0x0, 0xd, 0xa1, 0x0, 0x0, 0xff,
0xf7, 0x0, 0xf, 0xff, 0xfd, 0x40, 0xff, 0xff,
0xff, 0xaf, 0xff, 0xff, 0xfa, 0xff, 0xff, 0xd4,
0xf, 0xff, 0x70, 0x0, 0xda, 0x10, 0x0, 0x0,
0x0, 0x0, 0x0,
/* U+F04C "" */
0x9b, 0x90, 0x9b, 0x9f, 0xff, 0xf, 0xff, 0xff,
0xf0, 0xff, 0xff, 0xff, 0xf, 0xff, 0xff, 0xf0,
0xff, 0xff, 0xff, 0xf, 0xff, 0xff, 0xf0, 0xff,
0xf2, 0x42, 0x2, 0x42,
/* U+F04D "" */
0x24, 0x44, 0x44, 0x2f, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xf8, 0xbb, 0xbb, 0xb8,
/* U+F051 "" */
0x20, 0x0, 0x4f, 0x80, 0x2f, 0xff, 0x92, 0xff,
0xff, 0xcf, 0xff, 0xff, 0xff, 0xfe, 0x5f, 0xfd,
0x22, 0xf9, 0x10, 0x1b,
/* U+F052 "" */
0x0, 0x0, 0x20, 0x0, 0x0, 0x0, 0x8f, 0x80,
0x0, 0x0, 0x7f, 0xff, 0x70, 0x0, 0x5f, 0xff,
0xff, 0x50, 0xe, 0xff, 0xff, 0xfe, 0x0, 0x58,
0x88, 0x88, 0x50, 0xf, 0xff, 0xff, 0xff, 0x0,
0xab, 0xbb, 0xbb, 0xa0,
/* U+F053 "" */
0x0, 0x6, 0x20, 0x7, 0xf4, 0x7, 0xf5, 0x5,
0xf6, 0x0, 0x1e, 0xb0, 0x0, 0x2e, 0xb0, 0x0,
0x2e, 0x60, 0x0, 0x10,
/* U+F054 "" */
0x26, 0x0, 0x4, 0xf7, 0x0, 0x5, 0xf7, 0x0,
0x6, 0xf5, 0x0, 0xbe, 0x10, 0xbe, 0x20, 0x6e,
0x20, 0x0, 0x10, 0x0,
/* U+F067 "" */
0x0, 0x4, 0x0, 0x0, 0x3, 0xf3, 0x0, 0x0,
0x4f, 0x40, 0x7, 0x8a, 0xfa, 0x87, 0xef, 0xff,
0xff, 0xe0, 0x4, 0xf4, 0x0, 0x0, 0x4f, 0x40,
0x0, 0x1, 0xb1, 0x0,
/* U+F068 "" */
0x78, 0x88, 0x88, 0x7e, 0xff, 0xff, 0xfe,
/* U+F06E "" */
0x0, 0x8c, 0xcc, 0x80, 0x1, 0xdd, 0x16, 0x3d,
0xd1, 0xcf, 0x55, 0xed, 0x5f, 0xcb, 0xf5, 0xdf,
0xd5, 0xfc, 0x1d, 0xd3, 0x73, 0xdd, 0x10, 0x8,
0xdc, 0xc8, 0x10,
/* U+F070 "" */
0x1d, 0x30, 0x0, 0x0, 0x0, 0x0, 0x5e, 0x8c,
0xcc, 0xa2, 0x0, 0x0, 0x2d, 0xb4, 0x49, 0xf4,
0x0, 0x7a, 0x1a, 0xff, 0x3f, 0xe1, 0x7, 0xfa,
0x6, 0xf7, 0xff, 0x10, 0xa, 0xf3, 0x3, 0xef,
0x40, 0x0, 0x6, 0xcc, 0x71, 0xbb, 0x10, 0x0,
0x0, 0x0, 0x0, 0x89,
/* U+F071 "" */
0x0, 0x0, 0x3e, 0x30, 0x0, 0x0, 0x0, 0xc,
0xfc, 0x0, 0x0, 0x0, 0x6, 0xfc, 0xf6, 0x0,
0x0, 0x0, 0xed, 0xd, 0xe0, 0x0, 0x0, 0x8f,
0xe0, 0xef, 0x80, 0x0, 0x2f, 0xff, 0x6f, 0xff,
0x20, 0xb, 0xff, 0xe2, 0xef, 0xfa, 0x0, 0xdf,
0xff, 0xff, 0xff, 0xd0,
/* U+F074 "" */
0x0, 0x0, 0x0, 0x20, 0x44, 0x0, 0x4, 0xf5,
0xef, 0xb1, 0xcf, 0xfd, 0x1, 0x8c, 0xd1, 0xc1,
0x1, 0xdc, 0x81, 0xc1, 0xef, 0xc1, 0xbf, 0xfd,
0x44, 0x0, 0x4, 0xf5, 0x0, 0x0, 0x0, 0x20,
/* U+F077 "" */
0x0, 0x0, 0x0, 0x0, 0x4, 0xe4, 0x0, 0x4,
0xfc, 0xf4, 0x4, 0xf8, 0x8, 0xf4, 0xb8, 0x0,
0x8, 0xb0, 0x0, 0x0, 0x0,
/* U+F078 "" */
0x0, 0x0, 0x0, 0xb, 0x80, 0x0, 0x8b, 0x4f,
0x80, 0x8f, 0x40, 0x4f, 0xcf, 0x40, 0x0, 0x4e,
0x40, 0x0, 0x0, 0x0, 0x0,
/* U+F079 "" */
0x0, 0x94, 0x14, 0x44, 0x40, 0x0, 0xbf, 0xf8,
0xbb, 0xbf, 0x10, 0x8, 0xb7, 0x60, 0x0, 0xe1,
0x0, 0xb, 0x40, 0x0, 0x1e, 0x20, 0x0, 0xb7,
0x44, 0x5e, 0xfd, 0x50, 0x7, 0xbb, 0xb8, 0x5f,
0x80, 0x0, 0x0, 0x0, 0x0, 0x20, 0x0,
/* U+F07B "" */
0xdf, 0xfb, 0x0, 0x0, 0xff, 0xff, 0xff, 0xfd,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xdf, 0xff, 0xff, 0xfd,
/* U+F093 "" */
0x0, 0x9, 0x90, 0x0, 0x0, 0x9f, 0xf9, 0x0,
0x7, 0xff, 0xff, 0x70, 0x0, 0xf, 0xf0, 0x0,
0x0, 0xf, 0xf0, 0x0, 0x78, 0x4f, 0xf4, 0x87,
0xff, 0xe8, 0x8e, 0xff, 0xff, 0xff, 0xfb, 0xbf,
/* U+F095 "" */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7,
0xea, 0x0, 0x0, 0x0, 0xef, 0xe0, 0x0, 0x0,
0xc, 0xfc, 0x0, 0x0, 0x0, 0x4f, 0x70, 0x0,
0x0, 0x1d, 0xe0, 0x7, 0xdc, 0x4d, 0xf3, 0x0,
0xef, 0xff, 0xe3, 0x0, 0xa, 0xec, 0x70, 0x0,
0x0,
/* U+F0C4 "" */
0x3, 0x0, 0x0, 0x0, 0xcd, 0xc0, 0x2d, 0xc0,
0xe7, 0xf2, 0xee, 0x20, 0x4b, 0xff, 0xe2, 0x0,
0x4, 0xff, 0xa0, 0x0, 0xcd, 0xf9, 0xf9, 0x0,
0xe7, 0xe0, 0x7f, 0x90, 0x4a, 0x40, 0x4, 0x50,
/* U+F0C5 "" */
0x0, 0xff, 0xf7, 0x47, 0x4f, 0xff, 0x47, 0xf8,
0xff, 0xff, 0xff, 0x8f, 0xff, 0xff, 0xf8, 0xff,
0xff, 0xff, 0x8f, 0xff, 0xff, 0xfb, 0x78, 0x88,
0x7f, 0xff, 0xff, 0x0,
/* U+F0C7 "" */
0x24, 0x44, 0x41, 0xf, 0xbb, 0xbb, 0xe2, 0xf0,
0x0, 0xf, 0xdf, 0x44, 0x44, 0xff, 0xff, 0xfc,
0xff, 0xff, 0xf9, 0x9, 0xff, 0xff, 0xd5, 0xdf,
0xf8, 0xbb, 0xbb, 0xb8,
/* U+F0E7 "" */
0x7, 0xff, 0x60, 0x0, 0xaf, 0xf2, 0x0, 0xc,
0xff, 0x87, 0x0, 0xef, 0xff, 0xb0, 0x7, 0x8e,
0xf2, 0x0, 0x0, 0xf8, 0x0, 0x0, 0x3e, 0x0,
0x0, 0x6, 0x50, 0x0,
/* U+F0EA "" */
0x79, 0xb9, 0x70, 0xf, 0xfc, 0xff, 0x0, 0xff,
0x68, 0x83, 0xf, 0xf8, 0xff, 0x8b, 0xff, 0x8f,
0xf8, 0x8f, 0xf8, 0xff, 0xff, 0x78, 0x8f, 0xff,
0xf0, 0x7, 0xff, 0xff,
/* U+F0F3 "" */
0x0, 0xd, 0x0, 0x0, 0x4e, 0xfe, 0x30, 0xd,
0xff, 0xfd, 0x0, 0xff, 0xff, 0xf0, 0x3f, 0xff,
0xff, 0x3b, 0xff, 0xff, 0xfb, 0x78, 0x88, 0x88,
0x60, 0x4, 0xf4, 0x0,
/* U+F11C "" */
0xdf, 0xff, 0xff, 0xff, 0xdf, 0x18, 0x81, 0x88,
0x1f, 0xfe, 0xaa, 0xca, 0xae, 0xff, 0xea, 0xac,
0xaa, 0xef, 0xf1, 0x80, 0x0, 0x81, 0xfd, 0xff,
0xff, 0xff, 0xfd,
/* U+F124 "" */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x4b, 0xc0, 0x0, 0x0, 0x5c, 0xff, 0xb0, 0x0,
0x6e, 0xff, 0xff, 0x40, 0xd, 0xff, 0xff, 0xfc,
0x0, 0x6, 0x88, 0xcf, 0xf5, 0x0, 0x0, 0x0,
0x8f, 0xe0, 0x0, 0x0, 0x0, 0x8f, 0x60, 0x0,
0x0, 0x0, 0x5d, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0,
/* U+F15B "" */
0xff, 0xf8, 0xb0, 0xff, 0xf8, 0xfb, 0xff, 0xfc,
0x88, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
/* U+F1EB "" */
0x0, 0x4, 0x77, 0x40, 0x0, 0x9, 0xff, 0xcc,
0xff, 0x90, 0xcd, 0x40, 0x0, 0x4, 0xdc, 0x20,
0x4b, 0xff, 0xb4, 0x2, 0x1, 0xfa, 0x55, 0xaf,
0x10, 0x0, 0x0, 0x21, 0x0, 0x0, 0x0, 0x0,
0xee, 0x0, 0x0, 0x0, 0x0, 0x87, 0x0, 0x0,
/* U+F240 "" */
0x24, 0x44, 0x44, 0x44, 0x40, 0xfb, 0xbb, 0xbb,
0xbb, 0xda, 0xf7, 0xee, 0xee, 0xee, 0x5f, 0xf8,
0xff, 0xff, 0xff, 0x2f, 0xf5, 0x66, 0x66, 0x66,
0xab, 0x8b, 0xbb, 0xbb, 0xbb, 0xb3,
/* U+F241 "" */
0x24, 0x44, 0x44, 0x44, 0x40, 0xfb, 0xbb, 0xbb,
0xbb, 0xda, 0xf7, 0xee, 0xee, 0x70, 0x5f, 0xf8,
0xff, 0xff, 0x80, 0x2f, 0xf5, 0x66, 0x66, 0x54,
0xab, 0x8b, 0xbb, 0xbb, 0xbb, 0xb3,
/* U+F242 "" */
0x24, 0x44, 0x44, 0x44, 0x40, 0xfb, 0xbb, 0xbb,
0xbb, 0xda, 0xf7, 0xee, 0xe0, 0x0, 0x5f, 0xf8,
0xff, 0xf0, 0x0, 0x2f, 0xf5, 0x66, 0x64, 0x44,
0xab, 0x8b, 0xbb, 0xbb, 0xbb, 0xb3,
/* U+F243 "" */
0x24, 0x44, 0x44, 0x44, 0x40, 0xfb, 0xbb, 0xbb,
0xbb, 0xda, 0xf7, 0xe7, 0x0, 0x0, 0x5f, 0xf8,
0xf8, 0x0, 0x0, 0x2f, 0xf5, 0x65, 0x44, 0x44,
0xab, 0x8b, 0xbb, 0xbb, 0xbb, 0xb3,
/* U+F244 "" */
0x24, 0x44, 0x44, 0x44, 0x40, 0xfb, 0xbb, 0xbb,
0xbb, 0xd8, 0xf0, 0x0, 0x0, 0x0, 0x5f, 0xf0,
0x0, 0x0, 0x0, 0x2f, 0xf4, 0x44, 0x44, 0x44,
0xad, 0x8b, 0xbb, 0xbb, 0xbb, 0xb3,
/* U+F287 "" */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7,
0xd8, 0x0, 0x0, 0x0, 0x7, 0x36, 0x40, 0x0,
0x9, 0xb1, 0x91, 0x11, 0x17, 0x20, 0xef, 0x88,
0xd8, 0x88, 0xd9, 0x2, 0x20, 0x6, 0x48, 0x70,
0x0, 0x0, 0x0, 0x6, 0xec, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0,
/* U+F293 "" */
0x6, 0xdd, 0xc3, 0x4, 0xff, 0x3e, 0xd0, 0x9c,
0xb5, 0x5f, 0x2b, 0xf7, 0x1a, 0xf4, 0xbf, 0x81,
0xbf, 0x39, 0xc9, 0x64, 0xf2, 0x4f, 0xf3, 0xde,
0x0, 0x6d, 0xed, 0x30,
/* U+F2ED "" */
0x78, 0xdf, 0xd8, 0x77, 0x88, 0x88, 0x87, 0x8f,
0xff, 0xff, 0x88, 0xcc, 0x8c, 0xc8, 0x8c, 0xc8,
0xcc, 0x88, 0xcc, 0x8c, 0xc8, 0x8c, 0xc8, 0xcc,
0x85, 0xff, 0xff, 0xf5,
/* U+F304 "" */
0x0, 0x0, 0x0, 0x7e, 0x30, 0x0, 0x0, 0x4b,
0xfe, 0x0, 0x0, 0x8f, 0x9b, 0x70, 0x0, 0x8f,
0xff, 0x40, 0x0, 0x8f, 0xff, 0x80, 0x0, 0x7f,
0xff, 0x80, 0x0, 0xe, 0xff, 0x80, 0x0, 0x0,
0xee, 0x70, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0,
/* U+F55A "" */
0x0, 0xaf, 0xff, 0xff, 0xfc, 0xb, 0xff, 0x9c,
0xc9, 0xff, 0xaf, 0xff, 0xc1, 0x1c, 0xff, 0xaf,
0xff, 0xc1, 0x1c, 0xff, 0xb, 0xff, 0x9c, 0xc9,
0xff, 0x0, 0xaf, 0xff, 0xff, 0xfc,
/* U+F7C2 "" */
0x7, 0xff, 0xfe, 0x17, 0xb6, 0x27, 0xc3, 0xfe,
0xb9, 0xbe, 0x3f, 0xff, 0xff, 0xf3, 0xff, 0xff,
0xff, 0x3f, 0xff, 0xff, 0xf3, 0xff, 0xff, 0xff,
0x3c, 0xff, 0xff, 0xe1,
/* U+F8A2 "" */
0x0, 0x0, 0x0, 0x3, 0x0, 0x23, 0x0, 0x2,
0xf0, 0x2e, 0x92, 0x22, 0x5f, 0xd, 0xff, 0xff,
0xff, 0xf0, 0x2e, 0x92, 0x22, 0x21, 0x0, 0x23,
0x0, 0x0, 0x0
};
/*---------------------
* GLYPH DESCRIPTION
*--------------------*/
static const lv_font_fmt_txt_glyph_dsc_t glyph_dsc[] = {
{.bitmap_index = 0, .adv_w = 0, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0} /* id = 0 reserved */,
{.bitmap_index = 0, .adv_w = 34, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 0, .adv_w = 34, .box_w = 2, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 5, .adv_w = 50, .box_w = 3, .box_h = 3, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 10, .adv_w = 90, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 25, .adv_w = 79, .box_w = 5, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 43, .adv_w = 108, .box_w = 7, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 61, .adv_w = 88, .box_w = 6, .box_h = 6, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 79, .adv_w = 27, .box_w = 2, .box_h = 3, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 82, .adv_w = 43, .box_w = 3, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 93, .adv_w = 43, .box_w = 2, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 100, .adv_w = 51, .box_w = 4, .box_h = 3, .ofs_x = 0, .ofs_y = 3},
{.bitmap_index = 106, .adv_w = 74, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 116, .adv_w = 29, .box_w = 2, .box_h = 3, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 119, .adv_w = 49, .box_w = 3, .box_h = 1, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 121, .adv_w = 29, .box_w = 2, .box_h = 2, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 123, .adv_w = 45, .box_w = 5, .box_h = 7, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 141, .adv_w = 85, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 154, .adv_w = 47, .box_w = 3, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 162, .adv_w = 73, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 175, .adv_w = 73, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 188, .adv_w = 86, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 203, .adv_w = 73, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 216, .adv_w = 79, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 229, .adv_w = 77, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 242, .adv_w = 82, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 255, .adv_w = 79, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 268, .adv_w = 29, .box_w = 2, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 272, .adv_w = 29, .box_w = 2, .box_h = 6, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 278, .adv_w = 74, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 291, .adv_w = 74, .box_w = 5, .box_h = 3, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 299, .adv_w = 74, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 312, .adv_w = 73, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 325, .adv_w = 132, .box_w = 8, .box_h = 6, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 349, .adv_w = 94, .box_w = 7, .box_h = 5, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 367, .adv_w = 97, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 382, .adv_w = 93, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 397, .adv_w = 106, .box_w = 7, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 415, .adv_w = 86, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 428, .adv_w = 81, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 441, .adv_w = 99, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 456, .adv_w = 104, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 471, .adv_w = 40, .box_w = 2, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 476, .adv_w = 66, .box_w = 5, .box_h = 5, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 489, .adv_w = 92, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 504, .adv_w = 76, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 517, .adv_w = 122, .box_w = 7, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 535, .adv_w = 104, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 550, .adv_w = 108, .box_w = 7, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 568, .adv_w = 92, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 583, .adv_w = 108, .box_w = 7, .box_h = 6, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 604, .adv_w = 93, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 619, .adv_w = 79, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 632, .adv_w = 75, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 645, .adv_w = 101, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 660, .adv_w = 91, .box_w = 7, .box_h = 5, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 678, .adv_w = 144, .box_w = 9, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 701, .adv_w = 86, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 716, .adv_w = 83, .box_w = 7, .box_h = 5, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 734, .adv_w = 84, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 749, .adv_w = 43, .box_w = 3, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 760, .adv_w = 45, .box_w = 5, .box_h = 7, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 778, .adv_w = 43, .box_w = 2, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 785, .adv_w = 75, .box_w = 5, .box_h = 3, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 793, .adv_w = 64, .box_w = 4, .box_h = 1, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 795, .adv_w = 77, .box_w = 3, .box_h = 1, .ofs_x = 0, .ofs_y = 5},
{.bitmap_index = 797, .adv_w = 77, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 807, .adv_w = 87, .box_w = 6, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 825, .adv_w = 73, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 835, .adv_w = 87, .box_w = 5, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 850, .adv_w = 78, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 860, .adv_w = 45, .box_w = 4, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 872, .adv_w = 88, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 885, .adv_w = 87, .box_w = 5, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 900, .adv_w = 36, .box_w = 2, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 906, .adv_w = 36, .box_w = 3, .box_h = 7, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 917, .adv_w = 79, .box_w = 5, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 932, .adv_w = 36, .box_w = 2, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 938, .adv_w = 135, .box_w = 8, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 954, .adv_w = 87, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 964, .adv_w = 81, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 974, .adv_w = 87, .box_w = 6, .box_h = 5, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 989, .adv_w = 87, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1002, .adv_w = 52, .box_w = 4, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1010, .adv_w = 64, .box_w = 4, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1018, .adv_w = 53, .box_w = 4, .box_h = 5, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1028, .adv_w = 87, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1038, .adv_w = 72, .box_w = 6, .box_h = 4, .ofs_x = -1, .ofs_y = 0},
{.bitmap_index = 1050, .adv_w = 115, .box_w = 8, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1066, .adv_w = 71, .box_w = 5, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1076, .adv_w = 72, .box_w = 6, .box_h = 5, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 1091, .adv_w = 67, .box_w = 4, .box_h = 4, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1099, .adv_w = 45, .box_w = 3, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1110, .adv_w = 38, .box_w = 2, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1117, .adv_w = 45, .box_w = 3, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1128, .adv_w = 74, .box_w = 5, .box_h = 2, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 1133, .adv_w = 54, .box_w = 3, .box_h = 3, .ofs_x = 0, .ofs_y = 3},
{.bitmap_index = 1138, .adv_w = 40, .box_w = 2, .box_h = 3, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 1141, .adv_w = 128, .box_w = 8, .box_h = 9, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1177, .adv_w = 128, .box_w = 8, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1201, .adv_w = 128, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1233, .adv_w = 128, .box_w = 8, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1257, .adv_w = 88, .box_w = 6, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1275, .adv_w = 128, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1307, .adv_w = 128, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1339, .adv_w = 144, .box_w = 9, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1375, .adv_w = 128, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1407, .adv_w = 144, .box_w = 9, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1434, .adv_w = 128, .box_w = 8, .box_h = 10, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 1474, .adv_w = 64, .box_w = 4, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1488, .adv_w = 96, .box_w = 6, .box_h = 7, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1509, .adv_w = 144, .box_w = 9, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1545, .adv_w = 128, .box_w = 8, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1569, .adv_w = 112, .box_w = 5, .box_h = 8, .ofs_x = 1, .ofs_y = -1},
{.bitmap_index = 1589, .adv_w = 112, .box_w = 7, .box_h = 10, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 1624, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1652, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1680, .adv_w = 112, .box_w = 5, .box_h = 8, .ofs_x = 1, .ofs_y = -1},
{.bitmap_index = 1700, .adv_w = 112, .box_w = 9, .box_h = 8, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 1736, .adv_w = 80, .box_w = 5, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1756, .adv_w = 80, .box_w = 5, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1776, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1804, .adv_w = 112, .box_w = 7, .box_h = 2, .ofs_x = 0, .ofs_y = 2},
{.bitmap_index = 1811, .adv_w = 144, .box_w = 9, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1838, .adv_w = 160, .box_w = 11, .box_h = 8, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 1882, .adv_w = 144, .box_w = 11, .box_h = 8, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 1926, .adv_w = 128, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1958, .adv_w = 112, .box_w = 7, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1979, .adv_w = 112, .box_w = 7, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2000, .adv_w = 160, .box_w = 11, .box_h = 7, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 2039, .adv_w = 128, .box_w = 8, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2063, .adv_w = 128, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2095, .adv_w = 128, .box_w = 9, .box_h = 9, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 2136, .adv_w = 112, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2168, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2196, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2224, .adv_w = 80, .box_w = 7, .box_h = 8, .ofs_x = -1, .ofs_y = -1},
{.bitmap_index = 2252, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2280, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2308, .adv_w = 144, .box_w = 9, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2335, .adv_w = 128, .box_w = 10, .box_h = 10, .ofs_x = -1, .ofs_y = -2},
{.bitmap_index = 2385, .adv_w = 96, .box_w = 6, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2409, .adv_w = 160, .box_w = 10, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2449, .adv_w = 160, .box_w = 10, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2479, .adv_w = 160, .box_w = 10, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2509, .adv_w = 160, .box_w = 10, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2539, .adv_w = 160, .box_w = 10, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2569, .adv_w = 160, .box_w = 10, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2599, .adv_w = 160, .box_w = 11, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2643, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2671, .adv_w = 112, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2699, .adv_w = 128, .box_w = 9, .box_h = 9, .ofs_x = -1, .ofs_y = -2},
{.bitmap_index = 2740, .adv_w = 160, .box_w = 10, .box_h = 6, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2770, .adv_w = 96, .box_w = 7, .box_h = 8, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 2798, .adv_w = 129, .box_w = 9, .box_h = 6, .ofs_x = 0, .ofs_y = 0}
};
/*---------------------
* CHARACTER MAPPING
*--------------------*/
static const uint16_t unicode_list_1[] = {
0x0, 0x1f72, 0xef51, 0xef58, 0xef5b, 0xef5c, 0xef5d, 0xef61,
0xef63, 0xef65, 0xef69, 0xef6c, 0xef71, 0xef76, 0xef77, 0xef78,
0xef8e, 0xef98, 0xef9b, 0xef9c, 0xef9d, 0xefa1, 0xefa2, 0xefa3,
0xefa4, 0xefb7, 0xefb8, 0xefbe, 0xefc0, 0xefc1, 0xefc4, 0xefc7,
0xefc8, 0xefc9, 0xefcb, 0xefe3, 0xefe5, 0xf014, 0xf015, 0xf017,
0xf037, 0xf03a, 0xf043, 0xf06c, 0xf074, 0xf0ab, 0xf13b, 0xf190,
0xf191, 0xf192, 0xf193, 0xf194, 0xf1d7, 0xf1e3, 0xf23d, 0xf254,
0xf4aa, 0xf712, 0xf7f2
};
/*Collect the unicode lists and glyph_id offsets*/
static const lv_font_fmt_txt_cmap_t cmaps[] =
{
{
.range_start = 32, .range_length = 95, .glyph_id_start = 1,
.unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
},
{
.range_start = 176, .range_length = 63475, .glyph_id_start = 96,
.unicode_list = unicode_list_1, .glyph_id_ofs_list = NULL, .list_length = 59, .type = LV_FONT_FMT_TXT_CMAP_SPARSE_TINY
}
};
/*-----------------
* KERNING
*----------------*/
/*Map glyph_ids to kern left classes*/
static const uint8_t kern_left_class_mapping[] =
{
0, 0, 1, 2, 0, 3, 4, 5,
2, 6, 7, 8, 9, 10, 9, 10,
11, 12, 0, 13, 14, 15, 16, 17,
18, 19, 12, 20, 20, 0, 0, 0,
21, 22, 23, 24, 25, 22, 26, 27,
28, 29, 29, 30, 31, 32, 29, 29,
22, 33, 34, 35, 3, 36, 30, 37,
37, 38, 39, 40, 41, 42, 43, 0,
44, 0, 45, 46, 47, 48, 49, 50,
51, 45, 52, 52, 53, 48, 45, 45,
46, 46, 54, 55, 56, 57, 51, 58,
58, 59, 58, 60, 41, 0, 0, 9,
61, 9, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0
};
/*Map glyph_ids to kern right classes*/
static const uint8_t kern_right_class_mapping[] =
{
0, 0, 1, 2, 0, 3, 4, 5,
2, 6, 7, 8, 9, 10, 9, 10,
11, 12, 13, 14, 15, 16, 17, 12,
18, 19, 20, 21, 21, 0, 0, 0,
22, 23, 24, 25, 23, 25, 25, 25,
23, 25, 25, 26, 25, 25, 25, 25,
23, 25, 23, 25, 3, 27, 28, 29,
29, 30, 31, 32, 33, 34, 35, 0,
36, 0, 37, 38, 39, 39, 39, 0,
39, 38, 40, 41, 38, 38, 42, 42,
39, 42, 39, 42, 43, 44, 45, 46,
46, 47, 46, 48, 0, 0, 35, 9,
49, 9, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0
};
/*Kern values between classes*/
static const int8_t kern_class_values[] =
{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6, 0, 3, -3, 0, 0,
0, 0, -7, -8, 1, 6, 3, 2,
-5, 1, 6, 0, 5, 1, 4, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 8, 1, -1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 3, 0, -4, 0, 0, 0, 0,
0, -3, 2, 3, 0, 0, -1, 0,
-1, 1, 0, -1, 0, -1, -1, -3,
0, 0, 0, 0, -1, 0, 0, -2,
-2, 0, 0, -1, 0, -3, 0, 0,
0, 0, 0, 0, 0, 0, 0, -1,
-1, 0, -2, 0, -3, 0, -15, 0,
0, -3, 0, 3, 4, 0, 0, -3,
1, 1, 4, 3, -2, 3, 0, 0,
-7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -5, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, -3, -2, -6, 0, -5,
-1, 0, 0, 0, 0, 0, 5, 0,
-4, -1, 0, 0, 0, -2, 0, 0,
-1, -9, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -10, -1, 5,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -5, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 4,
0, 1, 0, 0, -3, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 5, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-5, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1,
3, 1, 4, -1, 0, 0, 3, -1,
-4, -18, 1, 3, 3, 0, -2, 0,
5, 0, 4, 0, 4, 0, -12, 0,
-2, 4, 0, 4, -1, 3, 1, 0,
0, 0, -1, 0, 0, -2, 10, 0,
10, 0, 4, 0, 5, 2, 2, 4,
0, 0, 0, -5, 0, 0, 0, 0,
0, -1, 0, 1, -2, -2, -3, 1,
0, -1, 0, 0, 0, -5, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -8, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, -7, 0, -8, 0, 0, 0,
0, -1, 0, 13, -2, -2, 1, 1,
-1, 0, -2, 1, 0, 0, -7, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, -12, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -8, 0, 8, 0, 0, -5, 0,
4, 0, -9, -12, -9, -3, 4, 0,
0, -9, 0, 2, -3, 0, -2, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 3, 4, -16, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6, 0, 1, 0, 0, 0,
0, 0, 1, 1, -2, -3, 0, 0,
0, -1, 0, 0, -1, 0, 0, 0,
-3, 0, -1, 0, -3, -3, 0, -3,
-4, -4, -2, 0, -3, 0, -3, 0,
0, 0, 0, -1, 0, 0, 1, 0,
1, -1, 0, 0, 0, 0, 0, 1,
-1, 0, 0, 0, -1, 1, 1, 0,
0, 0, 0, -2, 0, 0, 0, 0,
0, 0, 0, 0, 0, 2, -1, 0,
-2, 0, -2, 0, 0, -1, 0, 4,
0, 0, -1, 0, 0, 0, 0, 0,
0, 0, -1, -1, 0, 0, -1, 0,
-1, 0, 0, 0, 0, 0, 0, 0,
0, 0, -1, -1, 0, -1, -2, 0,
0, 0, 0, 0, 0, 0, 0, -1,
0, -1, -1, -1, 0, 0, 0, 0,
0, 0, 0, 0, 0, -1, 0, 0,
0, 0, -1, -2, 0, -2, 0, -4,
-1, -4, 3, 0, 0, -3, 1, 3,
3, 0, -3, 0, -2, 0, 0, -6,
1, -1, 1, -7, 1, 0, 0, 0,
-7, 0, -7, -1, -11, -1, 0, -6,
0, 3, 4, 0, 2, 0, 0, 0,
0, 0, 0, -2, -2, 0, -4, 0,
0, 0, -1, 0, 0, 0, -1, 0,
0, 0, 0, 0, -1, -1, 0, -1,
-2, 0, 0, 0, 0, 0, 0, 0,
-1, -1, 0, -1, -2, -1, 0, 0,
-1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -1, -1, 0, -2,
0, -1, 0, -3, 1, 0, 0, -2,
1, 1, 1, 0, 0, 0, 0, 0,
0, -1, 0, 0, 0, 0, 0, 1,
0, 0, -1, 0, -1, -1, -2, 0,
0, 0, 0, 0, 0, 0, 1, 0,
-1, 0, 0, 0, 0, -1, -2, 0,
-2, 0, 4, -1, 0, -4, 0, 0,
3, -6, -7, -5, -3, 1, 0, -1,
-8, -2, 0, -2, 0, -3, 2, -2,
-8, 0, -3, 0, 0, 1, 0, 1,
-1, 0, 1, 0, -4, -5, 0, -6,
-3, -3, -3, -4, -2, -3, 0, -2,
-3, 1, 0, 0, 0, -1, 0, 0,
0, 1, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, -1,
0, -1, 0, 0, -1, 0, -2, -3,
-3, 0, 0, -4, 0, 0, 0, 0,
0, 0, -1, 0, 0, 0, 0, 1,
-1, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 6, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
-1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -2, 0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -1, 0, 0, 0,
-2, 0, 0, 0, 0, -6, -4, 0,
0, 0, -2, -6, 0, 0, -1, 1,
0, -3, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -2, 0, 0, -2,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, -2, 0,
0, 0, 0, 2, 0, 1, -3, -3,
0, -1, -1, -2, 0, 0, 0, 0,
0, 0, -4, 0, -1, 0, -2, -1,
0, -3, -3, -4, -1, 0, -3, 0,
-4, 0, 0, 0, 0, 10, 0, 0,
1, 0, 0, -2, 0, 1, 0, -6,
0, 0, 0, 0, 0, -12, -2, 4,
4, -1, -5, 0, 1, -2, 0, -6,
-1, -2, 1, -9, -1, 2, 0, 2,
-4, -2, -5, -4, -5, 0, 0, -8,
0, 7, 0, 0, -1, 0, 0, 0,
-1, -1, -1, -3, -4, 0, -12, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -1, 0, -1, -1, -2, 0, 0,
-3, 0, -1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -3, 0, 0, 3,
0, 2, 0, -3, 1, -1, 0, -3,
-1, 0, -2, -1, -1, 0, -2, -2,
0, 0, -1, 0, -1, -2, -2, 0,
0, -1, 0, 1, -1, 0, -3, 0,
0, 0, -3, 0, -2, 0, -2, -2,
1, 0, 0, 0, 0, 0, 0, 0,
0, -3, 1, 0, -2, 0, -1, -2,
-4, -1, -1, -1, 0, -1, -2, 0,
0, 0, 0, 0, 0, -1, -1, -1,
0, 0, 0, 0, 2, -1, 0, -1,
0, 0, 0, -1, -2, -1, -1, -2,
-1, 0, 1, 5, 0, 0, -3, 0,
-1, 3, 0, -1, -5, -2, 2, 0,
0, -6, -2, 1, -2, 1, 0, -1,
-1, -4, 0, -2, 1, 0, 0, -2,
0, 0, 0, 1, 1, -3, -2, 0,
-2, -1, -2, -1, -1, 0, -2, 1,
-2, -2, 4, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -2, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, -1, -1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -2, 0, 0, -2,
0, 0, -1, -1, 0, 0, 0, 0,
-1, 0, 0, 0, 0, -1, 0, 0,
0, 0, 0, -1, 0, 0, 0, 0,
-2, 0, -3, 0, 0, 0, -4, 0,
1, -3, 3, 0, -1, -6, 0, 0,
-3, -1, 0, -5, -3, -4, 0, 0,
-6, -1, -5, -5, -6, 0, -3, 0,
1, 9, -2, 0, -3, -1, 0, -1,
-2, -3, -2, -5, -5, -3, -1, 0,
0, -1, 0, 0, 0, 0, -9, -1,
4, 3, -3, -5, 0, 0, -4, 0,
-6, -1, -1, 3, -12, -2, 0, 0,
0, -8, -2, -7, -1, -9, 0, 0,
-9, 0, 8, 0, 0, -1, 0, 0,
0, 0, -1, -1, -5, -1, 0, -8,
0, 0, 0, 0, -4, 0, -1, 0,
0, -4, -6, 0, 0, -1, -2, -4,
-1, 0, -1, 0, 0, 0, 0, -6,
-1, -4, -4, -1, -2, -3, -1, -2,
0, -3, -1, -4, -2, 0, -2, -2,
-1, -2, 0, 1, 0, -1, -4, 0,
3, 0, -2, 0, 0, 0, 0, 2,
0, 1, -3, 5, 0, -1, -1, -2,
0, 0, 0, 0, 0, 0, -4, 0,
-1, 0, -2, -1, 0, -3, -3, -4,
-1, 0, -3, 1, 5, 0, 0, 0,
0, 10, 0, 0, 1, 0, 0, -2,
0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-1, -3, 0, 0, 0, 0, 0, -1,
0, 0, 0, -1, -1, 0, 0, -3,
-1, 0, 0, -3, 0, 2, -1, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 2, 3, 1, -1, 0, -4,
-2, 0, 4, -4, -4, -3, -3, 5,
2, 1, -11, -1, 3, -1, 0, -1,
1, -1, -4, 0, -1, 1, -2, -1,
-4, -1, 0, 0, 4, 3, 0, -4,
0, -7, -2, 4, -2, -5, 0, -2,
-4, -4, -1, 5, 1, 0, -2, 0,
-3, 0, 1, 4, -3, -5, -5, -3,
4, 0, 0, -9, -1, 1, -2, -1,
-3, 0, -3, -5, -2, -2, -1, 0,
0, -3, -3, -1, 0, 4, 3, -1,
-7, 0, -7, -2, 0, -4, -7, 0,
-4, -2, -4, -4, 3, 0, 0, -2,
0, -3, -1, 0, -1, -2, 0, 2,
-4, 1, 0, 0, -7, 0, -1, -3,
-2, -1, -4, -3, -4, -3, 0, -4,
-1, -3, -2, -4, -1, 0, 0, 0,
6, -2, 0, -4, -1, 0, -1, -3,
-3, -3, -4, -5, -2, -3, 3, 0,
-2, 0, -6, -2, 1, 3, -4, -5,
-3, -4, 4, -1, 1, -12, -2, 3,
-3, -2, -5, 0, -4, -5, -2, -1,
-1, -1, -3, -4, 0, 0, 0, 4,
4, -1, -8, 0, -8, -3, 3, -5,
-9, -3, -4, -5, -6, -4, 3, 0,
0, 0, 0, -2, 0, 0, 1, -2,
3, 1, -2, 3, 0, 0, -4, 0,
0, 0, 0, 0, 0, -1, 0, 0,
0, 0, 0, 0, -1, 0, 0, 0,
0, 1, 4, 0, 0, -2, 0, 0,
0, 0, -1, -1, -2, 0, 0, 0,
0, 1, 0, 0, 0, 0, 1, 0,
-1, 0, 5, 0, 2, 0, 0, -2,
0, 3, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 4, 0, 4, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, -8, 0, -1, 2, 0, 4,
0, 0, 13, 2, -3, -3, 1, 1,
-1, 0, -6, 0, 0, 6, -8, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, -9, 5, 18, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -8, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -2, 0, 0, -2,
-1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -1, 0, -3, 0,
0, 0, 0, 0, 1, 17, -3, -1,
4, 3, -3, 1, 0, 0, 1, 1,
-2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -17, 4, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, -4,
0, 0, 0, -3, 0, 0, 0, 0,
-3, -1, 0, 0, 0, -3, 0, -2,
0, -6, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -9, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -1, 0, 0, -2, 0, -2, 0,
-3, 0, 0, 0, -2, 1, -2, 0,
0, -3, -1, -3, 0, 0, -3, 0,
-1, 0, -6, 0, -1, 0, 0, -10,
-2, -5, -1, -5, 0, 0, -9, 0,
-3, -1, 0, 0, 0, 0, 0, 0,
0, 0, -2, -2, -1, -2, 0, 0,
0, 0, -3, 0, -3, 2, -1, 3,
0, -1, -3, -1, -2, -2, 0, -2,
-1, -1, 1, -3, 0, 0, 0, 0,
-11, -1, -2, 0, -3, 0, -1, -6,
-1, 0, 0, -1, -1, 0, 0, 0,
0, 1, 0, -1, -2, -1, 2, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 2, 0, 0, 0, 0, 0,
0, -3, 0, -1, 0, 0, 0, -3,
1, 0, 0, 0, -3, -1, -3, 0,
0, -4, 0, -1, 0, -6, 0, 0,
0, 0, -12, 0, -3, -5, -6, 0,
0, -9, 0, -1, -2, 0, 0, 0,
0, 0, 0, 0, 0, -1, -2, -1,
-2, 0, 0, 0, 2, -2, 0, 4,
6, -1, -1, -4, 2, 6, 2, 3,
-3, 2, 5, 2, 4, 3, 3, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 8, 6, -2, -1, 0, -1,
10, 6, 10, 0, 0, 0, 1, 0,
0, 5, 0, 0, -2, 0, 0, 0,
0, 0, 0, 0, 0, 0, -1, 0,
0, 0, 0, 0, 0, 0, 0, 2,
0, 0, 0, 0, -11, -2, -1, -5,
-6, 0, 0, -9, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -2, 0, 0,
0, 0, 0, 0, 0, 0, 0, -1,
0, 0, 0, 0, 0, 0, 0, 0,
2, 0, 0, 0, 0, -11, -2, -1,
-5, -6, 0, 0, -5, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-1, 0, 0, 0, -3, 1, 0, -1,
1, 2, 1, -4, 0, 0, -1, 1,
0, 1, 0, 0, 0, 0, -3, 0,
-1, -1, -3, 0, -1, -5, 0, 8,
-1, 0, -3, -1, 0, -1, -2, 0,
-1, -4, -3, -2, 0, 0, 0, -2,
0, 0, 0, 0, 0, 0, 0, 0,
0, -1, 0, 0, 0, 0, 0, 0,
0, 0, 2, 0, 0, 0, 0, -11,
-2, -1, -5, -6, 0, 0, -9, 0,
0, 0, 0, 0, 0, 6, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-2, 0, -4, -2, -1, 4, -1, -1,
-5, 0, -1, 0, -1, -3, 0, 3,
0, 1, 0, 1, -3, -5, -2, 0,
-5, -2, -3, -5, -5, 0, -2, -3,
-2, -2, -1, -1, -2, -1, 0, -1,
0, 2, 0, 2, -1, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, -1, -1, -1, 0, 0,
-3, 0, -1, 0, -2, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
-8, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -1, -1, 0, -2,
0, 0, 0, 0, -1, 0, 0, -2,
-1, 1, 0, -2, -2, -1, 0, -4,
-1, -3, -1, -2, 0, -2, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, -9, 0, 4, 0, 0, -2, 0,
0, 0, 0, -2, 0, -1, 0, 0,
-1, 0, 0, -1, 0, -3, 0, 0,
5, -2, -4, -4, 1, 1, 1, 0,
-4, 1, 2, 1, 4, 1, 4, -1,
-3, 0, 0, -5, 0, 0, -4, -3,
0, 0, -3, 0, -2, -2, 0, -2,
0, -2, 0, -1, 2, 0, -1, -4,
-1, 5, 0, 0, -1, 0, -3, 0,
0, 2, -3, 0, 1, -1, 1, 0,
0, -4, 0, -1, 0, 0, -1, 1,
-1, 0, 0, 0, -5, -2, -3, 0,
-4, 0, 0, -6, 0, 5, -1, 0,
-2, 0, 1, 0, -1, 0, -1, -4,
0, -1, 1, 0, 0, 0, 0, -1,
0, 0, 1, -2, 0, 0, 0, -2,
-1, 0, -2, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -8, 0, 3, 0,
0, -1, 0, 0, 0, 0, 0, 0,
-1, -1, 0, 0, 0, 3, 0, 3,
0, 0, 0, 0, 0, -8, -7, 0,
6, 4, 2, -5, 1, 5, 0, 5,
0, 3, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 7, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0
};
/*Collect the kern class' data in one place*/
static const lv_font_fmt_txt_kern_classes_t kern_classes =
{
.class_pair_values = kern_class_values,
.left_class_mapping = kern_left_class_mapping,
.right_class_mapping = kern_right_class_mapping,
.left_class_cnt = 61,
.right_class_cnt = 49,
};
/*--------------------
* ALL CUSTOM DATA
*--------------------*/
/*Store all the custom data of the font*/
static lv_font_fmt_txt_dsc_t font_dsc = {
.glyph_bitmap = gylph_bitmap,
.glyph_dsc = glyph_dsc,
.cmaps = cmaps,
.kern_dsc = &kern_classes,
.kern_scale = 16,
.cmap_num = 2,
.bpp = 4,
.kern_classes = 1,
.bitmap_format = 0
};
/*-----------------
* PUBLIC FONT
*----------------*/
/*Initialize a public general font descriptor*/
lv_font_t font_2 = {
.get_glyph_dsc = lv_font_get_glyph_dsc_fmt_txt, /*Function pointer to get glyph's data*/
.get_glyph_bitmap = lv_font_get_bitmap_fmt_txt, /*Function pointer to get glyph's bitmap*/
.line_height = 10, /*The maximum line height required by the font*/
.base_line = 2, /*Baseline measured from the bottom of the line*/
#if !(LVGL_VERSION_MAJOR == 6 && LVGL_VERSION_MINOR == 0)
.subpx = LV_FONT_SUBPX_NONE,
#endif
.dsc = &font_dsc /*The custom font data. Will be accessed by `get_glyph_bitmap/dsc` */
};
#endif /*#if FONT_2*/
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/test_fonts/font_2.c | C | apache-2.0 | 51,460 |
#if LV_BUILD_TEST
#include "../../lvgl.h"
/*******************************************************************************
* Size: 20 px
* Bpp: 4
* Opts: --bpp 4 --size 20 --font ../RobotoMono-Regular.ttf -r 0x20-0x7f --format lvgl -o ..\generated_fonts/font_3.c
******************************************************************************/
#ifndef FONT_3
#define FONT_3 1
#endif
#if FONT_3
/*-----------------
* BITMAPS
*----------------*/
/*Store the image of the glyphs*/
static LV_ATTRIBUTE_LARGE_CONST const uint8_t gylph_bitmap[] = {
/* U+20 " " */
/* U+21 "!" */
0x1f, 0xb0, 0xf, 0xfe, 0x69, 0x10, 0x76, 0x40,
0x30, 0x81, 0x76, 0x98, 0xb0,
/* U+22 "\"" */
0x8e, 0x0, 0x7b, 0x0, 0x7c, 0x60, 0x11, 0x80,
0x80, 0x43, 0xca, 0x0, 0x37,
/* U+23 "#" */
0x0, 0xc5, 0xe6, 0x7, 0xe6, 0x1, 0xc8, 0x6,
0xa, 0x6, 0x1, 0xde, 0x40, 0xf, 0x30, 0xf,
0x2a, 0x0, 0x15, 0x40, 0x15, 0x7f, 0x8d, 0xbf,
0xc6, 0xde, 0xe1, 0xd2, 0xe0, 0xf2, 0xe0, 0xf2,
0x80, 0x8d, 0x81, 0x2d, 0xa1, 0x2c, 0x60, 0x11,
0x88, 0x80, 0x84, 0x40, 0x1d, 0xc4, 0x0, 0xd2,
0x0, 0xc2, 0x25, 0x61, 0x13, 0x30, 0x40, 0xd,
0xdc, 0x35, 0xee, 0x1a, 0xf6, 0x3, 0xdd, 0x4,
0x5c, 0x84, 0xdf, 0x80, 0xa0, 0x1, 0x90, 0xc1,
0x90, 0xc0, 0x2d, 0x21, 0xd, 0x20, 0xf, 0x1b,
0x80, 0x11, 0x0, 0x18,
/* U+24 "$" */
0x0, 0xcb, 0xe2, 0x1, 0xff, 0xc4, 0x78, 0xb,
0x40, 0xd, 0xb0, 0x64, 0xb6, 0xe0, 0x8, 0x27,
0xed, 0xd0, 0xc0, 0x82, 0x4, 0x0, 0xa, 0x41,
0xc0, 0x40, 0x38, 0xc8, 0x0, 0xe0, 0xe0, 0x12,
0x6b, 0x5, 0x84, 0x5a, 0x0, 0x70, 0xe9, 0xa5,
0xea, 0x80, 0x62, 0xcc, 0x29, 0x54, 0x80, 0x71,
0xd6, 0x93, 0x21, 0x29, 0x0, 0x45, 0x21, 0xaf,
0x4a, 0x1, 0x9c, 0xd, 0x2, 0x44, 0x2, 0xa0,
0xd1, 0x71, 0xf8, 0x86, 0x31, 0x38, 0x44, 0x9b,
0xb8, 0x97, 0x0, 0x26, 0xd6, 0x1e, 0xa1, 0x0,
0xe1, 0x0, 0xe0,
/* U+25 "%" */
0x7, 0xee, 0x40, 0x7, 0xc9, 0x10, 0xb7, 0x50,
0xf, 0x61, 0x32, 0xa7, 0x80, 0xf1, 0x80, 0x42,
0x1, 0xd2, 0x66, 0x0, 0x69, 0x98, 0x97, 0x45,
0xe0, 0x2, 0x55, 0x66, 0xab, 0xc1, 0x28, 0x6,
0xae, 0xe5, 0x8b, 0x48, 0x7, 0x84, 0x41, 0x6,
0x80, 0x1f, 0x89, 0xa0, 0x3, 0xfa, 0x11, 0x13,
0xdc, 0x70, 0xc, 0x6b, 0xc, 0xca, 0x88, 0x20,
0x5, 0x8, 0x78, 0xa8, 0xc5, 0x80, 0x13, 0x40,
0x7, 0xfb, 0x4c, 0x31, 0x51, 0x8b, 0x0, 0x3c,
0xcc, 0xa8, 0x82, 0x0,
/* U+26 "&" */
0x0, 0x26, 0x7e, 0xb0, 0x7, 0x15, 0x9b, 0xc,
0xa8, 0x6, 0xa0, 0xa9, 0xc1, 0xe0, 0xc, 0x40,
0xe0, 0x13, 0x80, 0x63, 0x7, 0x6, 0x1b, 0x0,
0xd4, 0x12, 0xf2, 0xae, 0x1, 0x8d, 0x8e, 0x1a,
0x80, 0x38, 0x90, 0x1, 0x40, 0x1c, 0x38, 0x50,
0x1a, 0x20, 0xbc, 0x70, 0x32, 0xf2, 0x34, 0x1a,
0x22, 0x40, 0x60, 0x65, 0x47, 0x51, 0x23, 0x10,
0xa, 0x8a, 0xa, 0x41, 0x5, 0x0, 0x2a, 0x0,
0x30, 0x40, 0x5d, 0x45, 0xc0, 0x84, 0x1, 0x6a,
0xa3, 0xb4, 0x71, 0xb2, 0x0,
/* U+27 "'" */
0x2f, 0x50, 0xe, 0x10, 0x3, 0x81, 0x88,
/* U+28 "(" */
0x0, 0xe1, 0x0, 0xd9, 0x20, 0x15, 0x8c, 0x80,
0x1d, 0x38, 0x40, 0x10, 0xa6, 0x0, 0x70, 0x90,
0xa, 0xc4, 0xc0, 0x2, 0x68, 0x1, 0x28, 0x68,
0x4, 0x40, 0x20, 0x10, 0x81, 0x80, 0x70, 0x80,
0x42, 0x2, 0x1, 0x18, 0x18, 0x4, 0xe1, 0xe0,
0x11, 0xa, 0x80, 0x67, 0x31, 0x0, 0xac, 0x24,
0x2, 0x25, 0x60, 0xd, 0x61, 0x40, 0x10, 0xea,
0xb8, 0x4, 0x7a, 0x80,
/* U+29 ")" */
0x20, 0xe, 0xe9, 0x0, 0xde, 0xd0, 0x1, 0x1c,
0x39, 0x80, 0x4e, 0x5e, 0x1, 0xa8, 0xcc, 0x1,
0x28, 0x50, 0x4, 0x42, 0x80, 0x19, 0x48, 0x40,
0x21, 0x2, 0x0, 0x8c, 0x1c, 0x2, 0x10, 0xe,
0x10, 0x70, 0x8, 0xc0, 0x80, 0x27, 0x11, 0x0,
0x44, 0x80, 0x12, 0x87, 0x80, 0x5c, 0x2a, 0x0,
0x34, 0x80, 0xb, 0x8d, 0x80, 0x14, 0x1a, 0x1,
0x7e, 0x8, 0x4,
/* U+2A "*" */
0x0, 0xd3, 0xe2, 0x1, 0xf0, 0x80, 0x80, 0x61,
0x0, 0x78, 0x6, 0x12, 0xeb, 0x41, 0x10, 0x36,
0xc0, 0xaa, 0xae, 0x47, 0xe4, 0xc0, 0xeb, 0xb0,
0x0, 0xdb, 0xd2, 0x1, 0x50, 0xab, 0x98, 0x6,
0x66, 0x45, 0x8d, 0x0, 0x43, 0x24, 0xc3, 0x8,
0xe0, 0x1, 0xbe, 0x0, 0x3b, 0xc0,
/* U+2B "+" */
0x0, 0xd1, 0x0, 0xf, 0xca, 0xc0, 0x1f, 0xfd,
0x6d, 0xff, 0x88, 0x7f, 0xee, 0x62, 0x28, 0x0,
0x45, 0xaf, 0x76, 0x21, 0xdd, 0xb0, 0x3, 0xff,
0xa4,
/* U+2C "," */
0xa, 0xf4, 0x1, 0x0, 0x9c, 0x18, 0x8, 0x49,
0x46, 0x1, 0x69, 0x80,
/* U+2D "-" */
0x78, 0x8f, 0x25, 0x3b, 0xfb, 0x40,
/* U+2E "." */
0x8, 0xc3, 0x17, 0x39, 0x14, 0xf,
/* U+2F "/" */
0x0, 0xf6, 0x68, 0x7, 0x88, 0xe8, 0x3, 0xd4,
0xc, 0x1, 0xe6, 0x41, 0x0, 0xe4, 0x1e, 0x0,
0xf7, 0x2, 0x80, 0x79, 0x58, 0x3, 0xcc, 0x14,
0x1, 0xed, 0x23, 0x0, 0xe1, 0x4a, 0x0, 0xf3,
0x2, 0x80, 0x7a, 0x90, 0x80, 0x38, 0xcb, 0x40,
0x3d, 0x40, 0xc0, 0x1e, 0x65, 0x0, 0xf2, 0x87,
0x0, 0x78,
/* U+30 "0" */
0x0, 0x25, 0xff, 0xb1, 0x0, 0x25, 0xb5, 0x66,
0x15, 0xa8, 0x2, 0xc7, 0xe6, 0x5e, 0x34, 0x8,
0x32, 0x20, 0x1, 0x90, 0x53, 0x2, 0x0, 0xc2,
0x1b, 0xe0, 0xc0, 0x14, 0x48, 0x8, 0x80, 0x21,
0xb7, 0x50, 0xe, 0x3c, 0x4b, 0x80, 0xd, 0x58,
0x1a, 0x80, 0x10, 0x83, 0x2e, 0x90, 0x8, 0x3,
0xc1, 0xe8, 0x3, 0x84, 0xc3, 0xc0, 0x32, 0x86,
0xa0, 0xc8, 0x80, 0x56, 0xa, 0x16, 0x3f, 0x32,
0xe2, 0x90, 0x2, 0xda, 0xb3, 0xa, 0xd8, 0x0,
/* U+31 "1" */
0x0, 0xc4, 0x80, 0x6, 0xcd, 0xc9, 0xf9, 0x30,
0x3, 0x25, 0xd8, 0x1, 0xd6, 0x8e, 0x0, 0x10,
0xf, 0xff, 0x78,
/* U+32 "2" */
0x0, 0xc, 0xf7, 0xf4, 0x0, 0x62, 0xf6, 0x56,
0x27, 0xd0, 0xa, 0x46, 0xed, 0x38, 0xa4, 0xe0,
0x4, 0x34, 0x0, 0xa0, 0x30, 0x5, 0xe4, 0x3,
0x18, 0x4, 0x30, 0xa0, 0x19, 0x3, 0x0, 0x3f,
0x40, 0x30, 0x7, 0xd2, 0x52, 0x20, 0x1e, 0x76,
0x56, 0x0, 0xf2, 0x41, 0xd0, 0x7, 0x8e, 0xcb,
0x40, 0x3c, 0x3a, 0x3e, 0x20, 0x1e, 0xc1, 0xd2,
0x0, 0xf5, 0x91, 0xa3, 0xbf, 0x18, 0x28, 0x1c,
0x47, 0x94,
/* U+33 "3" */
0x0, 0xc, 0xf7, 0xf4, 0x0, 0x43, 0xec, 0xae,
0xaf, 0xa0, 0xb, 0x1a, 0xb8, 0xb7, 0x26, 0x4,
0x15, 0x0, 0xa8, 0x30, 0x3b, 0x80, 0x1f, 0xfc,
0x2b, 0xf, 0x0, 0x85, 0xe7, 0x59, 0xd4, 0x2,
0x38, 0x62, 0x1c, 0x0, 0xc5, 0xfe, 0xb3, 0xb4,
0x0, 0xf2, 0x78, 0x78, 0x8, 0x80, 0x31, 0xa,
0x87, 0x60, 0x7, 0x9, 0x81, 0x92, 0x0, 0x4c,
0x8, 0x1c, 0x17, 0x68, 0xb9, 0x28, 0x2, 0xe6,
0x57, 0x57, 0xd1,
/* U+34 "4" */
0x0, 0xf1, 0xff, 0x80, 0x3f, 0x78, 0x7, 0xf3,
0x18, 0x7, 0xe1, 0x94, 0x30, 0xf, 0xac, 0x28,
0x3, 0xe4, 0x58, 0x10, 0xf, 0xa4, 0x9c, 0x3,
0xe7, 0x29, 0x0, 0xf8, 0xa1, 0x50, 0x3, 0xe9,
0xb, 0x0, 0xf8, 0xd0, 0x3b, 0xfe, 0x30, 0xff,
0xc, 0x47, 0x84, 0x1e, 0x9, 0xdf, 0xc4, 0x10,
0xe0, 0x1f, 0xfc, 0xa0,
/* U+35 "5" */
0x0, 0x7f, 0xfc, 0xa0, 0x20, 0x26, 0x7c, 0x20,
0x60, 0xd9, 0x9c, 0x80, 0xc1, 0xc0, 0x1f, 0x8,
0x18, 0x7, 0xc4, 0x7, 0x15, 0x6, 0x1, 0x78,
0x4b, 0xab, 0xe3, 0x80, 0x38, 0xa7, 0xb9, 0x21,
0x4, 0xd, 0xac, 0x22, 0x68, 0xa, 0x0, 0xf9,
0x40, 0xc0, 0x3e, 0x30, 0x0, 0xfd, 0x80, 0x62,
0x2, 0x13, 0x43, 0x0, 0xa0, 0x30, 0x38, 0x32,
0xa7, 0x51, 0xa, 0x5, 0xaa, 0x8c, 0xf, 0x60,
/* U+36 "6" */
0x0, 0x86, 0x37, 0xd4, 0x3, 0x27, 0x39, 0xa3,
0x0, 0x45, 0x61, 0x5d, 0x66, 0x1, 0x48, 0x52,
0x80, 0x70, 0xa1, 0xa8, 0x7, 0x90, 0x2c, 0x59,
0xd4, 0x2, 0x20, 0xde, 0x98, 0xad, 0x10, 0xe0,
0x58, 0xee, 0x31, 0x50, 0x5, 0xe, 0x22, 0x92,
0x41, 0x0, 0x20, 0x6, 0x50, 0x51, 0x6, 0x0,
0xde, 0x3, 0x81, 0xa0, 0x1b, 0x41, 0x90, 0x9c,
0x80, 0x4, 0xa2, 0x61, 0xc1, 0xb5, 0x4d, 0xa,
0x0, 0x1e, 0x22, 0xa9, 0x31, 0x0,
/* U+37 "7" */
0xef, 0xff, 0xd6, 0xec, 0xde, 0x40, 0x39, 0x9f,
0x88, 0x24, 0x3, 0xc2, 0xca, 0x20, 0x1e, 0x60,
0x90, 0xf, 0xa4, 0x8c, 0x3, 0xca, 0x36, 0x1,
0xf4, 0x8b, 0x0, 0x78, 0xcc, 0xc0, 0x1f, 0x48,
0x50, 0x7, 0x85, 0x50, 0x80, 0x3d, 0x21, 0xe0,
0x1f, 0x31, 0x20, 0x7, 0x98, 0x68, 0x3, 0xeb,
0x6, 0x0, 0xe0,
/* U+38 "8" */
0x0, 0x15, 0x77, 0xea, 0x80, 0x43, 0xaa, 0x8c,
0x15, 0x20, 0xb, 0xa, 0xa4, 0xe9, 0x31, 0x2,
0x2, 0x80, 0x54, 0x8, 0x6, 0x1, 0xf1, 0x82,
0x2, 0x80, 0x54, 0x8, 0x12, 0x75, 0x49, 0xd2,
0xa1, 0x0, 0x50, 0x2b, 0x11, 0xa0, 0x1, 0xe5,
0x77, 0xe8, 0xb0, 0x42, 0xa, 0x88, 0x16, 0xc9,
0x8c, 0x10, 0x3, 0x20, 0x60, 0x0, 0xc0, 0x31,
0x80, 0xc, 0x54, 0x80, 0x2b, 0xd, 0xa, 0xd,
0xa8, 0xc6, 0x36, 0x4, 0xc4, 0x57, 0x17, 0xc0,
/* U+39 "9" */
0x0, 0x26, 0x7f, 0x51, 0x0, 0x4d, 0x64, 0xca,
0xac, 0x10, 0x4, 0x8f, 0xcd, 0xc8, 0xd8, 0x28,
0x48, 0x80, 0x18, 0x94, 0x34, 0xc, 0x3, 0x28,
0x27, 0x80, 0x7b, 0x80, 0x48, 0xc, 0x3, 0x70,
0x1a, 0x4, 0x88, 0x0, 0xdc, 0xc, 0x5c, 0x7e,
0x6b, 0x4, 0x4, 0x22, 0x4d, 0x9e, 0x1c, 0x18,
0x0, 0xdb, 0xfa, 0xea, 0x24, 0x1, 0xe3, 0x33,
0x80, 0x79, 0x34, 0x60, 0x2, 0x5b, 0xeb, 0xd,
0x10, 0xb, 0x54, 0x9f, 0xcc, 0x0,
/* U+3A ":" */
0x5f, 0xb0, 0xf0, 0x42, 0x93, 0x62, 0x3c, 0x90,
0xf, 0xfe, 0x29, 0xe4, 0x4, 0x9b, 0x97, 0x81,
0x90,
/* U+3B ";" */
0x6, 0xfa, 0x0, 0x68, 0x28, 0x3, 0xcd, 0xc0,
0x9, 0x90, 0x1, 0xff, 0xcf, 0x4a, 0x60, 0x1,
0x2f, 0x0, 0x4, 0x3, 0x70, 0x60, 0x1, 0x9,
0x0, 0xf, 0xc0, 0x0,
/* U+3C "<" */
0x0, 0xf9, 0x2c, 0x3, 0x9b, 0x6d, 0x40, 0x2,
0xfd, 0x26, 0xd8, 0x33, 0xd0, 0x55, 0xd2, 0x48,
0xc3, 0x78, 0xa0, 0x12, 0x28, 0xdd, 0x20, 0x4,
0x35, 0xac, 0xb7, 0xae, 0x20, 0x2, 0x9e, 0x83,
0x8f, 0x0, 0xc2, 0xfd, 0x24, 0x1, 0xf3, 0x60,
/* U+3D "=" */
0x39, 0x9f, 0xc6, 0xec, 0xdf, 0x95, 0x3f, 0xff,
0x30, 0x7, 0xf8, 0xa6, 0x7f, 0x1b, 0x37, 0xf2,
0x80,
/* U+3E ">" */
0x3a, 0x30, 0xf, 0x9d, 0x73, 0xa, 0x1, 0xc9,
0x8c, 0x75, 0xae, 0x1, 0x8e, 0x7e, 0x9a, 0x3e,
0x44, 0x3, 0x2d, 0xe1, 0x32, 0x0, 0x65, 0xbc,
0x25, 0x40, 0x28, 0xea, 0x57, 0xea, 0x13, 0xd7,
0x39, 0xe8, 0x10, 0x3, 0xa5, 0xeb, 0x0, 0x72,
0x5a, 0x0, 0x7c,
/* U+3F "?" */
0x0, 0x1d, 0xf7, 0xea, 0x80, 0x4b, 0x88, 0xaa,
0x3a, 0x80, 0x5, 0x86, 0xdd, 0x78, 0xb8, 0x89,
0xe0, 0x80, 0x2, 0xe0, 0x43, 0x2e, 0x1, 0x8c,
0x4, 0x3, 0xc4, 0xa4, 0x40, 0xf, 0x70, 0x48,
0x7, 0xb0, 0xe1, 0x0, 0x3a, 0x4d, 0xdc, 0x1,
0xe7, 0x18, 0x0, 0xf8, 0x9c, 0x3, 0xf6, 0x48,
0x7, 0xe1, 0x10, 0x7, 0xc3, 0xde, 0x1, 0xf8,
0x48, 0x3, 0x0,
/* U+40 "@" */
0x0, 0xd1, 0xbf, 0xae, 0x1, 0xc3, 0xab, 0x76,
0xa9, 0xb0, 0xd, 0x4d, 0xac, 0x8f, 0xea, 0xc0,
0x4, 0x5b, 0x9, 0xfd, 0x3b, 0xb0, 0x3, 0xe4,
0x25, 0x2d, 0x95, 0x44, 0x20, 0x8a, 0x2d, 0xc8,
0x2, 0x4, 0x43, 0x2, 0x41, 0x30, 0x72, 0x1,
0x77, 0x8, 0x12, 0x80, 0x5, 0xc0, 0x21, 0x30,
0xe2, 0x0, 0x10, 0x80, 0xb0, 0x98, 0x0, 0xc0,
0x40, 0xc4, 0xc9, 0x44, 0x5e, 0x88, 0xa0, 0x29,
0x40, 0x12, 0x67, 0xb, 0x26, 0xc5, 0xb0, 0x5,
0xc9, 0xf7, 0x26, 0x5d, 0xa2, 0x0, 0x64, 0xd8,
0x44, 0x3a, 0x80, 0x75, 0x4a, 0x55, 0xd9, 0xc0,
0x20,
/* U+41 "A" */
0x0, 0xec, 0xf0, 0xf, 0xe1, 0x30, 0x50, 0xf,
0xce, 0x0, 0xf0, 0xf, 0xda, 0x8, 0x80, 0xf,
0xc8, 0xba, 0x26, 0x1, 0xe4, 0xc, 0x70, 0xb0,
0xf, 0x68, 0x38, 0x92, 0x80, 0x79, 0xcc, 0x41,
0x48, 0x80, 0x18, 0xc6, 0xc0, 0x16, 0xa, 0x1,
0xac, 0x32, 0x66, 0xc, 0x0, 0xca, 0x8, 0xcc,
0x50, 0x41, 0x0, 0x11, 0x1b, 0xff, 0x50, 0x20,
0x1, 0x43, 0x40, 0x32, 0x7, 0x80, 0x30, 0x10,
0x3, 0x9, 0xa0, 0xa, 0x20, 0x3, 0xc8, 0x28,
/* U+42 "B" */
0x4f, 0xfd, 0xd8, 0xa0, 0x18, 0xd9, 0x88, 0x55,
0x40, 0xa, 0xe6, 0x55, 0xc6, 0xa8, 0x1, 0xf4,
0x86, 0x0, 0x7c, 0x61, 0xe0, 0x1e, 0x1b, 0x5,
0x0, 0x5c, 0x42, 0x7c, 0xa8, 0x80, 0x6, 0xee,
0x61, 0x36, 0x0, 0xa3, 0xfe, 0xb1, 0xc3, 0x0,
0xf2, 0x70, 0x40, 0x7, 0xc6, 0xa, 0x1, 0xf0,
0x81, 0x80, 0x7d, 0x0, 0xa0, 0xb, 0x88, 0x4e,
0xb1, 0xc0, 0x0, 0xdd, 0xcc, 0x11, 0x80,
/* U+43 "C" */
0x0, 0x15, 0xff, 0xb1, 0x80, 0x24, 0xd5, 0x53,
0x14, 0xc8, 0x1, 0x43, 0xf5, 0x3c, 0x6c, 0x6c,
0x30, 0x20, 0x17, 0x84, 0xe8, 0x38, 0x6, 0x35,
0x36, 0x11, 0x0, 0x75, 0x49, 0x18, 0x7, 0xff,
0x40, 0x8c, 0x3, 0xf3, 0x8, 0x80, 0x3a, 0x63,
0x41, 0xc0, 0x31, 0xb1, 0x30, 0xc0, 0x80, 0x50,
0x12, 0x14, 0x3f, 0x32, 0xd4, 0x73, 0x4, 0xc5,
0x76, 0x19, 0x80,
/* U+44 "D" */
0x7f, 0xfb, 0xb1, 0x80, 0x3c, 0xae, 0xe1, 0x9d,
0x10, 0xd, 0xf1, 0x3b, 0x25, 0x80, 0x1f, 0x99,
0x84, 0xc0, 0x1f, 0xa0, 0x34, 0x3, 0xf0, 0x92,
0x0, 0x7f, 0x8, 0x7, 0xf9, 0xc0, 0x40, 0x3f,
0x38, 0x8, 0x7, 0xe1, 0x0, 0xfe, 0x12, 0x40,
0xf, 0xd0, 0x1a, 0x1, 0xf3, 0xb1, 0xb0, 0x5,
0xf1, 0x3b, 0x5, 0xa0, 0x19, 0x5d, 0xc3, 0x3a,
0x20, 0x0,
/* U+45 "E" */
0x3f, 0xff, 0xcc, 0x0, 0x26, 0x6f, 0x28, 0x1,
0x26, 0x7c, 0x60, 0x1f, 0xfd, 0xe6, 0xff, 0xe8,
0x0, 0x89, 0xdf, 0xb0, 0x2, 0x48, 0x8e, 0x40,
0xf, 0xfe, 0xaa, 0x44, 0x79, 0x0, 0x4, 0xef,
0xec,
/* U+46 "F" */
0x2f, 0xff, 0xd2, 0x0, 0x26, 0x6f, 0x60, 0x1,
0xe6, 0x7c, 0xa0, 0x1f, 0xfd, 0xe5, 0xff, 0xe9,
0x0, 0x89, 0xdf, 0xb0, 0x2, 0x78, 0x8e, 0x50,
0xf, 0xff, 0x38,
/* U+47 "G" */
0x0, 0x8a, 0xff, 0xd8, 0xa0, 0x19, 0x35, 0x10,
0xa5, 0x52, 0x1, 0x50, 0xed, 0xd7, 0x1b, 0x20,
0x38, 0xc1, 0x0, 0x5e, 0x1e, 0x18, 0xe, 0x1,
0x8e, 0x78, 0x14, 0x44, 0x1, 0xcc, 0xa0, 0x24,
0x1, 0xff, 0xc2, 0x68, 0x89, 0xc0, 0x3d, 0xae,
0xf4, 0x80, 0x90, 0x5, 0x7f, 0xe2, 0x0, 0x28,
0x88, 0x3, 0xf6, 0x84, 0x80, 0x7e, 0x62, 0x74,
0x0, 0x88, 0x80, 0x17, 0x8d, 0xda, 0x6f, 0x42,
0x80, 0x5, 0xec, 0xac, 0xc7, 0xd4,
/* U+48 "H" */
0x9f, 0x10, 0xc, 0x3f, 0x20, 0x1f, 0xff, 0x2e,
0xff, 0xdc, 0x1, 0x99, 0xdf, 0x30, 0x6, 0x88,
0xf0, 0x7, 0xff, 0xa0,
/* U+49 "I" */
0x4f, 0xff, 0xc8, 0xcd, 0x80, 0xc, 0xd8, 0xa6,
0x60, 0x19, 0x98, 0x80, 0x3f, 0xff, 0xe0, 0x1f,
0xfc, 0xd2, 0x99, 0x80, 0x66, 0x62, 0x66, 0xc0,
0x6, 0x6c,
/* U+4A "J" */
0x0, 0xfd, 0x3e, 0x60, 0x1f, 0xff, 0xf0, 0xf,
0xfe, 0x6b, 0xb0, 0x7, 0x18, 0x5, 0x52, 0x1,
0xce, 0x6, 0x14, 0x12, 0x1, 0x39, 0x28, 0x1,
0xcd, 0xb6, 0x72, 0xa, 0xc0, 0x2c, 0x80, 0x62,
0x6c, 0x10,
/* U+4B "K" */
0x4f, 0x80, 0xc, 0x9f, 0xa0, 0x1f, 0x15, 0x7,
0x80, 0x7d, 0xc3, 0x44, 0x1, 0xe9, 0x36, 0x50,
0xf, 0x2b, 0x14, 0x80, 0x78, 0xa8, 0x3c, 0x3,
0xc3, 0xc1, 0x4, 0x1, 0xe6, 0x30, 0xa0, 0xf,
0xc8, 0xa5, 0x0, 0x1e, 0x2a, 0xb1, 0x72, 0x0,
0xe5, 0x11, 0x40, 0x70, 0x7, 0xe6, 0x33, 0x30,
0x7, 0xee, 0x8, 0x10, 0xf, 0x89, 0xc6, 0xc0,
0x3f, 0x41, 0x2a, 0x0,
/* U+4C "L" */
0xf, 0xb0, 0xf, 0xff, 0xf8, 0x7, 0xff, 0xa9,
0x62, 0x3c, 0xc0, 0x1, 0x77, 0xf6, 0x0,
/* U+4D "M" */
0x8f, 0xd0, 0xd, 0x5f, 0x60, 0x2, 0x20, 0x4,
0xa0, 0x1c, 0xa0, 0x5, 0x0, 0xe2, 0xb0, 0x7,
0x88, 0x80, 0x24, 0x31, 0x5, 0x60, 0xd, 0xa0,
0xea, 0x16, 0x1, 0x98, 0xb7, 0xc4, 0xc4, 0x3,
0x2a, 0x2b, 0x80, 0x7a, 0xc0, 0x1a, 0x1, 0xc2,
0x62, 0x24, 0x0, 0xf9, 0x98, 0x1, 0xfa, 0x20,
0x1, 0xff, 0xd6,
/* U+4E "N" */
0x9f, 0x70, 0xc, 0x7f, 0x20, 0x9, 0x0, 0xfe,
0x17, 0x0, 0xfe, 0x90, 0xf, 0xca, 0x2e, 0x1,
0xf7, 0xc, 0x80, 0x7c, 0xf0, 0x2c, 0x1, 0xf3,
0xc, 0x0, 0x7e, 0x81, 0x60, 0xf, 0x98, 0x61,
0xc0, 0x3e, 0x91, 0xe0, 0xf, 0x9c, 0x54, 0x3,
0xf4, 0x80, 0x7f, 0x38, 0x80, 0x7f, 0x48, 0x0,
/* U+4F "O" */
0x0, 0x1d, 0xff, 0xac, 0x80, 0x24, 0xc4, 0x33,
0x26, 0x98, 0x2, 0x87, 0x73, 0x20, 0xd0, 0x61,
0x92, 0x0, 0x1c, 0xb, 0x60, 0x30, 0x6, 0x60,
0xc7, 0x11, 0x0, 0x61, 0x13, 0x91, 0x80, 0x78,
0xcc, 0x2, 0x1, 0xf0, 0x80, 0x80, 0x7c, 0x24,
0x60, 0x1e, 0x33, 0x38, 0x88, 0x3, 0x8, 0x9f,
0x1, 0x80, 0x33, 0x6, 0x30, 0xc1, 0x80, 0xa,
0x45, 0x82, 0x83, 0x2e, 0xda, 0x34, 0x0, 0x4d,
0x44, 0xd8, 0x80,
/* U+50 "P" */
0x2f, 0xfe, 0xe9, 0x10, 0xc, 0x4e, 0xf2, 0xb7,
0x90, 0x4, 0xf1, 0x15, 0xc8, 0xc8, 0x7, 0xe6,
0x24, 0x10, 0xf, 0xce, 0x6, 0x1, 0xf9, 0x80,
0xc0, 0x3e, 0x53, 0x41, 0x0, 0x3c, 0x45, 0x74,
0x32, 0x1, 0x13, 0xbc, 0xad, 0xe4, 0x1, 0x2f,
0xfd, 0xd2, 0x20, 0x1f, 0xfe, 0xd0,
/* U+51 "Q" */
0x0, 0x8e, 0xff, 0xd6, 0x60, 0x1c, 0x98, 0x86,
0x64, 0xc4, 0x0, 0x86, 0xc7, 0x73, 0x1a, 0x36,
0x20, 0x6, 0x8, 0x20, 0x1, 0x58, 0x30, 0x2,
0xc1, 0x80, 0x32, 0x85, 0x80, 0xc, 0x80, 0x3c,
0x46, 0x1, 0x30, 0x7, 0x98, 0x0, 0x20, 0x1f,
0xe1, 0x10, 0x7, 0xf8, 0x40, 0xc, 0x1, 0xe6,
0x0, 0x8c, 0x80, 0x3c, 0x46, 0x0, 0xb0, 0x50,
0xc, 0xa1, 0x60, 0x6, 0xb, 0x20, 0x1, 0x58,
0x30, 0x0, 0x6c, 0x76, 0xed, 0xa3, 0x42, 0x1,
0x26, 0x22, 0x42, 0x1a, 0x1, 0xc7, 0x7f, 0xf1,
0xbd, 0x0, 0x7e, 0x1c, 0x47, 0x10, 0xf, 0xeb,
0xd1,
/* U+52 "R" */
0x3f, 0xfe, 0xc6, 0x0, 0xe3, 0x77, 0x31, 0x4d,
0x0, 0x64, 0x88, 0x4f, 0x1a, 0xa8, 0x3, 0xf7,
0x87, 0x80, 0x7e, 0x20, 0x10, 0xf, 0xc4, 0x2,
0x1, 0xfb, 0xc3, 0x80, 0x24, 0x88, 0x4f, 0x1b,
0x20, 0x4, 0x6e, 0xe6, 0x19, 0x90, 0x6, 0x7f,
0xf5, 0x7, 0x0, 0x7e, 0x51, 0x71, 0x0, 0xfd,
0x0, 0xc0, 0x1f, 0x98, 0x64, 0x3, 0xfa, 0x45,
0xc0, 0x3f, 0x30, 0x48, 0x0,
/* U+53 "S" */
0x0, 0x1d, 0xf7, 0xe2, 0x80, 0x65, 0xc4, 0x55,
0x15, 0x58, 0x0, 0x68, 0x76, 0xeb, 0x91, 0xe,
0x8, 0xc, 0x40, 0x14, 0x85, 0x0, 0x42, 0x1,
0x8a, 0x6c, 0x10, 0x19, 0x40, 0x33, 0x30, 0x6,
0xc2, 0xb1, 0x84, 0x3, 0x93, 0x50, 0xe7, 0xa0,
0x3, 0x8a, 0xfa, 0x5, 0xf4, 0x3, 0xc2, 0xfc,
0xa5, 0x40, 0xac, 0x1, 0xd4, 0xa, 0x1d, 0x28,
0x1, 0xfb, 0xc2, 0x44, 0x2, 0x70, 0x40, 0x47,
0x2e, 0xa9, 0xc8, 0x19, 0x0, 0x45, 0xa2, 0x18,
0x63, 0xc8, 0x0,
/* U+54 "T" */
0x3f, 0xff, 0xf2, 0xb, 0x36, 0x0, 0x33, 0x71,
0x4c, 0xe2, 0x19, 0x9c, 0x40, 0x1f, 0xff, 0xf0,
0xf, 0xff, 0xc8,
/* U+55 "U" */
0xaf, 0x10, 0xc, 0x5f, 0x20, 0x1f, 0xfc, 0x73,
0x0, 0xff, 0xef, 0x18, 0x7, 0xff, 0x3c, 0xc0,
0x40, 0x30, 0x81, 0xf8, 0x20, 0x6, 0x40, 0xf7,
0x9, 0x20, 0x1, 0x48, 0x38, 0xd0, 0xed, 0x53,
0x46, 0x84, 0x17, 0x11, 0x54, 0x98, 0xa0,
/* U+56 "V" */
0x2f, 0xc0, 0xf, 0x6f, 0x89, 0x10, 0xc0, 0x38,
0x48, 0xc4, 0x10, 0x14, 0x3, 0x38, 0x58, 0x3,
0x43, 0x0, 0x36, 0x2, 0x0, 0x10, 0x1c, 0x3,
0x20, 0x98, 0x4, 0xa2, 0x40, 0x3, 0x17, 0x0,
0xde, 0x8, 0x0, 0xb0, 0xd0, 0xc, 0x81, 0xa0,
0x4, 0x4, 0x0, 0xc2, 0x68, 0x2, 0x68, 0x1,
0xeb, 0x4, 0x40, 0x68, 0x7, 0x94, 0x33, 0xc1,
0xc0, 0x3c, 0x44, 0x54, 0x31, 0x0, 0xf9, 0x8,
0x50, 0x3, 0xf6, 0x80, 0x2c, 0x3, 0xf2, 0x0,
0x98, 0x6,
/* U+57 "W" */
0x3f, 0x70, 0x5, 0xf8, 0x0, 0xfd, 0xc8, 0x38,
0x0, 0xa0, 0x40, 0xc0, 0x42, 0x6, 0x2, 0x20,
0x70, 0x30, 0x10, 0x16, 0x2, 0x0, 0x68, 0x70,
0x30, 0x11, 0x1, 0x40, 0xc8, 0x4, 0x8, 0x18,
0x43, 0xc9, 0x5c, 0x8, 0x40, 0x4, 0x2, 0x4f,
0xe4, 0xc, 0x40, 0xe, 0x3, 0x52, 0x20, 0x11,
0xb0, 0x0, 0x81, 0xc7, 0x54, 0x1c, 0x48, 0x0,
0xe1, 0x80, 0xc2, 0x2c, 0xf, 0x0, 0x10, 0x38,
0x18, 0x13, 0x81, 0x0, 0x4, 0x4, 0x80, 0xa,
0x20, 0xc0, 0x11, 0x3, 0x0, 0x38, 0x0, 0x40,
0x13, 0x1, 0x80, 0xc, 0x0, 0x20, 0x11, 0x7,
0x0, 0x14, 0x8, 0x0,
/* U+58 "X" */
0xc, 0xf5, 0x0, 0xc3, 0xfe, 0x10, 0xf0, 0x80,
0xd, 0x61, 0x2, 0x6, 0xa4, 0xc0, 0x2, 0x51,
0x70, 0xa, 0x2, 0x0, 0x12, 0x16, 0x1, 0x89,
0xc5, 0xcd, 0xd, 0x40, 0x3a, 0x46, 0x7c, 0x3c,
0x3, 0xc3, 0x2, 0x68, 0x60, 0x1f, 0x38, 0x3,
0x80, 0x3f, 0x48, 0x2, 0x40, 0x3e, 0x17, 0x26,
0x35, 0x0, 0xf5, 0x84, 0x40, 0x20, 0x3, 0x8d,
0x49, 0x45, 0xc9, 0x80, 0x37, 0x84, 0x80, 0x24,
0x20, 0x40, 0xa, 0x66, 0x40, 0x0, 0xb8, 0xc8,
0x2, 0x3, 0xc0, 0x34, 0xb, 0x90,
/* U+59 "Y" */
0x2f, 0xd0, 0xe, 0x1f, 0xe0, 0x24, 0x25, 0x0,
0xd2, 0x12, 0x0, 0x80, 0x90, 0xc, 0xc0, 0xc0,
0x3, 0x3c, 0x0, 0x61, 0x71, 0x0, 0xa0, 0x24,
0x1, 0x61, 0x20, 0x19, 0x9, 0x45, 0x49, 0x84,
0x3, 0xa0, 0x26, 0x41, 0x60, 0x1e, 0x52, 0x73,
0x52, 0x0, 0xfa, 0xc0, 0x12, 0x1, 0xf9, 0x80,
0xcc, 0x1, 0xff, 0xd6, 0x70, 0xf, 0xfe, 0x88,
/* U+5A "Z" */
0xcf, 0xff, 0xc9, 0x6c, 0xde, 0x0, 0x33, 0xcc,
0xf6, 0x2, 0x90, 0x7, 0xac, 0x2c, 0x3, 0xd0,
0x30, 0x20, 0x1c, 0x4e, 0x4e, 0x1, 0xe9, 0x9,
0x0, 0xf2, 0x21, 0x50, 0x3, 0xd2, 0x16, 0x1,
0xe7, 0x28, 0x10, 0xe, 0x18, 0x27, 0x0, 0xf5,
0x84, 0x0, 0x79, 0x15, 0x14, 0x3, 0xd0, 0x0,
0x88, 0xf2, 0x8, 0x23, 0xbf, 0xb0,
/* U+5B "[" */
0x68, 0x88, 0x2d, 0xde, 0x0, 0x17, 0xf8, 0x3,
0xff, 0xfe, 0x0, 0x28, 0x80, 0x4, 0xee, 0x0,
/* U+5C "\\" */
0x9f, 0x10, 0xe, 0xa0, 0x60, 0xe, 0x32, 0xa0,
0xf, 0x51, 0x18, 0x7, 0x30, 0x58, 0x7, 0xa,
0x30, 0x7, 0xb8, 0x50, 0x3, 0x94, 0x78, 0x3,
0xce, 0xa2, 0x1, 0xd4, 0xe, 0x1, 0xc6, 0x54,
0x1, 0xea, 0x32, 0x0, 0xe6, 0xa, 0x0, 0xe1,
0x46, 0x0, 0xf7, 0xa, 0x0, 0x72, 0x87, 0x0,
/* U+5D "]" */
0x8, 0x89, 0x81, 0xde, 0xb0, 0xff, 0x10, 0x7,
0xff, 0xfc, 0x1, 0x10, 0x20, 0x3, 0xb8, 0x0,
/* U+5E "^" */
0x0, 0xb7, 0x40, 0x1c, 0x64, 0x43, 0x0, 0xd4,
0x0, 0xa0, 0xc, 0xca, 0xa6, 0x0, 0x98, 0x3b,
0x80, 0xa0, 0xa, 0x14, 0x40, 0xc8, 0x11, 0xb0,
0x1, 0x8c, 0xa8, 0x28, 0x1, 0x41, 0x40,
/* U+5F "_" */
0x37, 0x7f, 0xc6, 0x91, 0x1f, 0x90,
/* U+60 "`" */
0x57, 0x30, 0x4a, 0xe0, 0x1f, 0x39,
/* U+61 "a" */
0x0, 0x26, 0x7f, 0x62, 0x80, 0x4d, 0x62, 0xee,
0x3a, 0x60, 0x19, 0x2d, 0x89, 0xd0, 0x90, 0x4,
0x48, 0x4, 0x48, 0x4, 0x2e, 0x80, 0x18, 0x40,
0x21, 0x9d, 0xff, 0x94, 0x2, 0xc6, 0x4a, 0xbc,
0x40, 0x3, 0x14, 0x4a, 0xa1, 0x88, 0x7, 0xe1,
0x70, 0x3, 0x8c, 0x4b, 0xcf, 0x90, 0x8, 0xb1,
0x5e, 0x16, 0x1c, 0x14,
/* U+62 "b" */
0x4f, 0x80, 0xf, 0xfe, 0xe3, 0xef, 0xeb, 0x0,
0x67, 0x87, 0x53, 0x97, 0x0, 0x87, 0x6a, 0x98,
0x30, 0x20, 0x6, 0x20, 0x1, 0x48, 0x38, 0x7,
0xc8, 0x1e, 0x1, 0xf0, 0x81, 0x80, 0x7c, 0x20,
0x60, 0x1f, 0x28, 0x78, 0x1, 0x40, 0x35, 0x83,
0x80, 0xb, 0x5d, 0xb0, 0xa0, 0x40, 0x10, 0xb3,
0x21, 0x97, 0x0,
/* U+63 "c" */
0x0, 0x1d, 0xf7, 0xea, 0x80, 0x49, 0x88, 0xec,
0x15, 0x20, 0xa, 0xc, 0x99, 0x6a, 0x31, 0xa8,
0xb9, 0x80, 0x5e, 0x4b, 0xa1, 0x80, 0x19, 0x35,
0x84, 0x1c, 0x3, 0xe1, 0x7, 0x0, 0xfb, 0x43,
0x0, 0x31, 0x42, 0x28, 0xb9, 0x0, 0x50, 0xee,
0xa, 0xd, 0x98, 0xd5, 0x73, 0x4, 0xc4, 0x77,
0xd, 0xc0, 0x0,
/* U+64 "d" */
0x0, 0xfa, 0x3d, 0x0, 0x3f, 0xfa, 0x8b, 0xbf,
0xce, 0x1, 0x9a, 0x89, 0x52, 0x1c, 0x0, 0x32,
0x3b, 0x54, 0xd1, 0x0, 0x38, 0x31, 0x0, 0x9,
0x80, 0x1e, 0x18, 0x1, 0xf1, 0x83, 0x80, 0x7c,
0x60, 0xe0, 0x1f, 0x78, 0x60, 0x7, 0xce, 0xc,
0x40, 0x1, 0x50, 0x0, 0xc8, 0xed, 0x53, 0xc8,
0x2, 0x6a, 0x25, 0x46, 0x80, 0x0,
/* U+65 "e" */
0x0, 0x15, 0x77, 0xe2, 0x80, 0x47, 0xaa, 0x8e,
0x55, 0x0, 0xd, 0x1d, 0xa8, 0xe3, 0x72, 0x61,
0x92, 0x0, 0xa4, 0x17, 0xc3, 0x26, 0x77, 0x87,
0x18, 0x23, 0x36, 0x50, 0x30, 0x6, 0x7f, 0xfa,
0xb4, 0x2c, 0x3, 0xe6, 0x7, 0x40, 0x8, 0xac,
0x86, 0xc2, 0xea, 0x2b, 0x54, 0xc1, 0x35, 0x51,
0xde, 0xf1,
/* U+66 "f" */
0x0, 0xe2, 0x68, 0x74, 0x0, 0xe7, 0xd9, 0x78,
0xb0, 0xc, 0x70, 0x57, 0xfe, 0xd0, 0xd, 0x61,
0x8, 0x0, 0x20, 0xc, 0x20, 0xc0, 0x1d, 0x1f,
0xe6, 0xc, 0xff, 0x90, 0x2e, 0x64, 0x60, 0xf3,
0x32, 0x81, 0xb3, 0x14, 0x2d, 0x9a, 0x10, 0xf,
0xff, 0xf8, 0x7, 0xff, 0x8,
/* U+67 "g" */
0x0, 0x36, 0xff, 0x43, 0xfa, 0x3, 0xc8, 0x44,
0xa4, 0x0, 0x6, 0x7, 0x1d, 0xd8, 0x60, 0x7,
0x9, 0x10, 0x9, 0x0, 0x1e, 0x6, 0x1, 0xfc,
0xe0, 0x1f, 0xce, 0x1, 0xf7, 0x86, 0x0, 0x7c,
0xe0, 0xc4, 0x0, 0x16, 0x0, 0xc, 0x8e, 0xd5,
0x3c, 0x40, 0x26, 0xa2, 0x57, 0x67, 0x0, 0xcb,
0xbf, 0xb0, 0x40, 0xc1, 0xa, 0x1, 0x12, 0x91,
0x0, 0xea, 0xe2, 0xb4, 0x24, 0x1, 0x72, 0xee,
0x54, 0xc4, 0x0,
/* U+68 "h" */
0x4f, 0x70, 0xf, 0xfe, 0xe1, 0xdf, 0xf4, 0x88,
0x5, 0x78, 0xc, 0x6d, 0xa0, 0x11, 0x6d, 0xce,
0x91, 0x98, 0x0, 0xc4, 0x1, 0x50, 0x28, 0x3,
0xc0, 0x30, 0x80, 0x7f, 0x18, 0x7, 0xff, 0xa0,
/* U+69 "i" */
0x0, 0xcd, 0xe8, 0x1, 0xf7, 0x1, 0x0, 0x7d,
0x1c, 0xc0, 0x1f, 0x84, 0x3, 0xbf, 0xf9, 0x80,
0x33, 0x34, 0x60, 0x1e, 0x99, 0xa8, 0x3, 0xff,
0xed, 0x33, 0x50, 0x54, 0xc9, 0xc1, 0x9a, 0x30,
0x36, 0x65, 0x0,
/* U+6A "j" */
0x0, 0xd3, 0xc4, 0x1, 0x8c, 0x44, 0x1, 0xab,
0x8c, 0x3, 0x84, 0x7, 0xff, 0x8c, 0x59, 0xa2,
0x0, 0xa6, 0x65, 0x0, 0xff, 0xf9, 0x10, 0x7,
0xa, 0x81, 0xc4, 0x27, 0xc2, 0x1, 0x5d, 0x8a,
0x9c, 0x0,
/* U+6B "k" */
0x4f, 0x80, 0xf, 0xff, 0x1a, 0xfe, 0x88, 0x7,
0x92, 0x8b, 0x4, 0x3, 0x92, 0xc7, 0xc4, 0x3,
0x8e, 0xc7, 0x8, 0x3, 0x8b, 0x42, 0xc8, 0x3,
0xca, 0x21, 0x20, 0x1f, 0xad, 0x4e, 0x40, 0x3c,
0xe9, 0x64, 0xca, 0x1, 0xf0, 0xf0, 0x51, 0x0,
0x7c, 0x72, 0x1e, 0x1, 0xf9, 0x94, 0xa8, 0x0,
/* U+6C "l" */
0xf, 0xfe, 0x60, 0xc, 0xcd, 0x18, 0x7, 0xa6,
0x6a, 0x0, 0xff, 0xff, 0x80, 0x7f, 0xf4, 0xe6,
0x6a, 0xa, 0x99, 0x38, 0x33, 0x46, 0x6, 0xcc,
0xa0,
/* U+6D "m" */
0x1f, 0x9b, 0xfd, 0x5b, 0xfd, 0x30, 0x9, 0xb1,
0xca, 0x8a, 0xb, 0x80, 0x25, 0x78, 0x11, 0x4b,
0xa9, 0x0, 0x46, 0x0, 0x33, 0x0, 0xc, 0x4,
0x3, 0xff, 0xfe, 0x1, 0xfc,
/* U+6E "n" */
0x4f, 0x54, 0xcf, 0xd9, 0x10, 0xb, 0xad, 0x98,
0xd, 0xa0, 0x12, 0xed, 0x4e, 0x99, 0x88, 0x0,
0xc4, 0x1, 0x58, 0x38, 0x3, 0xc0, 0x30, 0x81,
0x80, 0x7f, 0xfc, 0x0,
/* U+6F "o" */
0x0, 0x25, 0xff, 0xad, 0x0, 0x26, 0xb5, 0x66,
0x2d, 0xb0, 0x14, 0x97, 0xcc, 0xbc, 0xa4, 0xa8,
0x2c, 0x40, 0x3, 0x61, 0x46, 0xe, 0x1, 0x90,
0xd, 0xc0, 0x40, 0x31, 0x3, 0xb8, 0x4, 0x3,
0x8, 0x39, 0x82, 0x0, 0x64, 0x3, 0xa0, 0x81,
0x0, 0xc, 0x5, 0x14, 0x97, 0xcc, 0xbc, 0xa4,
0x81, 0xac, 0x99, 0x85, 0x6c, 0x0,
/* U+70 "p" */
0x4f, 0x67, 0xdf, 0xd6, 0x0, 0xd1, 0x2e, 0xa5,
0x2e, 0x1, 0x1f, 0xd5, 0x30, 0x20, 0x40, 0xa,
0x20, 0x3, 0x70, 0x70, 0x7, 0x80, 0x6c, 0xe,
0x0, 0xf9, 0xc0, 0x40, 0x3e, 0x70, 0x10, 0xf,
0xb0, 0x34, 0x1, 0x60, 0x11, 0x30, 0x20, 0x0,
0xf6, 0x65, 0xa3, 0x2, 0x0, 0x75, 0x76, 0x29,
0x70, 0xb, 0xe3, 0xbf, 0x58, 0x3, 0xff, 0xa8,
/* U+71 "q" */
0x0, 0x2e, 0xff, 0x4c, 0x7a, 0x3, 0xd0, 0x4c,
0x2b, 0x80, 0x6, 0x7, 0x19, 0x98, 0x80, 0x7,
0x9, 0x10, 0x8, 0xc0, 0x1e, 0x6, 0x1, 0xfc,
0xe0, 0x1f, 0xce, 0x1, 0xf7, 0x86, 0x0, 0x7c,
0xe0, 0xc4, 0x0, 0x15, 0x0, 0xc, 0xe, 0x4c,
0xbc, 0x80, 0x27, 0xa3, 0x67, 0x67, 0x0, 0xcb,
0xbf, 0xd0, 0x1, 0xff, 0xd5,
/* U+72 "r" */
0xcf, 0x6, 0xdf, 0xe5, 0x0, 0x4c, 0x88, 0x82,
0x20, 0x3, 0xdf, 0xef, 0xa0, 0x2, 0xd0, 0x3,
0xca, 0x1, 0xff, 0xe9,
/* U+73 "s" */
0x0, 0x1d, 0xf7, 0xeb, 0x80, 0x49, 0x8a, 0xec,
0x11, 0x60, 0x9, 0xf, 0x99, 0x6a, 0x24, 0x1,
0x8, 0x5, 0x34, 0xc1, 0x61, 0xce, 0x60, 0x4a,
0x40, 0xd6, 0xb1, 0x9f, 0x44, 0x1, 0x25, 0xfd,
0xb2, 0xe0, 0x93, 0xa0, 0x1, 0x26, 0x42, 0xc7,
0x12, 0x20, 0x10, 0x80, 0x8a, 0xb, 0xe6, 0x2e,
0x9, 0x81, 0xe9, 0x59, 0xd9, 0xf0, 0x0,
/* U+74 "t" */
0x0, 0x99, 0xc0, 0x3f, 0x5c, 0x0, 0x7f, 0xf0,
0xe7, 0xfc, 0x41, 0xff, 0x83, 0x66, 0x42, 0x13,
0x38, 0x11, 0x98, 0x60, 0xcd, 0x80, 0x3f, 0xfd,
0x4c, 0x8, 0x1, 0xf7, 0x5, 0xd4, 0xd9, 0x80,
0x4b, 0x44, 0xac, 0xe0,
/* U+75 "u" */
0x3f, 0x80, 0xd, 0x1e, 0x80, 0x1f, 0xfe, 0x81,
0x0, 0xf8, 0x40, 0x3f, 0x88, 0x1c, 0x3, 0x28,
0x4, 0xe3, 0x6c, 0xfa, 0x60, 0x14, 0x41, 0x66,
0xae, 0x0, 0x0,
/* U+76 "v" */
0xd, 0xf0, 0xe, 0x1f, 0xc0, 0xa0, 0x50, 0xc,
0xe1, 0x40, 0xc1, 0xc0, 0x1a, 0x81, 0x80, 0x55,
0x4, 0x0, 0x26, 0xc0, 0x17, 0x3, 0x0, 0x18,
0x28, 0x2, 0x42, 0xa0, 0x5, 0x11, 0x80, 0x6a,
0x22, 0xd4, 0x1, 0xcc, 0x15, 0x40, 0x60, 0xe,
0x14, 0x65, 0x50, 0x80, 0x7b, 0xc4, 0xb8, 0x3,
0xe4, 0x11, 0x20, 0x4,
/* U+77 "w" */
0x6f, 0x20, 0x5, 0x58, 0x5, 0xf0, 0xa0, 0xe0,
0x4, 0x40, 0x0, 0xc3, 0x4c, 0x34, 0x8, 0x40,
0xc1, 0x41, 0x0, 0x88, 0xe, 0x24, 0x81, 0xc2,
0x20, 0x47, 0xc, 0x57, 0xc0, 0x35, 0x0, 0x79,
0x2, 0x66, 0x14, 0x14, 0xc0, 0xa, 0x8, 0x48,
0x81, 0x31, 0xc0, 0x1, 0x87, 0x1, 0x90, 0xd0,
0x28, 0x4, 0x6a, 0x80, 0x4, 0x71, 0x10, 0x4,
0xa1, 0x80, 0xc, 0x15, 0x0, 0xde, 0x6, 0x0,
0x40, 0xc0, 0x0,
/* U+78 "x" */
0x7f, 0x90, 0xc, 0xff, 0x40, 0xe8, 0xca, 0x0,
0x38, 0x2a, 0x0, 0x50, 0xd8, 0x87, 0x7, 0x0,
0x43, 0x43, 0x52, 0x50, 0x60, 0x19, 0x1d, 0x19,
0x1c, 0x3, 0xd2, 0x0, 0xf0, 0xf, 0xac, 0x1,
0x20, 0x1e, 0x65, 0x54, 0x94, 0x80, 0x62, 0x91,
0xa6, 0x46, 0x40, 0xb, 0x83, 0x40, 0x14, 0x34,
0x21, 0x6, 0xe6, 0x0, 0x1b, 0x1a, 0x0,
/* U+79 "y" */
0x1f, 0xe0, 0xf, 0x77, 0x88, 0x94, 0x54, 0x3,
0x28, 0xa8, 0x84, 0x87, 0x0, 0x6e, 0x9, 0x0,
0x19, 0x90, 0x80, 0x2, 0x86, 0x60, 0xa, 0x42,
0xc0, 0xc, 0x12, 0x1, 0x94, 0x98, 0x1, 0x22,
0xa0, 0x1d, 0x60, 0xc8, 0x32, 0x1, 0xe6, 0x1b,
0xe0, 0x60, 0xf, 0x98, 0x95, 0x84, 0x3, 0xe9,
0x0, 0x58, 0x7, 0xe1, 0x12, 0x10, 0x7, 0xe7,
0x1f, 0x0, 0xfc, 0x50, 0x48, 0x1, 0xe3, 0xac,
0xe, 0x0, 0xf9, 0x54, 0x76, 0x60, 0x1e,
/* U+7A "z" */
0x5f, 0xff, 0xc6, 0xef, 0xe5, 0x0, 0x11, 0x22,
0x39, 0xc2, 0x84, 0x3, 0xa8, 0x9d, 0x40, 0x39,
0x94, 0xe0, 0x3, 0x8e, 0x47, 0x40, 0x38, 0x74,
0x34, 0x40, 0x3a, 0x86, 0x4c, 0x3, 0xa1, 0x15,
0x80, 0x39, 0x1c, 0x9, 0xdf, 0x90, 0x80, 0xf,
0x11, 0xda,
/* U+7B "{" */
0x0, 0xc9, 0x92, 0x1, 0x1d, 0xb5, 0x80, 0x50,
0x14, 0x40, 0x12, 0x20, 0x3, 0x8, 0x7, 0xe1,
0x0, 0xc6, 0x1, 0xe4, 0xd, 0x0, 0x13, 0x41,
0x30, 0x3, 0xe4, 0xf0, 0x40, 0x12, 0xc5, 0x40,
0x12, 0x4c, 0x22, 0x80, 0x64, 0xc, 0x0, 0xc4,
0x6, 0x1, 0xe1, 0x0, 0xc2, 0xe, 0x1, 0xc6,
0x60, 0xe, 0x80, 0x90, 0xc, 0x94, 0xd4, 0x1,
0x97, 0xec,
/* U+7C "|" */
0xbb, 0x0, 0x7f, 0xf6, 0x0,
/* U+7D "}" */
0xac, 0x30, 0xd, 0xf, 0x86, 0x1, 0x15, 0x4,
0x80, 0x61, 0x24, 0x0, 0xe1, 0x10, 0x7, 0xff,
0x1, 0xc0, 0x40, 0x31, 0x82, 0x80, 0x69, 0x1a,
0x52, 0x0, 0xe, 0x5, 0x48, 0x5, 0xc2, 0xfe,
0x0, 0x73, 0x98, 0x40, 0x6, 0x3, 0x80, 0x67,
0x1, 0x0, 0xff, 0x84, 0x40, 0x18, 0x49, 0x40,
0x35, 0x4, 0x0, 0x58, 0xb6, 0x60, 0x16, 0xf2,
0x0, 0x60,
/* U+7E "~" */
0x3, 0xdf, 0xd5, 0x0, 0xcc, 0x63, 0xa6, 0xa7,
0x52, 0x0, 0x29, 0x57, 0x1f, 0xae, 0x56, 0xea,
0xc1, 0x64, 0xa1, 0x0, 0x54, 0x9a, 0x96, 0x0
};
/*---------------------
* GLYPH DESCRIPTION
*--------------------*/
static const lv_font_fmt_txt_glyph_dsc_t glyph_dsc[] = {
{.bitmap_index = 0, .adv_w = 0, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0} /* id = 0 reserved */,
{.bitmap_index = 0, .adv_w = 192, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 0, .adv_w = 192, .box_w = 3, .box_h = 15, .ofs_x = 4, .ofs_y = 0},
{.bitmap_index = 13, .adv_w = 192, .box_w = 6, .box_h = 5, .ofs_x = 3, .ofs_y = 10},
{.bitmap_index = 26, .adv_w = 192, .box_w = 12, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 110, .adv_w = 192, .box_w = 10, .box_h = 19, .ofs_x = 1, .ofs_y = -2},
{.bitmap_index = 193, .adv_w = 192, .box_w = 12, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 269, .adv_w = 192, .box_w = 11, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 346, .adv_w = 192, .box_w = 3, .box_h = 5, .ofs_x = 4, .ofs_y = 10},
{.bitmap_index = 353, .adv_w = 192, .box_w = 6, .box_h = 22, .ofs_x = 3, .ofs_y = -5},
{.bitmap_index = 413, .adv_w = 192, .box_w = 6, .box_h = 22, .ofs_x = 3, .ofs_y = -5},
{.bitmap_index = 472, .adv_w = 192, .box_w = 10, .box_h = 10, .ofs_x = 1, .ofs_y = 5},
{.bitmap_index = 518, .adv_w = 192, .box_w = 10, .box_h = 11, .ofs_x = 1, .ofs_y = 1},
{.bitmap_index = 543, .adv_w = 192, .box_w = 4, .box_h = 6, .ofs_x = 3, .ofs_y = -4},
{.bitmap_index = 555, .adv_w = 192, .box_w = 8, .box_h = 2, .ofs_x = 2, .ofs_y = 6},
{.bitmap_index = 561, .adv_w = 192, .box_w = 4, .box_h = 3, .ofs_x = 4, .ofs_y = 0},
{.bitmap_index = 567, .adv_w = 192, .box_w = 9, .box_h = 16, .ofs_x = 2, .ofs_y = -1},
{.bitmap_index = 617, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 689, .adv_w = 192, .box_w = 6, .box_h = 15, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 708, .adv_w = 192, .box_w = 11, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 774, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 841, .adv_w = 192, .box_w = 11, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 893, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 957, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1027, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1078, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1150, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1220, .adv_w = 192, .box_w = 4, .box_h = 11, .ofs_x = 5, .ofs_y = 0},
{.bitmap_index = 1237, .adv_w = 192, .box_w = 5, .box_h = 15, .ofs_x = 4, .ofs_y = -4},
{.bitmap_index = 1265, .adv_w = 192, .box_w = 9, .box_h = 10, .ofs_x = 1, .ofs_y = 1},
{.bitmap_index = 1305, .adv_w = 192, .box_w = 10, .box_h = 6, .ofs_x = 1, .ofs_y = 4},
{.bitmap_index = 1322, .adv_w = 192, .box_w = 10, .box_h = 10, .ofs_x = 1, .ofs_y = 1},
{.bitmap_index = 1365, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1424, .adv_w = 192, .box_w = 12, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1513, .adv_w = 192, .box_w = 12, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1585, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1648, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1707, .adv_w = 192, .box_w = 11, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1765, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1798, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1825, .adv_w = 192, .box_w = 11, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1895, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1915, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 1941, .adv_w = 192, .box_w = 11, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1975, .adv_w = 192, .box_w = 11, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 2035, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 2050, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 2101, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 2149, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 2216, .adv_w = 192, .box_w = 11, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 2262, .adv_w = 192, .box_w = 12, .box_h = 18, .ofs_x = 0, .ofs_y = -3},
{.bitmap_index = 2351, .adv_w = 192, .box_w = 11, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 2412, .adv_w = 192, .box_w = 11, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 2487, .adv_w = 192, .box_w = 12, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2506, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 2545, .adv_w = 192, .box_w = 12, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2619, .adv_w = 192, .box_w = 12, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2711, .adv_w = 192, .box_w = 12, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2789, .adv_w = 192, .box_w = 12, .box_h = 15, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 2845, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 2899, .adv_w = 192, .box_w = 5, .box_h = 20, .ofs_x = 4, .ofs_y = -3},
{.bitmap_index = 2915, .adv_w = 192, .box_w = 8, .box_h = 16, .ofs_x = 2, .ofs_y = -1},
{.bitmap_index = 2963, .adv_w = 192, .box_w = 5, .box_h = 20, .ofs_x = 3, .ofs_y = -3},
{.bitmap_index = 2979, .adv_w = 192, .box_w = 8, .box_h = 8, .ofs_x = 2, .ofs_y = 7},
{.bitmap_index = 3010, .adv_w = 192, .box_w = 10, .box_h = 2, .ofs_x = 1, .ofs_y = -1},
{.bitmap_index = 3016, .adv_w = 192, .box_w = 4, .box_h = 3, .ofs_x = 4, .ofs_y = 12},
{.bitmap_index = 3022, .adv_w = 192, .box_w = 10, .box_h = 11, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3074, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3125, .adv_w = 192, .box_w = 10, .box_h = 11, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3176, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3230, .adv_w = 192, .box_w = 10, .box_h = 11, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3280, .adv_w = 192, .box_w = 11, .box_h = 16, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3325, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = -4},
{.bitmap_index = 3392, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3424, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3459, .adv_w = 192, .box_w = 7, .box_h = 19, .ofs_x = 2, .ofs_y = -4},
{.bitmap_index = 3493, .adv_w = 192, .box_w = 11, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3541, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3566, .adv_w = 192, .box_w = 12, .box_h = 11, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 3595, .adv_w = 192, .box_w = 10, .box_h = 11, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3623, .adv_w = 192, .box_w = 10, .box_h = 11, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3677, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = -4},
{.bitmap_index = 3733, .adv_w = 192, .box_w = 10, .box_h = 15, .ofs_x = 1, .ofs_y = -4},
{.bitmap_index = 3786, .adv_w = 192, .box_w = 8, .box_h = 11, .ofs_x = 3, .ofs_y = 0},
{.bitmap_index = 3806, .adv_w = 192, .box_w = 10, .box_h = 11, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3861, .adv_w = 192, .box_w = 10, .box_h = 14, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3897, .adv_w = 192, .box_w = 10, .box_h = 11, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3924, .adv_w = 192, .box_w = 11, .box_h = 11, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 3976, .adv_w = 192, .box_w = 12, .box_h = 11, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 4043, .adv_w = 192, .box_w = 11, .box_h = 11, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 4098, .adv_w = 192, .box_w = 12, .box_h = 15, .ofs_x = 0, .ofs_y = -4},
{.bitmap_index = 4169, .adv_w = 192, .box_w = 10, .box_h = 11, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 4211, .adv_w = 192, .box_w = 7, .box_h = 20, .ofs_x = 3, .ofs_y = -4},
{.bitmap_index = 4269, .adv_w = 192, .box_w = 2, .box_h = 19, .ofs_x = 5, .ofs_y = -4},
{.bitmap_index = 4274, .adv_w = 192, .box_w = 7, .box_h = 20, .ofs_x = 3, .ofs_y = -4},
{.bitmap_index = 4332, .adv_w = 192, .box_w = 12, .box_h = 4, .ofs_x = 0, .ofs_y = 4}
};
/*---------------------
* CHARACTER MAPPING
*--------------------*/
/*Collect the unicode lists and glyph_id offsets*/
static const lv_font_fmt_txt_cmap_t cmaps[] =
{
{
.range_start = 32, .range_length = 95, .glyph_id_start = 1,
.unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
}
};
/*--------------------
* ALL CUSTOM DATA
*--------------------*/
/*Store all the custom data of the font*/
static lv_font_fmt_txt_dsc_t font_dsc = {
.glyph_bitmap = gylph_bitmap,
.glyph_dsc = glyph_dsc,
.cmaps = cmaps,
.kern_dsc = NULL,
.kern_scale = 0,
.cmap_num = 1,
.bpp = 4,
.kern_classes = 0,
.bitmap_format = 1
};
/*-----------------
* PUBLIC FONT
*----------------*/
/*Initialize a public general font descriptor*/
lv_font_t font_3 = {
.get_glyph_dsc = lv_font_get_glyph_dsc_fmt_txt, /*Function pointer to get glyph's data*/
.get_glyph_bitmap = lv_font_get_bitmap_fmt_txt, /*Function pointer to get glyph's bitmap*/
.line_height = 22, /*The maximum line height required by the font*/
.base_line = 5, /*Baseline measured from the bottom of the line*/
#if !(LVGL_VERSION_MAJOR == 6 && LVGL_VERSION_MINOR == 0)
.subpx = LV_FONT_SUBPX_NONE,
#endif
.dsc = &font_dsc /*The custom font data. Will be accessed by `get_glyph_bitmap/dsc` */
};
#endif /*#if FONT_3*/
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/src/test_fonts/font_3.c | C | apache-2.0 | 40,236 |
# ==========================================
# Unity Project - A Test Framework for C
# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
# [Released under MIT License. Please refer to license.txt for details]
# ==========================================
class UnityTestRunnerGenerator
def initialize(options = nil)
@options = UnityTestRunnerGenerator.default_options
case options
when NilClass
@options
when String
@options.merge!(UnityTestRunnerGenerator.grab_config(options))
when Hash
# Check if some of these have been specified
@options[:has_setup] = !options[:setup_name].nil?
@options[:has_teardown] = !options[:teardown_name].nil?
@options[:has_suite_setup] = !options[:suite_setup].nil?
@options[:has_suite_teardown] = !options[:suite_teardown].nil?
@options.merge!(options)
else
raise 'If you specify arguments, it should be a filename or a hash of options'
end
require_relative 'type_sanitizer'
end
def self.default_options
{
includes: [],
defines: [],
plugins: [],
framework: :unity,
test_prefix: 'test|spec|should',
mock_prefix: 'Mock',
mock_suffix: '',
setup_name: 'setUp',
teardown_name: 'tearDown',
test_reset_name: 'resetTest',
test_verify_name: 'verifyTest',
main_name: 'main', # set to :auto to automatically generate each time
main_export_decl: '',
cmdline_args: false,
omit_begin_end: false,
use_param_tests: false,
include_extensions: '(?:hpp|hh|H|h)',
source_extensions: '(?:cpp|cc|ino|C|c)'
}
end
def self.grab_config(config_file)
options = default_options
unless config_file.nil? || config_file.empty?
require 'yaml'
yaml_guts = YAML.load_file(config_file)
options.merge!(yaml_guts[:unity] || yaml_guts[:cmock])
raise "No :unity or :cmock section found in #{config_file}" unless options
end
options
end
def run(input_file, output_file, options = nil)
@options.merge!(options) unless options.nil?
# pull required data from source file
source = File.read(input_file)
source = source.force_encoding('ISO-8859-1').encode('utf-8', replace: nil)
tests = find_tests(source)
headers = find_includes(source)
testfile_includes = (headers[:local] + headers[:system])
used_mocks = find_mocks(testfile_includes)
testfile_includes = (testfile_includes - used_mocks)
testfile_includes.delete_if { |inc| inc =~ /(unity|cmock)/ }
find_setup_and_teardown(source)
# build runner file
generate(input_file, output_file, tests, used_mocks, testfile_includes)
# determine which files were used to return them
all_files_used = [input_file, output_file]
all_files_used += testfile_includes.map { |filename| filename + '.c' } unless testfile_includes.empty?
all_files_used += @options[:includes] unless @options[:includes].empty?
all_files_used += headers[:linkonly] unless headers[:linkonly].empty?
all_files_used.uniq
end
def generate(input_file, output_file, tests, used_mocks, testfile_includes)
File.open(output_file, 'w') do |output|
create_header(output, used_mocks, testfile_includes)
create_externs(output, tests, used_mocks)
create_mock_management(output, used_mocks)
create_setup(output)
create_teardown(output)
create_suite_setup(output)
create_suite_teardown(output)
create_reset(output)
create_run_test(output) unless tests.empty?
create_args_wrappers(output, tests)
create_main(output, input_file, tests, used_mocks)
end
return unless @options[:header_file] && !@options[:header_file].empty?
File.open(@options[:header_file], 'w') do |output|
create_h_file(output, @options[:header_file], tests, testfile_includes, used_mocks)
end
end
def find_tests(source)
tests_and_line_numbers = []
# contains characters which will be substituted from within strings, doing
# this prevents these characters from interfering with scrubbers
# @ is not a valid C character, so there should be no clashes with files genuinely containing these markers
substring_subs = { '{' => '@co@', '}' => '@cc@', ';' => '@ss@', '/' => '@fs@' }
substring_re = Regexp.union(substring_subs.keys)
substring_unsubs = substring_subs.invert # the inverse map will be used to fix the strings afterwords
substring_unsubs['@quote@'] = '\\"'
substring_unsubs['@apos@'] = '\\\''
substring_unre = Regexp.union(substring_unsubs.keys)
source_scrubbed = source.clone
source_scrubbed = source_scrubbed.gsub(/\\"/, '@quote@') # hide escaped quotes to allow capture of the full string/char
source_scrubbed = source_scrubbed.gsub(/\\'/, '@apos@') # hide escaped apostrophes to allow capture of the full string/char
source_scrubbed = source_scrubbed.gsub(/("[^"\n]*")|('[^'\n]*')/) { |s| s.gsub(substring_re, substring_subs) } # temporarily hide problematic characters within strings
source_scrubbed = source_scrubbed.gsub(/\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '') # remove line comments that comment out the start of blocks
source_scrubbed = source_scrubbed.gsub(/\/\*.*?\*\//m, '') # remove block comments
source_scrubbed = source_scrubbed.gsub(/\/\/.*$/, '') # remove line comments (all that remain)
lines = source_scrubbed.split(/(^\s*\#.*$) | (;|\{|\}) /x) # Treat preprocessor directives as a logical line. Match ;, {, and } as end of lines
.map { |line| line.gsub(substring_unre, substring_unsubs) } # unhide the problematic characters previously removed
lines.each_with_index do |line, _index|
# find tests
next unless line =~ /^((?:\s*(?:TEST_CASE|TEST_RANGE)\s*\(.*?\)\s*)*)\s*void\s+((?:#{@options[:test_prefix]}).*)\s*\(\s*(.*)\s*\)/m
arguments = Regexp.last_match(1)
name = Regexp.last_match(2)
call = Regexp.last_match(3)
params = Regexp.last_match(4)
args = nil
if @options[:use_param_tests] && !arguments.empty?
args = []
arguments.scan(/\s*TEST_CASE\s*\((.*)\)\s*$/) { |a| args << a[0] }
arguments.scan(/\s*TEST_RANGE\s*\((.*)\)\s*$/).flatten.each do |range_str|
args += range_str.scan(/\[\s*(-?\d+.?\d*),\s*(-?\d+.?\d*),\s*(-?\d+.?\d*)\s*\]/).map do |arg_values_str|
arg_values_str.map do |arg_value_str|
arg_value_str.include?('.') ? arg_value_str.to_f : arg_value_str.to_i
end
end.map do |arg_values|
(arg_values[0]..arg_values[1]).step(arg_values[2]).to_a
end.reduce do |result, arg_range_expanded|
result.product(arg_range_expanded)
end.map do |arg_combinations|
arg_combinations.flatten.join(', ')
end
end
end
tests_and_line_numbers << { test: name, args: args, call: call, params: params, line_number: 0 }
end
tests_and_line_numbers.uniq! { |v| v[:test] }
# determine line numbers and create tests to run
source_lines = source.split("\n")
source_index = 0
tests_and_line_numbers.size.times do |i|
source_lines[source_index..-1].each_with_index do |line, index|
next unless line =~ /\s+#{tests_and_line_numbers[i][:test]}(?:\s|\()/
source_index += index
tests_and_line_numbers[i][:line_number] = source_index + 1
break
end
end
tests_and_line_numbers
end
def find_includes(source)
# remove comments (block and line, in three steps to ensure correct precedence)
source.gsub!(/\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '') # remove line comments that comment out the start of blocks
source.gsub!(/\/\*.*?\*\//m, '') # remove block comments
source.gsub!(/\/\/.*$/, '') # remove line comments (all that remain)
# parse out includes
includes = {
local: source.scan(/^\s*#include\s+\"\s*(.+\.#{@options[:include_extensions]})\s*\"/).flatten,
system: source.scan(/^\s*#include\s+<\s*(.+)\s*>/).flatten.map { |inc| "<#{inc}>" },
linkonly: source.scan(/^TEST_FILE\(\s*\"\s*(.+\.#{@options[:source_extensions]})\s*\"/).flatten
}
includes
end
def find_mocks(includes)
mock_headers = []
includes.each do |include_path|
include_file = File.basename(include_path)
mock_headers << include_path if include_file =~ /^#{@options[:mock_prefix]}.*#{@options[:mock_suffix]}\.h$/i
end
mock_headers
end
def find_setup_and_teardown(source)
@options[:has_setup] = source =~ /void\s+#{@options[:setup_name]}\s*\(/
@options[:has_teardown] = source =~ /void\s+#{@options[:teardown_name]}\s*\(/
@options[:has_suite_setup] ||= (source =~ /void\s+suiteSetUp\s*\(/)
@options[:has_suite_teardown] ||= (source =~ /int\s+suiteTearDown\s*\(int\s+([a-zA-Z0-9_])+\s*\)/)
end
def create_header(output, mocks, testfile_includes = [])
output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */')
output.puts("\n/*=======Automagically Detected Files To Include=====*/")
output.puts("#include \"#{@options[:framework]}.h\"")
output.puts('#include "cmock.h"') unless mocks.empty?
if @options[:defines] && !@options[:defines].empty?
@options[:defines].each { |d| output.puts("#ifndef #{d}\n#define #{d}\n#endif /* #{d} */") }
end
if @options[:header_file] && !@options[:header_file].empty?
output.puts("#include \"#{File.basename(@options[:header_file])}\"")
else
@options[:includes].flatten.uniq.compact.each do |inc|
output.puts("#include #{inc.include?('<') ? inc : "\"#{inc}\""}")
end
testfile_includes.each do |inc|
output.puts("#include #{inc.include?('<') ? inc : "\"#{inc}\""}")
end
end
mocks.each do |mock|
output.puts("#include \"#{mock}\"")
end
output.puts('#include "CException.h"') if @options[:plugins].include?(:cexception)
return unless @options[:enforce_strict_ordering]
output.puts('')
output.puts('int GlobalExpectCount;')
output.puts('int GlobalVerifyOrder;')
output.puts('char* GlobalOrderError;')
end
def create_externs(output, tests, _mocks)
output.puts("\n/*=======External Functions This Runner Calls=====*/")
output.puts("extern void #{@options[:setup_name]}(void);")
output.puts("extern void #{@options[:teardown_name]}(void);")
output.puts("\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif") if @options[:externc]
tests.each do |test|
output.puts("extern void #{test[:test]}(#{test[:call] || 'void'});")
end
output.puts("#ifdef __cplusplus\n}\n#endif") if @options[:externc]
output.puts('')
end
def create_mock_management(output, mock_headers)
output.puts("\n/*=======Mock Management=====*/")
output.puts('static void CMock_Init(void)')
output.puts('{')
if @options[:enforce_strict_ordering]
output.puts(' GlobalExpectCount = 0;')
output.puts(' GlobalVerifyOrder = 0;')
output.puts(' GlobalOrderError = NULL;')
end
mocks = mock_headers.map { |mock| File.basename(mock, '.*') }
mocks.each do |mock|
mock_clean = TypeSanitizer.sanitize_c_identifier(mock)
output.puts(" #{mock_clean}_Init();")
end
output.puts("}\n")
output.puts('static void CMock_Verify(void)')
output.puts('{')
mocks.each do |mock|
mock_clean = TypeSanitizer.sanitize_c_identifier(mock)
output.puts(" #{mock_clean}_Verify();")
end
output.puts("}\n")
output.puts('static void CMock_Destroy(void)')
output.puts('{')
mocks.each do |mock|
mock_clean = TypeSanitizer.sanitize_c_identifier(mock)
output.puts(" #{mock_clean}_Destroy();")
end
output.puts("}\n")
end
def create_setup(output)
return if @options[:has_setup]
output.puts("\n/*=======Setup (stub)=====*/")
output.puts("void #{@options[:setup_name]}(void) {}")
end
def create_teardown(output)
return if @options[:has_teardown]
output.puts("\n/*=======Teardown (stub)=====*/")
output.puts("void #{@options[:teardown_name]}(void) {}")
end
def create_suite_setup(output)
return if @options[:suite_setup].nil?
output.puts("\n/*=======Suite Setup=====*/")
output.puts('void suiteSetUp(void)')
output.puts('{')
output.puts(@options[:suite_setup])
output.puts('}')
end
def create_suite_teardown(output)
return if @options[:suite_teardown].nil?
output.puts("\n/*=======Suite Teardown=====*/")
output.puts('int suiteTearDown(int num_failures)')
output.puts('{')
output.puts(@options[:suite_teardown])
output.puts('}')
end
def create_reset(output)
output.puts("\n/*=======Test Reset Options=====*/")
output.puts("void #{@options[:test_reset_name]}(void);")
output.puts("void #{@options[:test_reset_name]}(void)")
output.puts('{')
output.puts(" #{@options[:teardown_name]}();")
output.puts(' CMock_Verify();')
output.puts(' CMock_Destroy();')
output.puts(' CMock_Init();')
output.puts(" #{@options[:setup_name]}();")
output.puts('}')
output.puts("void #{@options[:test_verify_name]}(void);")
output.puts("void #{@options[:test_verify_name]}(void)")
output.puts('{')
output.puts(' CMock_Verify();')
output.puts('}')
end
def create_run_test(output)
require 'erb'
template = ERB.new(File.read(File.join(__dir__, 'run_test.erb')), nil, '<>')
output.puts("\n" + template.result(binding))
end
def create_args_wrappers(output, tests)
return unless @options[:use_param_tests]
output.puts("\n/*=======Parameterized Test Wrappers=====*/")
tests.each do |test|
next if test[:args].nil? || test[:args].empty?
test[:args].each.with_index(1) do |args, idx|
output.puts("static void runner_args#{idx}_#{test[:test]}(void)")
output.puts('{')
output.puts(" #{test[:test]}(#{args});")
output.puts("}\n")
end
end
end
def create_main(output, filename, tests, used_mocks)
output.puts("\n/*=======MAIN=====*/")
main_name = @options[:main_name].to_sym == :auto ? "main_#{filename.gsub('.c', '')}" : (@options[:main_name]).to_s
if @options[:cmdline_args]
if main_name != 'main'
output.puts("#{@options[:main_export_decl]} int #{main_name}(int argc, char** argv);")
end
output.puts("#{@options[:main_export_decl]} int #{main_name}(int argc, char** argv)")
output.puts('{')
output.puts(' int parse_status = UnityParseOptions(argc, argv);')
output.puts(' if (parse_status != 0)')
output.puts(' {')
output.puts(' if (parse_status < 0)')
output.puts(' {')
output.puts(" UnityPrint(\"#{filename.gsub('.c', '')}.\");")
output.puts(' UNITY_PRINT_EOL();')
tests.each do |test|
if (!@options[:use_param_tests]) || test[:args].nil? || test[:args].empty?
output.puts(" UnityPrint(\" #{test[:test]}\");")
output.puts(' UNITY_PRINT_EOL();')
else
test[:args].each do |args|
output.puts(" UnityPrint(\" #{test[:test]}(#{args})\");")
output.puts(' UNITY_PRINT_EOL();')
end
end
end
output.puts(' return 0;')
output.puts(' }')
output.puts(' return parse_status;')
output.puts(' }')
else
main_return = @options[:omit_begin_end] ? 'void' : 'int'
if main_name != 'main'
output.puts("#{@options[:main_export_decl]} #{main_return} #{main_name}(void);")
end
output.puts("#{main_return} #{main_name}(void)")
output.puts('{')
end
output.puts(' suiteSetUp();') if @options[:has_suite_setup]
if @options[:omit_begin_end]
output.puts(" UnitySetTestFile(\"#{filename.gsub(/\\/, '\\\\\\')}\");")
else
output.puts(" UnityBegin(\"#{filename.gsub(/\\/, '\\\\\\')}\");")
end
tests.each do |test|
if (!@options[:use_param_tests]) || test[:args].nil? || test[:args].empty?
output.puts(" run_test(#{test[:test]}, \"#{test[:test]}\", #{test[:line_number]});")
else
test[:args].each.with_index(1) do |args, idx|
wrapper = "runner_args#{idx}_#{test[:test]}"
testname = "#{test[:test]}(#{args})".dump
output.puts(" run_test(#{wrapper}, #{testname}, #{test[:line_number]});")
end
end
end
output.puts
output.puts(' CMock_Guts_MemFreeFinal();') unless used_mocks.empty?
if @options[:has_suite_teardown]
if @options[:omit_begin_end]
output.puts(' (void) suite_teardown(0);')
else
output.puts(' return suiteTearDown(UnityEnd());')
end
else
output.puts(' return UnityEnd();') unless @options[:omit_begin_end]
end
output.puts('}')
end
def create_h_file(output, filename, tests, testfile_includes, used_mocks)
filename = File.basename(filename).gsub(/[-\/\\\.\,\s]/, '_').upcase
output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */')
output.puts("#ifndef _#{filename}")
output.puts("#define _#{filename}\n\n")
output.puts("#include \"#{@options[:framework]}.h\"")
output.puts('#include "cmock.h"') unless used_mocks.empty?
@options[:includes].flatten.uniq.compact.each do |inc|
output.puts("#include #{inc.include?('<') ? inc : "\"#{inc}\""}")
end
testfile_includes.each do |inc|
output.puts("#include #{inc.include?('<') ? inc : "\"#{inc}\""}")
end
output.puts "\n"
tests.each do |test|
if test[:params].nil? || test[:params].empty?
output.puts("void #{test[:test]}(void);")
else
output.puts("void #{test[:test]}(#{test[:params]});")
end
end
output.puts("#endif\n\n")
end
end
if $0 == __FILE__
options = { includes: [] }
# parse out all the options first (these will all be removed as we go)
ARGV.reject! do |arg|
case arg
when '-cexception'
options[:plugins] = [:cexception]
true
when /\.*\.ya?ml$/
options = UnityTestRunnerGenerator.grab_config(arg)
true
when /--(\w+)=\"?(.*)\"?/
options[Regexp.last_match(1).to_sym] = Regexp.last_match(2)
true
when /\.*\.(?:hpp|hh|H|h)$/
options[:includes] << arg
true
else false
end
end
# make sure there is at least one parameter left (the input file)
unless ARGV[0]
puts ["\nusage: ruby #{__FILE__} (files) (options) input_test_file (output)",
"\n input_test_file - this is the C file you want to create a runner for",
' output - this is the name of the runner file to generate',
' defaults to (input_test_file)_Runner',
' files:',
' *.yml / *.yaml - loads configuration from here in :unity or :cmock',
' *.h - header files are added as #includes in runner',
' options:',
' -cexception - include cexception support',
' -externc - add extern "C" for cpp support',
' --setup_name="" - redefine setUp func name to something else',
' --teardown_name="" - redefine tearDown func name to something else',
' --main_name="" - redefine main func name to something else',
' --test_prefix="" - redefine test prefix from default test|spec|should',
' --test_reset_name="" - redefine resetTest func name to something else',
' --test_verify_name="" - redefine verifyTest func name to something else',
' --suite_setup="" - code to execute for setup of entire suite',
' --suite_teardown="" - code to execute for teardown of entire suite',
' --use_param_tests=1 - enable parameterized tests (disabled by default)',
' --omit_begin_end=1 - omit calls to UnityBegin and UnityEnd (disabled by default)',
' --header_file="" - path/name of test header file to generate too'].join("\n")
exit 1
end
# create the default test runner name if not specified
ARGV[1] = ARGV[0].gsub('.c', '_Runner.c') unless ARGV[1]
UnityTestRunnerGenerator.new(options).run(ARGV[0], ARGV[1])
end
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/unity/generate_test_runner.rb | Ruby | apache-2.0 | 20,468 |
/*=======Test Runner Used To Run Each Test=====*/
static void run_test(UnityTestFunction func, const char* name, UNITY_LINE_TYPE line_num)
{
Unity.CurrentTestName = name;
Unity.CurrentTestLineNumber = line_num;
#ifdef UNITY_USE_COMMAND_LINE_ARGS
if (!UnityTestMatches())
return;
#endif
Unity.NumberOfTests++;
UNITY_CLR_DETAILS();
UNITY_EXEC_TIME_START();
CMock_Init();
if (TEST_PROTECT())
{
<% if @options[:plugins].include?(:cexception) %>
CEXCEPTION_T e;
Try {
<%= @options[:setup_name] %>();
func();
} Catch(e) {
TEST_ASSERT_EQUAL_HEX32_MESSAGE(CEXCEPTION_NONE, e, "Unhandled Exception!");
}
<% else %>
<%= @options[:setup_name] %>();
func();
<% end %>
}
if (TEST_PROTECT())
{
<%= @options[:teardown_name] %>();
CMock_Verify();
}
CMock_Destroy();
UNITY_EXEC_TIME_STOP();
UnityConcludeTest();
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/unity/run_test.erb | HTML+ERB | apache-2.0 | 969 |
module TypeSanitizer
def self.sanitize_c_identifier(unsanitized)
# convert filename to valid C identifier by replacing invalid chars with '_'
unsanitized.gsub(/[-\/\\\.\,\s]/, '_')
end
end
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/unity/type_sanitizer.rb | Ruby | apache-2.0 | 201 |
/* =========================================================================
Unity Project - A Test Framework for C
Copyright (c) 2007-21 Mike Karlesky, Mark VanderVoord, Greg Williams
[Released under MIT License. Please refer to license.txt for details]
============================================================================ */
#if LV_BUILD_TEST
#define UNITY_INCLUDE_PRINT_FORMATTED 1
#include "unity.h"
#include <stddef.h>
#ifdef AVR
#include <avr/pgmspace.h>
#else
#define PROGMEM
#endif
/* If omitted from header, declare overrideable prototypes here so they're ready for use */
#ifdef UNITY_OMIT_OUTPUT_CHAR_HEADER_DECLARATION
void UNITY_OUTPUT_CHAR(int);
#endif
/* Helpful macros for us to use here in Assert functions */
#define UNITY_FAIL_AND_BAIL { Unity.CurrentTestFailed = 1; UNITY_OUTPUT_FLUSH(); TEST_ABORT(); }
#define UNITY_IGNORE_AND_BAIL { Unity.CurrentTestIgnored = 1; UNITY_OUTPUT_FLUSH(); TEST_ABORT(); }
#define RETURN_IF_FAIL_OR_IGNORE if (Unity.CurrentTestFailed || Unity.CurrentTestIgnored) TEST_ABORT()
struct UNITY_STORAGE_T Unity;
#ifdef UNITY_OUTPUT_COLOR
const char PROGMEM UnityStrOk[] = "\033[42mOK\033[00m";
const char PROGMEM UnityStrPass[] = "\033[42mPASS\033[00m";
const char PROGMEM UnityStrFail[] = "\033[41mFAIL\033[00m";
const char PROGMEM UnityStrIgnore[] = "\033[43mIGNORE\033[00m";
#else
const char PROGMEM UnityStrOk[] = "OK";
const char PROGMEM UnityStrPass[] = "PASS";
const char PROGMEM UnityStrFail[] = "FAIL";
const char PROGMEM UnityStrIgnore[] = "IGNORE";
#endif
static const char PROGMEM UnityStrNull[] = "NULL";
static const char PROGMEM UnityStrSpacer[] = ". ";
static const char PROGMEM UnityStrExpected[] = " Expected ";
static const char PROGMEM UnityStrWas[] = " Was ";
static const char PROGMEM UnityStrGt[] = " to be greater than ";
static const char PROGMEM UnityStrLt[] = " to be less than ";
static const char PROGMEM UnityStrOrEqual[] = "or equal to ";
static const char PROGMEM UnityStrNotEqual[] = " to be not equal to ";
static const char PROGMEM UnityStrElement[] = " Element ";
static const char PROGMEM UnityStrByte[] = " Byte ";
static const char PROGMEM UnityStrMemory[] = " Memory Mismatch.";
static const char PROGMEM UnityStrDelta[] = " Values Not Within Delta ";
static const char PROGMEM UnityStrPointless[] = " You Asked Me To Compare Nothing, Which Was Pointless.";
static const char PROGMEM UnityStrNullPointerForExpected[] = " Expected pointer to be NULL";
static const char PROGMEM UnityStrNullPointerForActual[] = " Actual pointer was NULL";
#ifndef UNITY_EXCLUDE_FLOAT
static const char PROGMEM UnityStrNot[] = "Not ";
static const char PROGMEM UnityStrInf[] = "Infinity";
static const char PROGMEM UnityStrNegInf[] = "Negative Infinity";
static const char PROGMEM UnityStrNaN[] = "NaN";
static const char PROGMEM UnityStrDet[] = "Determinate";
static const char PROGMEM UnityStrInvalidFloatTrait[] = "Invalid Float Trait";
#endif
const char PROGMEM UnityStrErrShorthand[] = "Unity Shorthand Support Disabled";
const char PROGMEM UnityStrErrFloat[] = "Unity Floating Point Disabled";
const char PROGMEM UnityStrErrDouble[] = "Unity Double Precision Disabled";
const char PROGMEM UnityStrErr64[] = "Unity 64-bit Support Disabled";
static const char PROGMEM UnityStrBreaker[] = "-----------------------";
static const char PROGMEM UnityStrResultsTests[] = " Tests ";
static const char PROGMEM UnityStrResultsFailures[] = " Failures ";
static const char PROGMEM UnityStrResultsIgnored[] = " Ignored ";
#ifndef UNITY_EXCLUDE_DETAILS
static const char PROGMEM UnityStrDetail1Name[] = UNITY_DETAIL1_NAME " ";
static const char PROGMEM UnityStrDetail2Name[] = " " UNITY_DETAIL2_NAME " ";
#endif
/*-----------------------------------------------
* Pretty Printers & Test Result Output Handlers
*-----------------------------------------------*/
/*-----------------------------------------------*/
/* Local helper function to print characters. */
static void UnityPrintChar(const char* pch)
{
/* printable characters plus CR & LF are printed */
if ((*pch <= 126) && (*pch >= 32))
{
UNITY_OUTPUT_CHAR(*pch);
}
/* write escaped carriage returns */
else if (*pch == 13)
{
UNITY_OUTPUT_CHAR('\\');
UNITY_OUTPUT_CHAR('r');
}
/* write escaped line feeds */
else if (*pch == 10)
{
UNITY_OUTPUT_CHAR('\\');
UNITY_OUTPUT_CHAR('n');
}
/* unprintable characters are shown as codes */
else
{
UNITY_OUTPUT_CHAR('\\');
UNITY_OUTPUT_CHAR('x');
UnityPrintNumberHex((UNITY_UINT)*pch, 2);
}
}
/*-----------------------------------------------*/
/* Local helper function to print ANSI escape strings e.g. "\033[42m". */
#ifdef UNITY_OUTPUT_COLOR
static UNITY_UINT UnityPrintAnsiEscapeString(const char* string)
{
const char* pch = string;
UNITY_UINT count = 0;
while (*pch && (*pch != 'm'))
{
UNITY_OUTPUT_CHAR(*pch);
pch++;
count++;
}
UNITY_OUTPUT_CHAR('m');
count++;
return count;
}
#endif
/*-----------------------------------------------*/
void UnityPrint(const char* string)
{
const char* pch = string;
if (pch != NULL)
{
while (*pch)
{
#ifdef UNITY_OUTPUT_COLOR
/* print ANSI escape code */
if ((*pch == 27) && (*(pch + 1) == '['))
{
pch += UnityPrintAnsiEscapeString(pch);
continue;
}
#endif
UnityPrintChar(pch);
pch++;
}
}
}
/*-----------------------------------------------*/
void UnityPrintLen(const char* string, const UNITY_UINT32 length)
{
const char* pch = string;
if (pch != NULL)
{
while (*pch && ((UNITY_UINT32)(pch - string) < length))
{
/* printable characters plus CR & LF are printed */
if ((*pch <= 126) && (*pch >= 32))
{
UNITY_OUTPUT_CHAR(*pch);
}
/* write escaped carriage returns */
else if (*pch == 13)
{
UNITY_OUTPUT_CHAR('\\');
UNITY_OUTPUT_CHAR('r');
}
/* write escaped line feeds */
else if (*pch == 10)
{
UNITY_OUTPUT_CHAR('\\');
UNITY_OUTPUT_CHAR('n');
}
/* unprintable characters are shown as codes */
else
{
UNITY_OUTPUT_CHAR('\\');
UNITY_OUTPUT_CHAR('x');
UnityPrintNumberHex((UNITY_UINT)*pch, 2);
}
pch++;
}
}
}
/*-----------------------------------------------*/
void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style)
{
if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT)
{
if (style == UNITY_DISPLAY_STYLE_CHAR)
{
/* printable characters plus CR & LF are printed */
UNITY_OUTPUT_CHAR('\'');
if ((number <= 126) && (number >= 32))
{
UNITY_OUTPUT_CHAR((int)number);
}
/* write escaped carriage returns */
else if (number == 13)
{
UNITY_OUTPUT_CHAR('\\');
UNITY_OUTPUT_CHAR('r');
}
/* write escaped line feeds */
else if (number == 10)
{
UNITY_OUTPUT_CHAR('\\');
UNITY_OUTPUT_CHAR('n');
}
/* unprintable characters are shown as codes */
else
{
UNITY_OUTPUT_CHAR('\\');
UNITY_OUTPUT_CHAR('x');
UnityPrintNumberHex((UNITY_UINT)number, 2);
}
UNITY_OUTPUT_CHAR('\'');
}
else
{
UnityPrintNumber(number);
}
}
else if ((style & UNITY_DISPLAY_RANGE_UINT) == UNITY_DISPLAY_RANGE_UINT)
{
UnityPrintNumberUnsigned((UNITY_UINT)number);
}
else
{
UNITY_OUTPUT_CHAR('0');
UNITY_OUTPUT_CHAR('x');
UnityPrintNumberHex((UNITY_UINT)number, (char)((style & 0xF) * 2));
}
}
/*-----------------------------------------------*/
void UnityPrintNumber(const UNITY_INT number_to_print)
{
UNITY_UINT number = (UNITY_UINT)number_to_print;
if (number_to_print < 0)
{
/* A negative number, including MIN negative */
UNITY_OUTPUT_CHAR('-');
number = (~number) + 1;
}
UnityPrintNumberUnsigned(number);
}
/*-----------------------------------------------
* basically do an itoa using as little ram as possible */
void UnityPrintNumberUnsigned(const UNITY_UINT number)
{
UNITY_UINT divisor = 1;
/* figure out initial divisor */
while (number / divisor > 9)
{
divisor *= 10;
}
/* now mod and print, then divide divisor */
do
{
UNITY_OUTPUT_CHAR((char)('0' + (number / divisor % 10)));
divisor /= 10;
} while (divisor > 0);
}
/*-----------------------------------------------*/
void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles_to_print)
{
int nibble;
char nibbles = nibbles_to_print;
if ((unsigned)nibbles > UNITY_MAX_NIBBLES)
{
nibbles = UNITY_MAX_NIBBLES;
}
while (nibbles > 0)
{
nibbles--;
nibble = (int)(number >> (nibbles * 4)) & 0x0F;
if (nibble <= 9)
{
UNITY_OUTPUT_CHAR((char)('0' + nibble));
}
else
{
UNITY_OUTPUT_CHAR((char)('A' - 10 + nibble));
}
}
}
/*-----------------------------------------------*/
void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number)
{
UNITY_UINT current_bit = (UNITY_UINT)1 << (UNITY_INT_WIDTH - 1);
UNITY_INT32 i;
for (i = 0; i < UNITY_INT_WIDTH; i++)
{
if (current_bit & mask)
{
if (current_bit & number)
{
UNITY_OUTPUT_CHAR('1');
}
else
{
UNITY_OUTPUT_CHAR('0');
}
}
else
{
UNITY_OUTPUT_CHAR('X');
}
current_bit = current_bit >> 1;
}
}
/*-----------------------------------------------*/
#ifndef UNITY_EXCLUDE_FLOAT_PRINT
/*
* This function prints a floating-point value in a format similar to
* printf("%.7g") on a single-precision machine or printf("%.9g") on a
* double-precision machine. The 7th digit won't always be totally correct
* in single-precision operation (for that level of accuracy, a more
* complicated algorithm would be needed).
*/
void UnityPrintFloat(const UNITY_DOUBLE input_number)
{
#ifdef UNITY_INCLUDE_DOUBLE
static const int sig_digits = 9;
static const UNITY_INT32 min_scaled = 100000000;
static const UNITY_INT32 max_scaled = 1000000000;
#else
static const int sig_digits = 7;
static const UNITY_INT32 min_scaled = 1000000;
static const UNITY_INT32 max_scaled = 10000000;
#endif
UNITY_DOUBLE number = input_number;
/* print minus sign (does not handle negative zero) */
if (number < 0.0f)
{
UNITY_OUTPUT_CHAR('-');
number = -number;
}
/* handle zero, NaN, and +/- infinity */
if (number == 0.0f)
{
UnityPrint("0");
}
else if (isnan(number))
{
UnityPrint("nan");
}
else if (isinf(number))
{
UnityPrint("inf");
}
else
{
UNITY_INT32 n_int = 0, n;
int exponent = 0;
int decimals, digits;
char buf[16] = {0};
/*
* Scale up or down by powers of 10. To minimize rounding error,
* start with a factor/divisor of 10^10, which is the largest
* power of 10 that can be represented exactly. Finally, compute
* (exactly) the remaining power of 10 and perform one more
* multiplication or division.
*/
if (number < 1.0f)
{
UNITY_DOUBLE factor = 1.0f;
while (number < (UNITY_DOUBLE)max_scaled / 1e10f) { number *= 1e10f; exponent -= 10; }
while (number * factor < (UNITY_DOUBLE)min_scaled) { factor *= 10.0f; exponent--; }
number *= factor;
}
else if (number > (UNITY_DOUBLE)max_scaled)
{
UNITY_DOUBLE divisor = 1.0f;
while (number > (UNITY_DOUBLE)min_scaled * 1e10f) { number /= 1e10f; exponent += 10; }
while (number / divisor > (UNITY_DOUBLE)max_scaled) { divisor *= 10.0f; exponent++; }
number /= divisor;
}
else
{
/*
* In this range, we can split off the integer part before
* doing any multiplications. This reduces rounding error by
* freeing up significant bits in the fractional part.
*/
UNITY_DOUBLE factor = 1.0f;
n_int = (UNITY_INT32)number;
number -= (UNITY_DOUBLE)n_int;
while (n_int < min_scaled) { n_int *= 10; factor *= 10.0f; exponent--; }
number *= factor;
}
/* round to nearest integer */
n = ((UNITY_INT32)(number + number) + 1) / 2;
#ifndef UNITY_ROUND_TIES_AWAY_FROM_ZERO
/* round to even if exactly between two integers */
if ((n & 1) && (((UNITY_DOUBLE)n - number) == 0.5f))
n--;
#endif
n += n_int;
if (n >= max_scaled)
{
n = min_scaled;
exponent++;
}
/* determine where to place decimal point */
decimals = ((exponent <= 0) && (exponent >= -(sig_digits + 3))) ? (-exponent) : (sig_digits - 1);
exponent += decimals;
/* truncate trailing zeroes after decimal point */
while ((decimals > 0) && ((n % 10) == 0))
{
n /= 10;
decimals--;
}
/* build up buffer in reverse order */
digits = 0;
while ((n != 0) || (digits < (decimals + 1)))
{
buf[digits++] = (char)('0' + n % 10);
n /= 10;
}
while (digits > 0)
{
if (digits == decimals) { UNITY_OUTPUT_CHAR('.'); }
UNITY_OUTPUT_CHAR(buf[--digits]);
}
/* print exponent if needed */
if (exponent != 0)
{
UNITY_OUTPUT_CHAR('e');
if (exponent < 0)
{
UNITY_OUTPUT_CHAR('-');
exponent = -exponent;
}
else
{
UNITY_OUTPUT_CHAR('+');
}
digits = 0;
while ((exponent != 0) || (digits < 2))
{
buf[digits++] = (char)('0' + exponent % 10);
exponent /= 10;
}
while (digits > 0)
{
UNITY_OUTPUT_CHAR(buf[--digits]);
}
}
}
}
#endif /* ! UNITY_EXCLUDE_FLOAT_PRINT */
/*-----------------------------------------------*/
static void UnityTestResultsBegin(const char* file, const UNITY_LINE_TYPE line)
{
#ifdef UNITY_OUTPUT_FOR_ECLIPSE
UNITY_OUTPUT_CHAR('(');
UnityPrint(file);
UNITY_OUTPUT_CHAR(':');
UnityPrintNumber((UNITY_INT)line);
UNITY_OUTPUT_CHAR(')');
UNITY_OUTPUT_CHAR(' ');
UnityPrint(Unity.CurrentTestName);
UNITY_OUTPUT_CHAR(':');
#else
#ifdef UNITY_OUTPUT_FOR_IAR_WORKBENCH
UnityPrint("<SRCREF line=");
UnityPrintNumber((UNITY_INT)line);
UnityPrint(" file=\"");
UnityPrint(file);
UNITY_OUTPUT_CHAR('"');
UNITY_OUTPUT_CHAR('>');
UnityPrint(Unity.CurrentTestName);
UnityPrint("</SRCREF> ");
#else
#ifdef UNITY_OUTPUT_FOR_QT_CREATOR
UnityPrint("file://");
UnityPrint(file);
UNITY_OUTPUT_CHAR(':');
UnityPrintNumber((UNITY_INT)line);
UNITY_OUTPUT_CHAR(' ');
UnityPrint(Unity.CurrentTestName);
UNITY_OUTPUT_CHAR(':');
#else
UnityPrint(file);
UNITY_OUTPUT_CHAR(':');
UnityPrintNumber((UNITY_INT)line);
UNITY_OUTPUT_CHAR(':');
UnityPrint(Unity.CurrentTestName);
UNITY_OUTPUT_CHAR(':');
#endif
#endif
#endif
}
/*-----------------------------------------------*/
static void UnityTestResultsFailBegin(const UNITY_LINE_TYPE line)
{
UnityTestResultsBegin(Unity.TestFile, line);
UnityPrint(UnityStrFail);
UNITY_OUTPUT_CHAR(':');
}
/*-----------------------------------------------*/
void UnityConcludeTest(void)
{
if (Unity.CurrentTestIgnored)
{
Unity.TestIgnores++;
}
else if (!Unity.CurrentTestFailed)
{
UnityTestResultsBegin(Unity.TestFile, Unity.CurrentTestLineNumber);
UnityPrint(UnityStrPass);
}
else
{
Unity.TestFailures++;
}
Unity.CurrentTestFailed = 0;
Unity.CurrentTestIgnored = 0;
UNITY_PRINT_EXEC_TIME();
UNITY_PRINT_EOL();
UNITY_FLUSH_CALL();
}
/*-----------------------------------------------*/
static void UnityAddMsgIfSpecified(const char* msg)
{
if (msg)
{
UnityPrint(UnityStrSpacer);
#ifdef UNITY_PRINT_TEST_CONTEXT
UNITY_PRINT_TEST_CONTEXT();
#endif
#ifndef UNITY_EXCLUDE_DETAILS
if (Unity.CurrentDetail1)
{
UnityPrint(UnityStrDetail1Name);
UnityPrint(Unity.CurrentDetail1);
if (Unity.CurrentDetail2)
{
UnityPrint(UnityStrDetail2Name);
UnityPrint(Unity.CurrentDetail2);
}
UnityPrint(UnityStrSpacer);
}
#endif
UnityPrint(msg);
}
}
/*-----------------------------------------------*/
static void UnityPrintExpectedAndActualStrings(const char* expected, const char* actual)
{
UnityPrint(UnityStrExpected);
if (expected != NULL)
{
UNITY_OUTPUT_CHAR('\'');
UnityPrint(expected);
UNITY_OUTPUT_CHAR('\'');
}
else
{
UnityPrint(UnityStrNull);
}
UnityPrint(UnityStrWas);
if (actual != NULL)
{
UNITY_OUTPUT_CHAR('\'');
UnityPrint(actual);
UNITY_OUTPUT_CHAR('\'');
}
else
{
UnityPrint(UnityStrNull);
}
}
/*-----------------------------------------------*/
static void UnityPrintExpectedAndActualStringsLen(const char* expected,
const char* actual,
const UNITY_UINT32 length)
{
UnityPrint(UnityStrExpected);
if (expected != NULL)
{
UNITY_OUTPUT_CHAR('\'');
UnityPrintLen(expected, length);
UNITY_OUTPUT_CHAR('\'');
}
else
{
UnityPrint(UnityStrNull);
}
UnityPrint(UnityStrWas);
if (actual != NULL)
{
UNITY_OUTPUT_CHAR('\'');
UnityPrintLen(actual, length);
UNITY_OUTPUT_CHAR('\'');
}
else
{
UnityPrint(UnityStrNull);
}
}
/*-----------------------------------------------
* Assertion & Control Helpers
*-----------------------------------------------*/
/*-----------------------------------------------*/
static int UnityIsOneArrayNull(UNITY_INTERNAL_PTR expected,
UNITY_INTERNAL_PTR actual,
const UNITY_LINE_TYPE lineNumber,
const char* msg)
{
/* Both are NULL or same pointer */
if (expected == actual) { return 0; }
/* print and return true if just expected is NULL */
if (expected == NULL)
{
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrNullPointerForExpected);
UnityAddMsgIfSpecified(msg);
return 1;
}
/* print and return true if just actual is NULL */
if (actual == NULL)
{
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrNullPointerForActual);
UnityAddMsgIfSpecified(msg);
return 1;
}
return 0; /* return false if neither is NULL */
}
/*-----------------------------------------------
* Assertion Functions
*-----------------------------------------------*/
/*-----------------------------------------------*/
void UnityAssertBits(const UNITY_INT mask,
const UNITY_INT expected,
const UNITY_INT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber)
{
RETURN_IF_FAIL_OR_IGNORE;
if ((mask & expected) != (mask & actual))
{
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrExpected);
UnityPrintMask((UNITY_UINT)mask, (UNITY_UINT)expected);
UnityPrint(UnityStrWas);
UnityPrintMask((UNITY_UINT)mask, (UNITY_UINT)actual);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
}
/*-----------------------------------------------*/
void UnityAssertEqualNumber(const UNITY_INT expected,
const UNITY_INT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style)
{
RETURN_IF_FAIL_OR_IGNORE;
if (expected != actual)
{
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrExpected);
UnityPrintNumberByStyle(expected, style);
UnityPrint(UnityStrWas);
UnityPrintNumberByStyle(actual, style);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
}
/*-----------------------------------------------*/
void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold,
const UNITY_INT actual,
const UNITY_COMPARISON_T compare,
const char *msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style)
{
int failed = 0;
RETURN_IF_FAIL_OR_IGNORE;
if ((threshold == actual) && (compare & UNITY_EQUAL_TO)) { return; }
if ((threshold == actual)) { failed = 1; }
if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT)
{
if ((actual > threshold) && (compare & UNITY_SMALLER_THAN)) { failed = 1; }
if ((actual < threshold) && (compare & UNITY_GREATER_THAN)) { failed = 1; }
}
else /* UINT or HEX */
{
if (((UNITY_UINT)actual > (UNITY_UINT)threshold) && (compare & UNITY_SMALLER_THAN)) { failed = 1; }
if (((UNITY_UINT)actual < (UNITY_UINT)threshold) && (compare & UNITY_GREATER_THAN)) { failed = 1; }
}
if (failed)
{
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrExpected);
UnityPrintNumberByStyle(actual, style);
if (compare & UNITY_GREATER_THAN) { UnityPrint(UnityStrGt); }
if (compare & UNITY_SMALLER_THAN) { UnityPrint(UnityStrLt); }
if (compare & UNITY_EQUAL_TO) { UnityPrint(UnityStrOrEqual); }
if (compare == UNITY_NOT_EQUAL) { UnityPrint(UnityStrNotEqual); }
UnityPrintNumberByStyle(threshold, style);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
}
#define UnityPrintPointlessAndBail() \
{ \
UnityTestResultsFailBegin(lineNumber); \
UnityPrint(UnityStrPointless); \
UnityAddMsgIfSpecified(msg); \
UNITY_FAIL_AND_BAIL; }
/*-----------------------------------------------*/
void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected,
UNITY_INTERNAL_PTR actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style,
const UNITY_FLAGS_T flags)
{
UNITY_UINT32 elements = num_elements;
unsigned int length = style & 0xF;
unsigned int increment = 0;
RETURN_IF_FAIL_OR_IGNORE;
if (num_elements == 0)
{
UnityPrintPointlessAndBail();
}
if (expected == actual)
{
return; /* Both are NULL or same pointer */
}
if (UnityIsOneArrayNull(expected, actual, lineNumber, msg))
{
UNITY_FAIL_AND_BAIL;
}
while ((elements > 0) && (elements--))
{
UNITY_INT expect_val;
UNITY_INT actual_val;
switch (length)
{
case 1:
expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)expected;
actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)actual;
increment = sizeof(UNITY_INT8);
break;
case 2:
expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)expected;
actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)actual;
increment = sizeof(UNITY_INT16);
break;
#ifdef UNITY_SUPPORT_64
case 8:
expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)expected;
actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)actual;
increment = sizeof(UNITY_INT64);
break;
#endif
default: /* default is length 4 bytes */
case 4:
expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)expected;
actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)actual;
increment = sizeof(UNITY_INT32);
length = 4;
break;
}
if (expect_val != actual_val)
{
if ((style & UNITY_DISPLAY_RANGE_UINT) && (length < (UNITY_INT_WIDTH / 8)))
{ /* For UINT, remove sign extension (padding 1's) from signed type casts above */
UNITY_INT mask = 1;
mask = (mask << 8 * length) - 1;
expect_val &= mask;
actual_val &= mask;
}
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrElement);
UnityPrintNumberUnsigned(num_elements - elements - 1);
UnityPrint(UnityStrExpected);
UnityPrintNumberByStyle(expect_val, style);
UnityPrint(UnityStrWas);
UnityPrintNumberByStyle(actual_val, style);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
/* Walk through array by incrementing the pointers */
if (flags == UNITY_ARRAY_TO_ARRAY)
{
expected = (UNITY_INTERNAL_PTR)((const char*)expected + increment);
}
actual = (UNITY_INTERNAL_PTR)((const char*)actual + increment);
}
}
/*-----------------------------------------------*/
#ifndef UNITY_EXCLUDE_FLOAT
/* Wrap this define in a function with variable types as float or double */
#define UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff) \
if (isinf(expected) && isinf(actual) && (((expected) < 0) == ((actual) < 0))) return 1; \
if (UNITY_NAN_CHECK) return 1; \
(diff) = (actual) - (expected); \
if ((diff) < 0) (diff) = -(diff); \
if ((delta) < 0) (delta) = -(delta); \
return !(isnan(diff) || isinf(diff) || ((diff) > (delta)))
/* This first part of this condition will catch any NaN or Infinite values */
#ifndef UNITY_NAN_NOT_EQUAL_NAN
#define UNITY_NAN_CHECK isnan(expected) && isnan(actual)
#else
#define UNITY_NAN_CHECK 0
#endif
#ifndef UNITY_EXCLUDE_FLOAT_PRINT
#define UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual) \
{ \
UnityPrint(UnityStrExpected); \
UnityPrintFloat(expected); \
UnityPrint(UnityStrWas); \
UnityPrintFloat(actual); }
#else
#define UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual) \
UnityPrint(UnityStrDelta)
#endif /* UNITY_EXCLUDE_FLOAT_PRINT */
/*-----------------------------------------------*/
static int UnityFloatsWithin(UNITY_FLOAT delta, UNITY_FLOAT expected, UNITY_FLOAT actual)
{
UNITY_FLOAT diff;
UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff);
}
/*-----------------------------------------------*/
void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected,
UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLAGS_T flags)
{
UNITY_UINT32 elements = num_elements;
UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* ptr_expected = expected;
UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* ptr_actual = actual;
RETURN_IF_FAIL_OR_IGNORE;
if (elements == 0)
{
UnityPrintPointlessAndBail();
}
if (expected == actual)
{
return; /* Both are NULL or same pointer */
}
if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg))
{
UNITY_FAIL_AND_BAIL;
}
while (elements--)
{
if (!UnityFloatsWithin(*ptr_expected * UNITY_FLOAT_PRECISION, *ptr_expected, *ptr_actual))
{
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrElement);
UnityPrintNumberUnsigned(num_elements - elements - 1);
UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT((UNITY_DOUBLE)*ptr_expected, (UNITY_DOUBLE)*ptr_actual);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
if (flags == UNITY_ARRAY_TO_ARRAY)
{
ptr_expected++;
}
ptr_actual++;
}
}
/*-----------------------------------------------*/
void UnityAssertFloatsWithin(const UNITY_FLOAT delta,
const UNITY_FLOAT expected,
const UNITY_FLOAT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber)
{
RETURN_IF_FAIL_OR_IGNORE;
if (!UnityFloatsWithin(delta, expected, actual))
{
UnityTestResultsFailBegin(lineNumber);
UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT((UNITY_DOUBLE)expected, (UNITY_DOUBLE)actual);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
}
/*-----------------------------------------------*/
void UnityAssertFloatSpecial(const UNITY_FLOAT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLOAT_TRAIT_T style)
{
const char* trait_names[] = {UnityStrInf, UnityStrNegInf, UnityStrNaN, UnityStrDet};
UNITY_INT should_be_trait = ((UNITY_INT)style & 1);
UNITY_INT is_trait = !should_be_trait;
UNITY_INT trait_index = (UNITY_INT)(style >> 1);
RETURN_IF_FAIL_OR_IGNORE;
switch (style)
{
case UNITY_FLOAT_IS_INF:
case UNITY_FLOAT_IS_NOT_INF:
is_trait = isinf(actual) && (actual > 0);
break;
case UNITY_FLOAT_IS_NEG_INF:
case UNITY_FLOAT_IS_NOT_NEG_INF:
is_trait = isinf(actual) && (actual < 0);
break;
case UNITY_FLOAT_IS_NAN:
case UNITY_FLOAT_IS_NOT_NAN:
is_trait = isnan(actual) ? 1 : 0;
break;
case UNITY_FLOAT_IS_DET: /* A determinate number is non infinite and not NaN. */
case UNITY_FLOAT_IS_NOT_DET:
is_trait = !isinf(actual) && !isnan(actual);
break;
default: /* including UNITY_FLOAT_INVALID_TRAIT */
trait_index = 0;
trait_names[0] = UnityStrInvalidFloatTrait;
break;
}
if (is_trait != should_be_trait)
{
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrExpected);
if (!should_be_trait)
{
UnityPrint(UnityStrNot);
}
UnityPrint(trait_names[trait_index]);
UnityPrint(UnityStrWas);
#ifndef UNITY_EXCLUDE_FLOAT_PRINT
UnityPrintFloat((UNITY_DOUBLE)actual);
#else
if (should_be_trait)
{
UnityPrint(UnityStrNot);
}
UnityPrint(trait_names[trait_index]);
#endif
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
}
#endif /* not UNITY_EXCLUDE_FLOAT */
/*-----------------------------------------------*/
#ifndef UNITY_EXCLUDE_DOUBLE
static int UnityDoublesWithin(UNITY_DOUBLE delta, UNITY_DOUBLE expected, UNITY_DOUBLE actual)
{
UNITY_DOUBLE diff;
UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff);
}
/*-----------------------------------------------*/
void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected,
UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLAGS_T flags)
{
UNITY_UINT32 elements = num_elements;
UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* ptr_expected = expected;
UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* ptr_actual = actual;
RETURN_IF_FAIL_OR_IGNORE;
if (elements == 0)
{
UnityPrintPointlessAndBail();
}
if (expected == actual)
{
return; /* Both are NULL or same pointer */
}
if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg))
{
UNITY_FAIL_AND_BAIL;
}
while (elements--)
{
if (!UnityDoublesWithin(*ptr_expected * UNITY_DOUBLE_PRECISION, *ptr_expected, *ptr_actual))
{
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrElement);
UnityPrintNumberUnsigned(num_elements - elements - 1);
UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(*ptr_expected, *ptr_actual);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
if (flags == UNITY_ARRAY_TO_ARRAY)
{
ptr_expected++;
}
ptr_actual++;
}
}
/*-----------------------------------------------*/
void UnityAssertDoublesWithin(const UNITY_DOUBLE delta,
const UNITY_DOUBLE expected,
const UNITY_DOUBLE actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber)
{
RETURN_IF_FAIL_OR_IGNORE;
if (!UnityDoublesWithin(delta, expected, actual))
{
UnityTestResultsFailBegin(lineNumber);
UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
}
/*-----------------------------------------------*/
void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLOAT_TRAIT_T style)
{
const char* trait_names[] = {UnityStrInf, UnityStrNegInf, UnityStrNaN, UnityStrDet};
UNITY_INT should_be_trait = ((UNITY_INT)style & 1);
UNITY_INT is_trait = !should_be_trait;
UNITY_INT trait_index = (UNITY_INT)(style >> 1);
RETURN_IF_FAIL_OR_IGNORE;
switch (style)
{
case UNITY_FLOAT_IS_INF:
case UNITY_FLOAT_IS_NOT_INF:
is_trait = isinf(actual) && (actual > 0);
break;
case UNITY_FLOAT_IS_NEG_INF:
case UNITY_FLOAT_IS_NOT_NEG_INF:
is_trait = isinf(actual) && (actual < 0);
break;
case UNITY_FLOAT_IS_NAN:
case UNITY_FLOAT_IS_NOT_NAN:
is_trait = isnan(actual) ? 1 : 0;
break;
case UNITY_FLOAT_IS_DET: /* A determinate number is non infinite and not NaN. */
case UNITY_FLOAT_IS_NOT_DET:
is_trait = !isinf(actual) && !isnan(actual);
break;
default: /* including UNITY_FLOAT_INVALID_TRAIT */
trait_index = 0;
trait_names[0] = UnityStrInvalidFloatTrait;
break;
}
if (is_trait != should_be_trait)
{
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrExpected);
if (!should_be_trait)
{
UnityPrint(UnityStrNot);
}
UnityPrint(trait_names[trait_index]);
UnityPrint(UnityStrWas);
#ifndef UNITY_EXCLUDE_FLOAT_PRINT
UnityPrintFloat(actual);
#else
if (should_be_trait)
{
UnityPrint(UnityStrNot);
}
UnityPrint(trait_names[trait_index]);
#endif
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
}
#endif /* not UNITY_EXCLUDE_DOUBLE */
/*-----------------------------------------------*/
void UnityAssertNumbersWithin(const UNITY_UINT delta,
const UNITY_INT expected,
const UNITY_INT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style)
{
RETURN_IF_FAIL_OR_IGNORE;
if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT)
{
if (actual > expected)
{
Unity.CurrentTestFailed = (((UNITY_UINT)actual - (UNITY_UINT)expected) > delta);
}
else
{
Unity.CurrentTestFailed = (((UNITY_UINT)expected - (UNITY_UINT)actual) > delta);
}
}
else
{
if ((UNITY_UINT)actual > (UNITY_UINT)expected)
{
Unity.CurrentTestFailed = (((UNITY_UINT)actual - (UNITY_UINT)expected) > delta);
}
else
{
Unity.CurrentTestFailed = (((UNITY_UINT)expected - (UNITY_UINT)actual) > delta);
}
}
if (Unity.CurrentTestFailed)
{
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrDelta);
UnityPrintNumberByStyle((UNITY_INT)delta, style);
UnityPrint(UnityStrExpected);
UnityPrintNumberByStyle(expected, style);
UnityPrint(UnityStrWas);
UnityPrintNumberByStyle(actual, style);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
}
/*-----------------------------------------------*/
void UnityAssertNumbersArrayWithin(const UNITY_UINT delta,
UNITY_INTERNAL_PTR expected,
UNITY_INTERNAL_PTR actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style,
const UNITY_FLAGS_T flags)
{
UNITY_UINT32 elements = num_elements;
unsigned int length = style & 0xF;
unsigned int increment = 0;
RETURN_IF_FAIL_OR_IGNORE;
if (num_elements == 0)
{
UnityPrintPointlessAndBail();
}
if (expected == actual)
{
return; /* Both are NULL or same pointer */
}
if (UnityIsOneArrayNull(expected, actual, lineNumber, msg))
{
UNITY_FAIL_AND_BAIL;
}
while ((elements > 0) && (elements--))
{
UNITY_INT expect_val;
UNITY_INT actual_val;
switch (length)
{
case 1:
expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)expected;
actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)actual;
increment = sizeof(UNITY_INT8);
break;
case 2:
expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)expected;
actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)actual;
increment = sizeof(UNITY_INT16);
break;
#ifdef UNITY_SUPPORT_64
case 8:
expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)expected;
actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)actual;
increment = sizeof(UNITY_INT64);
break;
#endif
default: /* default is length 4 bytes */
case 4:
expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)expected;
actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)actual;
increment = sizeof(UNITY_INT32);
length = 4;
break;
}
if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT)
{
if (actual_val > expect_val)
{
Unity.CurrentTestFailed = (((UNITY_UINT)actual_val - (UNITY_UINT)expect_val) > delta);
}
else
{
Unity.CurrentTestFailed = (((UNITY_UINT)expect_val - (UNITY_UINT)actual_val) > delta);
}
}
else
{
if ((UNITY_UINT)actual_val > (UNITY_UINT)expect_val)
{
Unity.CurrentTestFailed = (((UNITY_UINT)actual_val - (UNITY_UINT)expect_val) > delta);
}
else
{
Unity.CurrentTestFailed = (((UNITY_UINT)expect_val - (UNITY_UINT)actual_val) > delta);
}
}
if (Unity.CurrentTestFailed)
{
if ((style & UNITY_DISPLAY_RANGE_UINT) && (length < (UNITY_INT_WIDTH / 8)))
{ /* For UINT, remove sign extension (padding 1's) from signed type casts above */
UNITY_INT mask = 1;
mask = (mask << 8 * length) - 1;
expect_val &= mask;
actual_val &= mask;
}
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrDelta);
UnityPrintNumberByStyle((UNITY_INT)delta, style);
UnityPrint(UnityStrElement);
UnityPrintNumberUnsigned(num_elements - elements - 1);
UnityPrint(UnityStrExpected);
UnityPrintNumberByStyle(expect_val, style);
UnityPrint(UnityStrWas);
UnityPrintNumberByStyle(actual_val, style);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
/* Walk through array by incrementing the pointers */
if (flags == UNITY_ARRAY_TO_ARRAY)
{
expected = (UNITY_INTERNAL_PTR)((const char*)expected + increment);
}
actual = (UNITY_INTERNAL_PTR)((const char*)actual + increment);
}
}
/*-----------------------------------------------*/
void UnityAssertEqualString(const char* expected,
const char* actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber)
{
UNITY_UINT32 i;
RETURN_IF_FAIL_OR_IGNORE;
/* if both pointers not null compare the strings */
if (expected && actual)
{
for (i = 0; expected[i] || actual[i]; i++)
{
if (expected[i] != actual[i])
{
Unity.CurrentTestFailed = 1;
break;
}
}
}
else
{ /* handle case of one pointers being null (if both null, test should pass) */
if (expected != actual)
{
Unity.CurrentTestFailed = 1;
}
}
if (Unity.CurrentTestFailed)
{
UnityTestResultsFailBegin(lineNumber);
UnityPrintExpectedAndActualStrings(expected, actual);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
}
/*-----------------------------------------------*/
void UnityAssertEqualStringLen(const char* expected,
const char* actual,
const UNITY_UINT32 length,
const char* msg,
const UNITY_LINE_TYPE lineNumber)
{
UNITY_UINT32 i;
RETURN_IF_FAIL_OR_IGNORE;
/* if both pointers not null compare the strings */
if (expected && actual)
{
for (i = 0; (i < length) && (expected[i] || actual[i]); i++)
{
if (expected[i] != actual[i])
{
Unity.CurrentTestFailed = 1;
break;
}
}
}
else
{ /* handle case of one pointers being null (if both null, test should pass) */
if (expected != actual)
{
Unity.CurrentTestFailed = 1;
}
}
if (Unity.CurrentTestFailed)
{
UnityTestResultsFailBegin(lineNumber);
UnityPrintExpectedAndActualStringsLen(expected, actual, length);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
}
/*-----------------------------------------------*/
void UnityAssertEqualStringArray(UNITY_INTERNAL_PTR expected,
const char** actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLAGS_T flags)
{
UNITY_UINT32 i = 0;
UNITY_UINT32 j = 0;
const char* expd = NULL;
const char* act = NULL;
RETURN_IF_FAIL_OR_IGNORE;
/* if no elements, it's an error */
if (num_elements == 0)
{
UnityPrintPointlessAndBail();
}
if ((const void*)expected == (const void*)actual)
{
return; /* Both are NULL or same pointer */
}
if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg))
{
UNITY_FAIL_AND_BAIL;
}
if (flags != UNITY_ARRAY_TO_ARRAY)
{
expd = (const char*)expected;
}
do
{
act = actual[j];
if (flags == UNITY_ARRAY_TO_ARRAY)
{
expd = ((const char* const*)expected)[j];
}
/* if both pointers not null compare the strings */
if (expd && act)
{
for (i = 0; expd[i] || act[i]; i++)
{
if (expd[i] != act[i])
{
Unity.CurrentTestFailed = 1;
break;
}
}
}
else
{ /* handle case of one pointers being null (if both null, test should pass) */
if (expd != act)
{
Unity.CurrentTestFailed = 1;
}
}
if (Unity.CurrentTestFailed)
{
UnityTestResultsFailBegin(lineNumber);
if (num_elements > 1)
{
UnityPrint(UnityStrElement);
UnityPrintNumberUnsigned(j);
}
UnityPrintExpectedAndActualStrings(expd, act);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
} while (++j < num_elements);
}
/*-----------------------------------------------*/
void UnityAssertEqualMemory(UNITY_INTERNAL_PTR expected,
UNITY_INTERNAL_PTR actual,
const UNITY_UINT32 length,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLAGS_T flags)
{
UNITY_PTR_ATTRIBUTE const unsigned char* ptr_exp = (UNITY_PTR_ATTRIBUTE const unsigned char*)expected;
UNITY_PTR_ATTRIBUTE const unsigned char* ptr_act = (UNITY_PTR_ATTRIBUTE const unsigned char*)actual;
UNITY_UINT32 elements = num_elements;
UNITY_UINT32 bytes;
RETURN_IF_FAIL_OR_IGNORE;
if ((elements == 0) || (length == 0))
{
UnityPrintPointlessAndBail();
}
if (expected == actual)
{
return; /* Both are NULL or same pointer */
}
if (UnityIsOneArrayNull(expected, actual, lineNumber, msg))
{
UNITY_FAIL_AND_BAIL;
}
while (elements--)
{
bytes = length;
while (bytes--)
{
if (*ptr_exp != *ptr_act)
{
UnityTestResultsFailBegin(lineNumber);
UnityPrint(UnityStrMemory);
if (num_elements > 1)
{
UnityPrint(UnityStrElement);
UnityPrintNumberUnsigned(num_elements - elements - 1);
}
UnityPrint(UnityStrByte);
UnityPrintNumberUnsigned(length - bytes - 1);
UnityPrint(UnityStrExpected);
UnityPrintNumberByStyle(*ptr_exp, UNITY_DISPLAY_STYLE_HEX8);
UnityPrint(UnityStrWas);
UnityPrintNumberByStyle(*ptr_act, UNITY_DISPLAY_STYLE_HEX8);
UnityAddMsgIfSpecified(msg);
UNITY_FAIL_AND_BAIL;
}
ptr_exp++;
ptr_act++;
}
if (flags == UNITY_ARRAY_TO_VAL)
{
ptr_exp = (UNITY_PTR_ATTRIBUTE const unsigned char*)expected;
}
}
}
/*-----------------------------------------------*/
static union
{
UNITY_INT8 i8;
UNITY_INT16 i16;
UNITY_INT32 i32;
#ifdef UNITY_SUPPORT_64
UNITY_INT64 i64;
#endif
#ifndef UNITY_EXCLUDE_FLOAT
float f;
#endif
#ifndef UNITY_EXCLUDE_DOUBLE
double d;
#endif
} UnityQuickCompare;
UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size)
{
switch(size)
{
case 1:
UnityQuickCompare.i8 = (UNITY_INT8)num;
return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i8);
case 2:
UnityQuickCompare.i16 = (UNITY_INT16)num;
return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i16);
#ifdef UNITY_SUPPORT_64
case 8:
UnityQuickCompare.i64 = (UNITY_INT64)num;
return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i64);
#endif
default: /* 4 bytes */
UnityQuickCompare.i32 = (UNITY_INT32)num;
return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i32);
}
}
#ifndef UNITY_EXCLUDE_FLOAT
/*-----------------------------------------------*/
UNITY_INTERNAL_PTR UnityFloatToPtr(const float num)
{
UnityQuickCompare.f = num;
return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.f);
}
#endif
#ifndef UNITY_EXCLUDE_DOUBLE
/*-----------------------------------------------*/
UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num)
{
UnityQuickCompare.d = num;
return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.d);
}
#endif
/*-----------------------------------------------
* printf helper function
*-----------------------------------------------*/
#ifdef UNITY_INCLUDE_PRINT_FORMATTED
static void UnityPrintFVA(const char* format, va_list va)
{
const char* pch = format;
if (pch != NULL)
{
while (*pch)
{
/* format identification character */
if (*pch == '%')
{
pch++;
if (pch != NULL)
{
switch (*pch)
{
case 'd':
case 'i':
{
const int number = va_arg(va, int);
UnityPrintNumber((UNITY_INT)number);
break;
}
#ifndef UNITY_EXCLUDE_FLOAT_PRINT
case 'f':
case 'g':
{
const double number = va_arg(va, double);
UnityPrintFloat((UNITY_DOUBLE)number);
break;
}
#endif
case 'u':
{
const unsigned int number = va_arg(va, unsigned int);
UnityPrintNumberUnsigned((UNITY_UINT)number);
break;
}
case 'b':
{
const unsigned int number = va_arg(va, unsigned int);
const UNITY_UINT mask = (UNITY_UINT)0 - (UNITY_UINT)1;
UNITY_OUTPUT_CHAR('0');
UNITY_OUTPUT_CHAR('b');
UnityPrintMask(mask, (UNITY_UINT)number);
break;
}
case 'x':
case 'X':
case 'p':
{
const unsigned int number = va_arg(va, unsigned int);
UNITY_OUTPUT_CHAR('0');
UNITY_OUTPUT_CHAR('x');
UnityPrintNumberHex((UNITY_UINT)number, 8);
break;
}
case 'c':
{
const int ch = va_arg(va, int);
UnityPrintChar((const char *)&ch);
break;
}
case 's':
{
const char * string = va_arg(va, const char *);
UnityPrint(string);
break;
}
case '%':
{
UnityPrintChar(pch);
break;
}
default:
{
/* print the unknown format character */
UNITY_OUTPUT_CHAR('%');
UnityPrintChar(pch);
break;
}
}
}
}
#ifdef UNITY_OUTPUT_COLOR
/* print ANSI escape code */
else if ((*pch == 27) && (*(pch + 1) == '['))
{
pch += UnityPrintAnsiEscapeString(pch);
continue;
}
#endif
else if (*pch == '\n')
{
UNITY_PRINT_EOL();
}
else
{
UnityPrintChar(pch);
}
pch++;
}
}
}
void UnityPrintF(const UNITY_LINE_TYPE line, const char* format, ...)
{
UnityTestResultsBegin(Unity.TestFile, line);
UnityPrint("INFO");
if(format != NULL)
{
UnityPrint(": ");
va_list va;
va_start(va, format);
UnityPrintFVA(format, va);
va_end(va);
}
UNITY_PRINT_EOL();
}
#endif /* ! UNITY_INCLUDE_PRINT_FORMATTED */
/*-----------------------------------------------
* Control Functions
*-----------------------------------------------*/
/*-----------------------------------------------*/
void UnityFail(const char* msg, const UNITY_LINE_TYPE line)
{
RETURN_IF_FAIL_OR_IGNORE;
UnityTestResultsBegin(Unity.TestFile, line);
UnityPrint(UnityStrFail);
if (msg != NULL)
{
UNITY_OUTPUT_CHAR(':');
#ifdef UNITY_PRINT_TEST_CONTEXT
UNITY_PRINT_TEST_CONTEXT();
#endif
#ifndef UNITY_EXCLUDE_DETAILS
if (Unity.CurrentDetail1)
{
UnityPrint(UnityStrDetail1Name);
UnityPrint(Unity.CurrentDetail1);
if (Unity.CurrentDetail2)
{
UnityPrint(UnityStrDetail2Name);
UnityPrint(Unity.CurrentDetail2);
}
UnityPrint(UnityStrSpacer);
}
#endif
if (msg[0] != ' ')
{
UNITY_OUTPUT_CHAR(' ');
}
UnityPrint(msg);
}
UNITY_FAIL_AND_BAIL;
}
/*-----------------------------------------------*/
void UnityIgnore(const char* msg, const UNITY_LINE_TYPE line)
{
RETURN_IF_FAIL_OR_IGNORE;
UnityTestResultsBegin(Unity.TestFile, line);
UnityPrint(UnityStrIgnore);
if (msg != NULL)
{
UNITY_OUTPUT_CHAR(':');
UNITY_OUTPUT_CHAR(' ');
UnityPrint(msg);
}
UNITY_IGNORE_AND_BAIL;
}
/*-----------------------------------------------*/
void UnityMessage(const char* msg, const UNITY_LINE_TYPE line)
{
UnityTestResultsBegin(Unity.TestFile, line);
UnityPrint("INFO");
if (msg != NULL)
{
UNITY_OUTPUT_CHAR(':');
UNITY_OUTPUT_CHAR(' ');
UnityPrint(msg);
}
UNITY_PRINT_EOL();
}
/*-----------------------------------------------*/
/* If we have not defined our own test runner, then include our default test runner to make life easier */
#ifndef UNITY_SKIP_DEFAULT_RUNNER
void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum)
{
Unity.CurrentTestName = FuncName;
Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)FuncLineNum;
Unity.NumberOfTests++;
UNITY_CLR_DETAILS();
UNITY_EXEC_TIME_START();
if (TEST_PROTECT())
{
setUp();
Func();
}
if (TEST_PROTECT())
{
tearDown();
}
UNITY_EXEC_TIME_STOP();
UnityConcludeTest();
}
#endif
/*-----------------------------------------------*/
void UnitySetTestFile(const char* filename)
{
Unity.TestFile = filename;
}
/*-----------------------------------------------*/
void UnityBegin(const char* filename)
{
Unity.TestFile = filename;
Unity.CurrentTestName = NULL;
Unity.CurrentTestLineNumber = 0;
Unity.NumberOfTests = 0;
Unity.TestFailures = 0;
Unity.TestIgnores = 0;
Unity.CurrentTestFailed = 0;
Unity.CurrentTestIgnored = 0;
UNITY_CLR_DETAILS();
UNITY_OUTPUT_START();
}
/*-----------------------------------------------*/
int UnityEnd(void)
{
UNITY_PRINT_EOL();
UnityPrint(UnityStrBreaker);
UNITY_PRINT_EOL();
UnityPrintNumber((UNITY_INT)(Unity.NumberOfTests));
UnityPrint(UnityStrResultsTests);
UnityPrintNumber((UNITY_INT)(Unity.TestFailures));
UnityPrint(UnityStrResultsFailures);
UnityPrintNumber((UNITY_INT)(Unity.TestIgnores));
UnityPrint(UnityStrResultsIgnored);
UNITY_PRINT_EOL();
if (Unity.TestFailures == 0U)
{
UnityPrint(UnityStrOk);
}
else
{
UnityPrint(UnityStrFail);
#ifdef UNITY_DIFFERENTIATE_FINAL_FAIL
UNITY_OUTPUT_CHAR('E'); UNITY_OUTPUT_CHAR('D');
#endif
}
UNITY_PRINT_EOL();
UNITY_FLUSH_CALL();
UNITY_OUTPUT_COMPLETE();
return (int)(Unity.TestFailures);
}
/*-----------------------------------------------
* Command Line Argument Support
*-----------------------------------------------*/
#ifdef UNITY_USE_COMMAND_LINE_ARGS
char* UnityOptionIncludeNamed = NULL;
char* UnityOptionExcludeNamed = NULL;
int UnityVerbosity = 1;
/*-----------------------------------------------*/
int UnityParseOptions(int argc, char** argv)
{
int i;
UnityOptionIncludeNamed = NULL;
UnityOptionExcludeNamed = NULL;
for (i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
{
switch (argv[i][1])
{
case 'l': /* list tests */
return -1;
case 'n': /* include tests with name including this string */
case 'f': /* an alias for -n */
if (argv[i][2] == '=')
{
UnityOptionIncludeNamed = &argv[i][3];
}
else if (++i < argc)
{
UnityOptionIncludeNamed = argv[i];
}
else
{
UnityPrint("ERROR: No Test String to Include Matches For");
UNITY_PRINT_EOL();
return 1;
}
break;
case 'q': /* quiet */
UnityVerbosity = 0;
break;
case 'v': /* verbose */
UnityVerbosity = 2;
break;
case 'x': /* exclude tests with name including this string */
if (argv[i][2] == '=')
{
UnityOptionExcludeNamed = &argv[i][3];
}
else if (++i < argc)
{
UnityOptionExcludeNamed = argv[i];
}
else
{
UnityPrint("ERROR: No Test String to Exclude Matches For");
UNITY_PRINT_EOL();
return 1;
}
break;
default:
UnityPrint("ERROR: Unknown Option ");
UNITY_OUTPUT_CHAR(argv[i][1]);
UNITY_PRINT_EOL();
return 1;
}
}
}
return 0;
}
/*-----------------------------------------------*/
int IsStringInBiggerString(const char* longstring, const char* shortstring)
{
const char* lptr = longstring;
const char* sptr = shortstring;
const char* lnext = lptr;
if (*sptr == '*')
{
return 1;
}
while (*lptr)
{
lnext = lptr + 1;
/* If they current bytes match, go on to the next bytes */
while (*lptr && *sptr && (*lptr == *sptr))
{
lptr++;
sptr++;
/* We're done if we match the entire string or up to a wildcard */
if (*sptr == '*')
return 1;
if (*sptr == ',')
return 1;
if (*sptr == '"')
return 1;
if (*sptr == '\'')
return 1;
if (*sptr == ':')
return 2;
if (*sptr == 0)
return 1;
}
/* Otherwise we start in the long pointer 1 character further and try again */
lptr = lnext;
sptr = shortstring;
}
return 0;
}
/*-----------------------------------------------*/
int UnityStringArgumentMatches(const char* str)
{
int retval;
const char* ptr1;
const char* ptr2;
const char* ptrf;
/* Go through the options and get the substrings for matching one at a time */
ptr1 = str;
while (ptr1[0] != 0)
{
if ((ptr1[0] == '"') || (ptr1[0] == '\''))
{
ptr1++;
}
/* look for the start of the next partial */
ptr2 = ptr1;
ptrf = 0;
do
{
ptr2++;
if ((ptr2[0] == ':') && (ptr2[1] != 0) && (ptr2[0] != '\'') && (ptr2[0] != '"') && (ptr2[0] != ','))
{
ptrf = &ptr2[1];
}
} while ((ptr2[0] != 0) && (ptr2[0] != '\'') && (ptr2[0] != '"') && (ptr2[0] != ','));
while ((ptr2[0] != 0) && ((ptr2[0] == ':') || (ptr2[0] == '\'') || (ptr2[0] == '"') || (ptr2[0] == ',')))
{
ptr2++;
}
/* done if complete filename match */
retval = IsStringInBiggerString(Unity.TestFile, ptr1);
if (retval == 1)
{
return retval;
}
/* done if testname match after filename partial match */
if ((retval == 2) && (ptrf != 0))
{
if (IsStringInBiggerString(Unity.CurrentTestName, ptrf))
{
return 1;
}
}
/* done if complete testname match */
if (IsStringInBiggerString(Unity.CurrentTestName, ptr1) == 1)
{
return 1;
}
ptr1 = ptr2;
}
/* we couldn't find a match for any substrings */
return 0;
}
/*-----------------------------------------------*/
int UnityTestMatches(void)
{
/* Check if this test name matches the included test pattern */
int retval;
if (UnityOptionIncludeNamed)
{
retval = UnityStringArgumentMatches(UnityOptionIncludeNamed);
}
else
{
retval = 1;
}
/* Check if this test name matches the excluded test pattern */
if (UnityOptionExcludeNamed)
{
if (UnityStringArgumentMatches(UnityOptionExcludeNamed))
{
retval = 0;
}
}
return retval;
}
#endif /* UNITY_USE_COMMAND_LINE_ARGS */
/*-----------------------------------------------*/
#endif /*LV_BUILD_TEST*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/unity/unity.c | C | apache-2.0 | 65,571 |
/* ==========================================
Unity Project - A Test Framework for C
Copyright (c) 2007-21 Mike Karlesky, Mark VanderVoord, Greg Williams
[Released under MIT License. Please refer to license.txt for details]
========================================== */
#if LV_BUILD_TEST
#define UNITY_INCLUDE_PRINT_FORMATTED 1
#ifndef UNITY_FRAMEWORK_H
#define UNITY_FRAMEWORK_H
#define UNITY
#define UNITY_VERSION_MAJOR 2
#define UNITY_VERSION_MINOR 5
#define UNITY_VERSION_BUILD 2
#define UNITY_VERSION ((UNITY_VERSION_MAJOR << 16) | (UNITY_VERSION_MINOR << 8) | UNITY_VERSION_BUILD)
#ifdef __cplusplus
extern "C"
{
#endif
#include "unity_internals.h"
/*-------------------------------------------------------
* Test Setup / Teardown
*-------------------------------------------------------*/
/* These functions are intended to be called before and after each test.
* If using unity directly, these will need to be provided for each test
* executable built. If you are using the test runner generator and/or
* Ceedling, these are optional. */
void setUp(void);
void tearDown(void);
/* These functions are intended to be called at the beginning and end of an
* entire test suite. suiteTearDown() is passed the number of tests that
* failed, and its return value becomes the exit code of main(). If using
* Unity directly, you're in charge of calling these if they are desired.
* If using Ceedling or the test runner generator, these will be called
* automatically if they exist. */
void suiteSetUp(void);
int suiteTearDown(int num_failures);
/*-------------------------------------------------------
* Test Reset and Verify
*-------------------------------------------------------*/
/* These functions are intended to be called before during tests in order
* to support complex test loops, etc. Both are NOT built into Unity. Instead
* the test runner generator will create them. resetTest will run teardown and
* setup again, verifying any end-of-test needs between. verifyTest will only
* run the verification. */
void resetTest(void);
void verifyTest(void);
/*-------------------------------------------------------
* Configuration Options
*-------------------------------------------------------
* All options described below should be passed as a compiler flag to all files using Unity. If you must add #defines, place them BEFORE the #include above.
* Integers/longs/pointers
* - Unity attempts to automatically discover your integer sizes
* - define UNITY_EXCLUDE_STDINT_H to stop attempting to look in <stdint.h>
* - define UNITY_EXCLUDE_LIMITS_H to stop attempting to look in <limits.h>
* - If you cannot use the automatic methods above, you can force Unity by using these options:
* - define UNITY_SUPPORT_64
* - set UNITY_INT_WIDTH
* - set UNITY_LONG_WIDTH
* - set UNITY_POINTER_WIDTH
* Floats
* - define UNITY_EXCLUDE_FLOAT to disallow floating point comparisons
* - define UNITY_FLOAT_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_FLOAT
* - define UNITY_FLOAT_TYPE to specify doubles instead of single precision floats
* - define UNITY_INCLUDE_DOUBLE to allow double floating point comparisons
* - define UNITY_EXCLUDE_DOUBLE to disallow double floating point comparisons (default)
* - define UNITY_DOUBLE_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_DOUBLE
* - define UNITY_DOUBLE_TYPE to specify something other than double
* - define UNITY_EXCLUDE_FLOAT_PRINT to trim binary size, won't print floating point values in errors
* Output
* - by default, Unity prints to standard out with putchar. define UNITY_OUTPUT_CHAR(a) with a different function if desired
* - define UNITY_DIFFERENTIATE_FINAL_FAIL to print FAILED (vs. FAIL) at test end summary - for automated search for failure
* Optimization
* - by default, line numbers are stored in unsigned shorts. Define UNITY_LINE_TYPE with a different type if your files are huge
* - by default, test and failure counters are unsigned shorts. Define UNITY_COUNTER_TYPE with a different type if you want to save space or have more than 65535 Tests.
* Test Cases
* - define UNITY_SUPPORT_TEST_CASES to include the TEST_CASE macro, though really it's mostly about the runner generator script
* Parameterized Tests
* - you'll want to create a define of TEST_CASE(...) which basically evaluates to nothing
* Tests with Arguments
* - you'll want to define UNITY_USE_COMMAND_LINE_ARGS if you have the test runner passing arguments to Unity
*-------------------------------------------------------
* Basic Fail and Ignore
*-------------------------------------------------------*/
#define TEST_FAIL_MESSAGE(message) UNITY_TEST_FAIL(__LINE__, (message))
#define TEST_FAIL() UNITY_TEST_FAIL(__LINE__, NULL)
#define TEST_IGNORE_MESSAGE(message) UNITY_TEST_IGNORE(__LINE__, (message))
#define TEST_IGNORE() UNITY_TEST_IGNORE(__LINE__, NULL)
#define TEST_MESSAGE(message) UnityMessage((message), __LINE__)
#define TEST_ONLY()
#ifdef UNITY_INCLUDE_PRINT_FORMATTED
#define TEST_PRINTF(message, ...) UnityPrintF(__LINE__, (message), __VA_ARGS__)
#endif
/* It is not necessary for you to call PASS. A PASS condition is assumed if nothing fails.
* This method allows you to abort a test immediately with a PASS state, ignoring the remainder of the test. */
#define TEST_PASS() TEST_ABORT()
#define TEST_PASS_MESSAGE(message) do { UnityMessage((message), __LINE__); TEST_ABORT(); } while(0)
/* This macro does nothing, but it is useful for build tools (like Ceedling) to make use of this to figure out
* which files should be linked to in order to perform a test. Use it like TEST_FILE("sandwiches.c") */
#define TEST_FILE(a)
/*-------------------------------------------------------
* Test Asserts (simple)
*-------------------------------------------------------*/
/* Boolean */
#define TEST_ASSERT(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expression Evaluated To FALSE")
#define TEST_ASSERT_TRUE(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expected TRUE Was FALSE")
#define TEST_ASSERT_UNLESS(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expression Evaluated To TRUE")
#define TEST_ASSERT_FALSE(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expected FALSE Was TRUE")
#define TEST_ASSERT_NULL(pointer) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, " Expected NULL")
#define TEST_ASSERT_NOT_NULL(pointer) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, " Expected Non-NULL")
#define TEST_ASSERT_EMPTY(pointer) UNITY_TEST_ASSERT_EMPTY( (pointer), __LINE__, " Expected Empty")
#define TEST_ASSERT_NOT_EMPTY(pointer) UNITY_TEST_ASSERT_NOT_EMPTY((pointer), __LINE__, " Expected Non-Empty")
/* Integers (of all sizes) */
#define TEST_ASSERT_EQUAL_INT(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_size_t(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX8(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX16(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX32(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX64(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_CHAR(expected, actual) UNITY_TEST_ASSERT_EQUAL_CHAR((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_BITS(mask, expected, actual) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_BITS_HIGH(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT)(-1), (actual), __LINE__, NULL)
#define TEST_ASSERT_BITS_LOW(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT)(0), (actual), __LINE__, NULL)
#define TEST_ASSERT_BIT_HIGH(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT)1 << (bit)), (UNITY_UINT)(-1), (actual), __LINE__, NULL)
#define TEST_ASSERT_BIT_LOW(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT)1 << (bit)), (UNITY_UINT)(0), (actual), __LINE__, NULL)
/* Integer Not Equal To (of all sizes) */
#define TEST_ASSERT_NOT_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_CHAR((threshold), (actual), __LINE__, NULL)
/* Integer Greater Than/ Less Than (of all sizes) */
#define TEST_ASSERT_GREATER_THAN(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_size_t(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_CHAR((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_size_t(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_THAN_CHAR(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_CHAR((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL)
#define TEST_ASSERT_LESS_OR_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, NULL)
/* Integer Ranges (of all sizes) */
#define TEST_ASSERT_INT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_INT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_INT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_INT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_INT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_UINT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_UINT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_UINT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_UINT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_UINT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_size_t_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_HEX_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_HEX8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_HEX16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_HEX32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_HEX64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_CHAR_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_CHAR_WITHIN((delta), (expected), (actual), __LINE__, NULL)
/* Integer Array Ranges (of all sizes) */
#define TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_size_t_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_HEX_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
#define TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL)
/* Structs and Strings */
#define TEST_ASSERT_EQUAL_PTR(expected, actual) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_STRING(expected, actual) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_MEMORY(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, NULL)
/* Arrays */
#define TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_size_t_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
/* Arrays Compared To Single Value */
#define TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_size_t(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_HEX(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_CHAR((expected), (actual), (num_elements), __LINE__, NULL)
/* Floating Point (If Enabled) */
#define TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_FLOAT(expected, actual) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_NOT_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, NULL)
#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, NULL)
/* Double (If Enabled) */
#define TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_DOUBLE(expected, actual) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_NOT_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, NULL)
#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, NULL)
/* Shorthand */
#ifdef UNITY_SHORTHAND_AS_OLD
#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal")
#endif
#ifdef UNITY_SHORTHAND_AS_INT
#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand)
#endif
#ifdef UNITY_SHORTHAND_AS_MEM
#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_MEMORY((&expected), (&actual), sizeof(expected), __LINE__, NULL)
#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand)
#endif
#ifdef UNITY_SHORTHAND_AS_RAW
#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) == (actual)), __LINE__, " Expected Equal")
#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal")
#endif
#ifdef UNITY_SHORTHAND_AS_NONE
#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand)
#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand)
#endif
/*-------------------------------------------------------
* Test Asserts (with additional messages)
*-------------------------------------------------------*/
/* Boolean */
#define TEST_ASSERT_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message))
#define TEST_ASSERT_TRUE_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message))
#define TEST_ASSERT_UNLESS_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message))
#define TEST_ASSERT_FALSE_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message))
#define TEST_ASSERT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, (message))
#define TEST_ASSERT_NOT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, (message))
#define TEST_ASSERT_EMPTY_MESSAGE(pointer, message) UNITY_TEST_ASSERT_EMPTY( (pointer), __LINE__, (message))
#define TEST_ASSERT_NOT_EMPTY_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NOT_EMPTY((pointer), __LINE__, (message))
/* Integers (of all sizes) */
#define TEST_ASSERT_EQUAL_INT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_size_t_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_BITS_MESSAGE(mask, expected, actual, message) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_BITS_HIGH_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, (message))
#define TEST_ASSERT_BITS_LOW_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, (message))
#define TEST_ASSERT_BIT_HIGH_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), (actual), __LINE__, (message))
#define TEST_ASSERT_BIT_LOW_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_CHAR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_CHAR((expected), (actual), __LINE__, (message))
/* Integer Not Equal To (of all sizes) */
#define TEST_ASSERT_NOT_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_CHAR((threshold), (actual), __LINE__, (message))
/* Integer Greater Than/ Less Than (of all sizes) */
#define TEST_ASSERT_GREATER_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_THAN_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_CHAR((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_THAN_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_CHAR((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_GREATER_OR_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message))
#define TEST_ASSERT_LESS_OR_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, (message))
/* Integer Ranges (of all sizes) */
#define TEST_ASSERT_INT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_INT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_INT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_INT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_INT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_UINT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_UINT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_UINT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_UINT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_UINT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_size_t_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_HEX_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_HEX8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_HEX16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_HEX32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_HEX64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_CHAR_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_CHAR_WITHIN((delta), (expected), (actual), __LINE__, (message))
/* Integer Array Ranges (of all sizes) */
#define TEST_ASSERT_INT_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_INT8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_INT16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_INT32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_INT64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_UINT_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_UINT8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_UINT16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_UINT32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_UINT64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_size_t_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_HEX_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_HEX8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_HEX16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_HEX32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_HEX64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
#define TEST_ASSERT_CHAR_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message))
/* Structs and Strings */
#define TEST_ASSERT_EQUAL_PTR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_STRING_LEN_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, (message))
#define TEST_ASSERT_EQUAL_MEMORY_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, (message))
/* Arrays */
#define TEST_ASSERT_EQUAL_INT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_INT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_UINT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_size_t_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_HEX64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_PTR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_STRING_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_MEMORY_ARRAY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EQUAL_CHAR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
/* Arrays Compared To Single Value*/
#define TEST_ASSERT_EACH_EQUAL_INT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_INT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_INT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_INT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_INT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_UINT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_UINT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_UINT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_UINT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_UINT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_size_t_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_HEX_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_HEX8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_HEX16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_HEX32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_HEX64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_PTR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_STRING_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_MEMORY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_CHAR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_CHAR((expected), (actual), (num_elements), __LINE__, (message))
/* Floating Point (If Enabled) */
#define TEST_ASSERT_FLOAT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_FLOAT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_FLOAT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_FLOAT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, (message))
#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, (message))
/* Double (If Enabled) */
#define TEST_ASSERT_DOUBLE_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_DOUBLE_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_EACH_EQUAL_DOUBLE_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, (message))
#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, (message))
/* Shorthand */
#ifdef UNITY_SHORTHAND_AS_OLD
#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message))
#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, (message))
#endif
#ifdef UNITY_SHORTHAND_AS_INT
#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, message)
#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand)
#endif
#ifdef UNITY_SHORTHAND_AS_MEM
#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_MEMORY((&expected), (&actual), sizeof(expected), __LINE__, message)
#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand)
#endif
#ifdef UNITY_SHORTHAND_AS_RAW
#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) == (actual)), __LINE__, message)
#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, message)
#endif
#ifdef UNITY_SHORTHAND_AS_NONE
#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand)
#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand)
#endif
/* end of UNITY_FRAMEWORK_H */
#ifdef __cplusplus
}
#endif
#endif
#include "unity_support.h"
#endif /*LV_BUILD_TEST*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/unity/unity.h | C | apache-2.0 | 89,128 |
/* ==========================================
Unity Project - A Test Framework for C
Copyright (c) 2007-21 Mike Karlesky, Mark VanderVoord, Greg Williams
[Released under MIT License. Please refer to license.txt for details]
========================================== */
#if LV_BUILD_TEST
#ifndef UNITY_INTERNALS_H
#define UNITY_INTERNALS_H
#ifdef UNITY_INCLUDE_CONFIG_H
#include "unity_config.h"
#endif
#ifndef UNITY_EXCLUDE_SETJMP_H
#include <setjmp.h>
#endif
#ifndef UNITY_EXCLUDE_MATH_H
#include <math.h>
#endif
#ifndef UNITY_EXCLUDE_STDDEF_H
#include <stddef.h>
#endif
#ifdef UNITY_INCLUDE_PRINT_FORMATTED
#include <stdarg.h>
#endif
/* Unity Attempts to Auto-Detect Integer Types
* Attempt 1: UINT_MAX, ULONG_MAX in <limits.h>, or default to 32 bits
* Attempt 2: UINTPTR_MAX in <stdint.h>, or default to same size as long
* The user may override any of these derived constants:
* UNITY_INT_WIDTH, UNITY_LONG_WIDTH, UNITY_POINTER_WIDTH */
#ifndef UNITY_EXCLUDE_STDINT_H
#include <stdint.h>
#endif
#ifndef UNITY_EXCLUDE_LIMITS_H
#include <limits.h>
#endif
#if defined(__GNUC__) || defined(__clang__)
#define UNITY_FUNCTION_ATTR(a) __attribute__((a))
#else
#define UNITY_FUNCTION_ATTR(a) /* ignore */
#endif
/*-------------------------------------------------------
* Guess Widths If Not Specified
*-------------------------------------------------------*/
/* Determine the size of an int, if not already specified.
* We cannot use sizeof(int), because it is not yet defined
* at this stage in the translation of the C program.
* Also sizeof(int) does return the size in addressable units on all platforms,
* which may not necessarily be the size in bytes.
* Therefore, infer it from UINT_MAX if possible. */
#ifndef UNITY_INT_WIDTH
#ifdef UINT_MAX
#if (UINT_MAX == 0xFFFF)
#define UNITY_INT_WIDTH (16)
#elif (UINT_MAX == 0xFFFFFFFF)
#define UNITY_INT_WIDTH (32)
#elif (UINT_MAX == 0xFFFFFFFFFFFFFFFF)
#define UNITY_INT_WIDTH (64)
#endif
#else /* Set to default */
#define UNITY_INT_WIDTH (32)
#endif /* UINT_MAX */
#endif
/* Determine the size of a long, if not already specified. */
#ifndef UNITY_LONG_WIDTH
#ifdef ULONG_MAX
#if (ULONG_MAX == 0xFFFF)
#define UNITY_LONG_WIDTH (16)
#elif (ULONG_MAX == 0xFFFFFFFF)
#define UNITY_LONG_WIDTH (32)
#elif (ULONG_MAX == 0xFFFFFFFFFFFFFFFF)
#define UNITY_LONG_WIDTH (64)
#endif
#else /* Set to default */
#define UNITY_LONG_WIDTH (32)
#endif /* ULONG_MAX */
#endif
/* Determine the size of a pointer, if not already specified. */
#ifndef UNITY_POINTER_WIDTH
#ifdef UINTPTR_MAX
#if (UINTPTR_MAX <= 0xFFFF)
#define UNITY_POINTER_WIDTH (16)
#elif (UINTPTR_MAX <= 0xFFFFFFFF)
#define UNITY_POINTER_WIDTH (32)
#elif (UINTPTR_MAX <= 0xFFFFFFFFFFFFFFFF)
#define UNITY_POINTER_WIDTH (64)
#endif
#else /* Set to default */
#define UNITY_POINTER_WIDTH UNITY_LONG_WIDTH
#endif /* UINTPTR_MAX */
#endif
/*-------------------------------------------------------
* Int Support (Define types based on detected sizes)
*-------------------------------------------------------*/
#if (UNITY_INT_WIDTH == 32)
typedef unsigned char UNITY_UINT8;
typedef unsigned short UNITY_UINT16;
typedef unsigned int UNITY_UINT32;
typedef signed char UNITY_INT8;
typedef signed short UNITY_INT16;
typedef signed int UNITY_INT32;
#elif (UNITY_INT_WIDTH == 16)
typedef unsigned char UNITY_UINT8;
typedef unsigned int UNITY_UINT16;
typedef unsigned long UNITY_UINT32;
typedef signed char UNITY_INT8;
typedef signed int UNITY_INT16;
typedef signed long UNITY_INT32;
#else
#error Invalid UNITY_INT_WIDTH specified! (16 or 32 are supported)
#endif
/*-------------------------------------------------------
* 64-bit Support
*-------------------------------------------------------*/
/* Auto-detect 64 Bit Support */
#ifndef UNITY_SUPPORT_64
#if UNITY_LONG_WIDTH == 64 || UNITY_POINTER_WIDTH == 64
#define UNITY_SUPPORT_64
#endif
#endif
/* 64-Bit Support Dependent Configuration */
#ifndef UNITY_SUPPORT_64
/* No 64-bit Support */
typedef UNITY_UINT32 UNITY_UINT;
typedef UNITY_INT32 UNITY_INT;
#define UNITY_MAX_NIBBLES (8) /* Maximum number of nibbles in a UNITY_(U)INT */
#else
/* 64-bit Support */
#if (UNITY_LONG_WIDTH == 32)
typedef unsigned long long UNITY_UINT64;
typedef signed long long UNITY_INT64;
#elif (UNITY_LONG_WIDTH == 64)
typedef unsigned long UNITY_UINT64;
typedef signed long UNITY_INT64;
#else
#error Invalid UNITY_LONG_WIDTH specified! (32 or 64 are supported)
#endif
typedef UNITY_UINT64 UNITY_UINT;
typedef UNITY_INT64 UNITY_INT;
#define UNITY_MAX_NIBBLES (16) /* Maximum number of nibbles in a UNITY_(U)INT */
#endif
/*-------------------------------------------------------
* Pointer Support
*-------------------------------------------------------*/
#if (UNITY_POINTER_WIDTH == 32)
#define UNITY_PTR_TO_INT UNITY_INT32
#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX32
#elif (UNITY_POINTER_WIDTH == 64)
#define UNITY_PTR_TO_INT UNITY_INT64
#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX64
#elif (UNITY_POINTER_WIDTH == 16)
#define UNITY_PTR_TO_INT UNITY_INT16
#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX16
#else
#error Invalid UNITY_POINTER_WIDTH specified! (16, 32 or 64 are supported)
#endif
#ifndef UNITY_PTR_ATTRIBUTE
#define UNITY_PTR_ATTRIBUTE
#endif
#ifndef UNITY_INTERNAL_PTR
#define UNITY_INTERNAL_PTR UNITY_PTR_ATTRIBUTE const void*
#endif
/*-------------------------------------------------------
* Float Support
*-------------------------------------------------------*/
#ifdef UNITY_EXCLUDE_FLOAT
/* No Floating Point Support */
#ifndef UNITY_EXCLUDE_DOUBLE
#define UNITY_EXCLUDE_DOUBLE /* Remove double when excluding float support */
#endif
#ifndef UNITY_EXCLUDE_FLOAT_PRINT
#define UNITY_EXCLUDE_FLOAT_PRINT
#endif
#else
/* Floating Point Support */
#ifndef UNITY_FLOAT_PRECISION
#define UNITY_FLOAT_PRECISION (0.00001f)
#endif
#ifndef UNITY_FLOAT_TYPE
#define UNITY_FLOAT_TYPE float
#endif
typedef UNITY_FLOAT_TYPE UNITY_FLOAT;
/* isinf & isnan macros should be provided by math.h */
#ifndef isinf
/* The value of Inf - Inf is NaN */
#define isinf(n) (isnan((n) - (n)) && !isnan(n))
#endif
#ifndef isnan
/* NaN is the only floating point value that does NOT equal itself.
* Therefore if n != n, then it is NaN. */
#define isnan(n) ((n != n) ? 1 : 0)
#endif
#endif
/*-------------------------------------------------------
* Double Float Support
*-------------------------------------------------------*/
/* unlike float, we DON'T include by default */
#if defined(UNITY_EXCLUDE_DOUBLE) || !defined(UNITY_INCLUDE_DOUBLE)
/* No Floating Point Support */
#ifndef UNITY_EXCLUDE_DOUBLE
#define UNITY_EXCLUDE_DOUBLE
#else
#undef UNITY_INCLUDE_DOUBLE
#endif
#ifndef UNITY_EXCLUDE_FLOAT
#ifndef UNITY_DOUBLE_TYPE
#define UNITY_DOUBLE_TYPE double
#endif
typedef UNITY_FLOAT UNITY_DOUBLE;
/* For parameter in UnityPrintFloat(UNITY_DOUBLE), which aliases to double or float */
#endif
#else
/* Double Floating Point Support */
#ifndef UNITY_DOUBLE_PRECISION
#define UNITY_DOUBLE_PRECISION (1e-12)
#endif
#ifndef UNITY_DOUBLE_TYPE
#define UNITY_DOUBLE_TYPE double
#endif
typedef UNITY_DOUBLE_TYPE UNITY_DOUBLE;
#endif
/*-------------------------------------------------------
* Output Method: stdout (DEFAULT)
*-------------------------------------------------------*/
#ifndef UNITY_OUTPUT_CHAR
/* Default to using putchar, which is defined in stdio.h */
#include <stdio.h>
#define UNITY_OUTPUT_CHAR(a) (void)putchar(a)
#else
/* If defined as something else, make sure we declare it here so it's ready for use */
#ifdef UNITY_OUTPUT_CHAR_HEADER_DECLARATION
extern void UNITY_OUTPUT_CHAR_HEADER_DECLARATION;
#endif
#endif
#ifndef UNITY_OUTPUT_FLUSH
#ifdef UNITY_USE_FLUSH_STDOUT
/* We want to use the stdout flush utility */
#include <stdio.h>
#define UNITY_OUTPUT_FLUSH() (void)fflush(stdout)
#else
/* We've specified nothing, therefore flush should just be ignored */
#define UNITY_OUTPUT_FLUSH()
#endif
#else
/* If defined as something else, make sure we declare it here so it's ready for use */
#ifdef UNITY_OUTPUT_FLUSH_HEADER_DECLARATION
extern void UNITY_OUTPUT_FLUSH_HEADER_DECLARATION;
#endif
#endif
#ifndef UNITY_OUTPUT_FLUSH
#define UNITY_FLUSH_CALL()
#else
#define UNITY_FLUSH_CALL() UNITY_OUTPUT_FLUSH()
#endif
#ifndef UNITY_PRINT_EOL
#define UNITY_PRINT_EOL() UNITY_OUTPUT_CHAR('\n')
#endif
#ifndef UNITY_OUTPUT_START
#define UNITY_OUTPUT_START()
#endif
#ifndef UNITY_OUTPUT_COMPLETE
#define UNITY_OUTPUT_COMPLETE()
#endif
#ifdef UNITY_INCLUDE_EXEC_TIME
#if !defined(UNITY_EXEC_TIME_START) && \
!defined(UNITY_EXEC_TIME_STOP) && \
!defined(UNITY_PRINT_EXEC_TIME) && \
!defined(UNITY_TIME_TYPE)
/* If none any of these macros are defined then try to provide a default implementation */
#if defined(UNITY_CLOCK_MS)
/* This is a simple way to get a default implementation on platforms that support getting a millisecond counter */
#define UNITY_TIME_TYPE UNITY_UINT
#define UNITY_EXEC_TIME_START() Unity.CurrentTestStartTime = UNITY_CLOCK_MS()
#define UNITY_EXEC_TIME_STOP() Unity.CurrentTestStopTime = UNITY_CLOCK_MS()
#define UNITY_PRINT_EXEC_TIME() { \
UNITY_UINT execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \
UnityPrint(" ("); \
UnityPrintNumberUnsigned(execTimeMs); \
UnityPrint(" ms)"); \
}
#elif defined(_WIN32)
#include <time.h>
#define UNITY_TIME_TYPE clock_t
#define UNITY_GET_TIME(t) t = (clock_t)((clock() * 1000) / CLOCKS_PER_SEC)
#define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime)
#define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime)
#define UNITY_PRINT_EXEC_TIME() { \
UNITY_UINT execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \
UnityPrint(" ("); \
UnityPrintNumberUnsigned(execTimeMs); \
UnityPrint(" ms)"); \
}
#elif defined(__unix__) || defined(__APPLE__)
#include <time.h>
#define UNITY_TIME_TYPE struct timespec
#define UNITY_GET_TIME(t) clock_gettime(CLOCK_MONOTONIC, &t)
#define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime)
#define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime)
#define UNITY_PRINT_EXEC_TIME() { \
UNITY_UINT execTimeMs = ((Unity.CurrentTestStopTime.tv_sec - Unity.CurrentTestStartTime.tv_sec) * 1000L); \
execTimeMs += ((Unity.CurrentTestStopTime.tv_nsec - Unity.CurrentTestStartTime.tv_nsec) / 1000000L); \
UnityPrint(" ("); \
UnityPrintNumberUnsigned(execTimeMs); \
UnityPrint(" ms)"); \
}
#endif
#endif
#endif
#ifndef UNITY_EXEC_TIME_START
#define UNITY_EXEC_TIME_START() do{}while(0)
#endif
#ifndef UNITY_EXEC_TIME_STOP
#define UNITY_EXEC_TIME_STOP() do{}while(0)
#endif
#ifndef UNITY_TIME_TYPE
#define UNITY_TIME_TYPE UNITY_UINT
#endif
#ifndef UNITY_PRINT_EXEC_TIME
#define UNITY_PRINT_EXEC_TIME() do{}while(0)
#endif
/*-------------------------------------------------------
* Footprint
*-------------------------------------------------------*/
#ifndef UNITY_LINE_TYPE
#define UNITY_LINE_TYPE UNITY_UINT
#endif
#ifndef UNITY_COUNTER_TYPE
#define UNITY_COUNTER_TYPE UNITY_UINT
#endif
/*-------------------------------------------------------
* Internal Structs Needed
*-------------------------------------------------------*/
typedef void (*UnityTestFunction)(void);
#define UNITY_DISPLAY_RANGE_INT (0x10)
#define UNITY_DISPLAY_RANGE_UINT (0x20)
#define UNITY_DISPLAY_RANGE_HEX (0x40)
#define UNITY_DISPLAY_RANGE_CHAR (0x80)
typedef enum
{
UNITY_DISPLAY_STYLE_INT = (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_INT,
UNITY_DISPLAY_STYLE_INT8 = 1 + UNITY_DISPLAY_RANGE_INT,
UNITY_DISPLAY_STYLE_INT16 = 2 + UNITY_DISPLAY_RANGE_INT,
UNITY_DISPLAY_STYLE_INT32 = 4 + UNITY_DISPLAY_RANGE_INT,
#ifdef UNITY_SUPPORT_64
UNITY_DISPLAY_STYLE_INT64 = 8 + UNITY_DISPLAY_RANGE_INT,
#endif
UNITY_DISPLAY_STYLE_UINT = (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_UINT,
UNITY_DISPLAY_STYLE_UINT8 = 1 + UNITY_DISPLAY_RANGE_UINT,
UNITY_DISPLAY_STYLE_UINT16 = 2 + UNITY_DISPLAY_RANGE_UINT,
UNITY_DISPLAY_STYLE_UINT32 = 4 + UNITY_DISPLAY_RANGE_UINT,
#ifdef UNITY_SUPPORT_64
UNITY_DISPLAY_STYLE_UINT64 = 8 + UNITY_DISPLAY_RANGE_UINT,
#endif
UNITY_DISPLAY_STYLE_HEX8 = 1 + UNITY_DISPLAY_RANGE_HEX,
UNITY_DISPLAY_STYLE_HEX16 = 2 + UNITY_DISPLAY_RANGE_HEX,
UNITY_DISPLAY_STYLE_HEX32 = 4 + UNITY_DISPLAY_RANGE_HEX,
#ifdef UNITY_SUPPORT_64
UNITY_DISPLAY_STYLE_HEX64 = 8 + UNITY_DISPLAY_RANGE_HEX,
#endif
UNITY_DISPLAY_STYLE_CHAR = 1 + UNITY_DISPLAY_RANGE_CHAR + UNITY_DISPLAY_RANGE_INT,
UNITY_DISPLAY_STYLE_UNKNOWN
} UNITY_DISPLAY_STYLE_T;
typedef enum
{
UNITY_WITHIN = 0x0,
UNITY_EQUAL_TO = 0x1,
UNITY_GREATER_THAN = 0x2,
UNITY_GREATER_OR_EQUAL = 0x2 + UNITY_EQUAL_TO,
UNITY_SMALLER_THAN = 0x4,
UNITY_SMALLER_OR_EQUAL = 0x4 + UNITY_EQUAL_TO,
UNITY_NOT_EQUAL = 0x0,
UNITY_UNKNOWN
} UNITY_COMPARISON_T;
#ifndef UNITY_EXCLUDE_FLOAT
typedef enum UNITY_FLOAT_TRAIT
{
UNITY_FLOAT_IS_NOT_INF = 0,
UNITY_FLOAT_IS_INF,
UNITY_FLOAT_IS_NOT_NEG_INF,
UNITY_FLOAT_IS_NEG_INF,
UNITY_FLOAT_IS_NOT_NAN,
UNITY_FLOAT_IS_NAN,
UNITY_FLOAT_IS_NOT_DET,
UNITY_FLOAT_IS_DET,
UNITY_FLOAT_INVALID_TRAIT
} UNITY_FLOAT_TRAIT_T;
#endif
typedef enum
{
UNITY_ARRAY_TO_VAL = 0,
UNITY_ARRAY_TO_ARRAY,
UNITY_ARRAY_UNKNOWN
} UNITY_FLAGS_T;
struct UNITY_STORAGE_T
{
const char* TestFile;
const char* CurrentTestName;
#ifndef UNITY_EXCLUDE_DETAILS
const char* CurrentDetail1;
const char* CurrentDetail2;
#endif
UNITY_LINE_TYPE CurrentTestLineNumber;
UNITY_COUNTER_TYPE NumberOfTests;
UNITY_COUNTER_TYPE TestFailures;
UNITY_COUNTER_TYPE TestIgnores;
UNITY_COUNTER_TYPE CurrentTestFailed;
UNITY_COUNTER_TYPE CurrentTestIgnored;
#ifdef UNITY_INCLUDE_EXEC_TIME
UNITY_TIME_TYPE CurrentTestStartTime;
UNITY_TIME_TYPE CurrentTestStopTime;
#endif
#ifndef UNITY_EXCLUDE_SETJMP_H
jmp_buf AbortFrame;
#endif
};
extern struct UNITY_STORAGE_T Unity;
/*-------------------------------------------------------
* Test Suite Management
*-------------------------------------------------------*/
void UnityBegin(const char* filename);
int UnityEnd(void);
void UnitySetTestFile(const char* filename);
void UnityConcludeTest(void);
#ifndef RUN_TEST
void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum);
#else
#define UNITY_SKIP_DEFAULT_RUNNER
#endif
/*-------------------------------------------------------
* Details Support
*-------------------------------------------------------*/
#ifdef UNITY_EXCLUDE_DETAILS
#define UNITY_CLR_DETAILS()
#define UNITY_SET_DETAIL(d1)
#define UNITY_SET_DETAILS(d1,d2)
#else
#define UNITY_CLR_DETAILS() { Unity.CurrentDetail1 = 0; Unity.CurrentDetail2 = 0; }
#define UNITY_SET_DETAIL(d1) { Unity.CurrentDetail1 = (d1); Unity.CurrentDetail2 = 0; }
#define UNITY_SET_DETAILS(d1,d2) { Unity.CurrentDetail1 = (d1); Unity.CurrentDetail2 = (d2); }
#ifndef UNITY_DETAIL1_NAME
#define UNITY_DETAIL1_NAME "Function"
#endif
#ifndef UNITY_DETAIL2_NAME
#define UNITY_DETAIL2_NAME "Argument"
#endif
#endif
#ifdef UNITY_PRINT_TEST_CONTEXT
void UNITY_PRINT_TEST_CONTEXT(void);
#endif
/*-------------------------------------------------------
* Test Output
*-------------------------------------------------------*/
void UnityPrint(const char* string);
#ifdef UNITY_INCLUDE_PRINT_FORMATTED
void UnityPrintF(const UNITY_LINE_TYPE line, const char* format, ...);
#endif
void UnityPrintLen(const char* string, const UNITY_UINT32 length);
void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number);
void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style);
void UnityPrintNumber(const UNITY_INT number_to_print);
void UnityPrintNumberUnsigned(const UNITY_UINT number);
void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles_to_print);
#ifndef UNITY_EXCLUDE_FLOAT_PRINT
void UnityPrintFloat(const UNITY_DOUBLE input_number);
#endif
/*-------------------------------------------------------
* Test Assertion Functions
*-------------------------------------------------------
* Use the macros below this section instead of calling
* these directly. The macros have a consistent naming
* convention and will pull in file and line information
* for you. */
void UnityAssertEqualNumber(const UNITY_INT expected,
const UNITY_INT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style);
void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold,
const UNITY_INT actual,
const UNITY_COMPARISON_T compare,
const char *msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style);
void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected,
UNITY_INTERNAL_PTR actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style,
const UNITY_FLAGS_T flags);
void UnityAssertBits(const UNITY_INT mask,
const UNITY_INT expected,
const UNITY_INT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber);
void UnityAssertEqualString(const char* expected,
const char* actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber);
void UnityAssertEqualStringLen(const char* expected,
const char* actual,
const UNITY_UINT32 length,
const char* msg,
const UNITY_LINE_TYPE lineNumber);
void UnityAssertEqualStringArray( UNITY_INTERNAL_PTR expected,
const char** actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLAGS_T flags);
void UnityAssertEqualMemory( UNITY_INTERNAL_PTR expected,
UNITY_INTERNAL_PTR actual,
const UNITY_UINT32 length,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLAGS_T flags);
void UnityAssertNumbersWithin(const UNITY_UINT delta,
const UNITY_INT expected,
const UNITY_INT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style);
void UnityAssertNumbersArrayWithin(const UNITY_UINT delta,
UNITY_INTERNAL_PTR expected,
UNITY_INTERNAL_PTR actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_DISPLAY_STYLE_T style,
const UNITY_FLAGS_T flags);
#ifndef UNITY_EXCLUDE_SETJMP_H
void UnityFail(const char* message, const UNITY_LINE_TYPE line) UNITY_FUNCTION_ATTR(noreturn);
void UnityIgnore(const char* message, const UNITY_LINE_TYPE line) UNITY_FUNCTION_ATTR(noreturn);
#else
void UnityFail(const char* message, const UNITY_LINE_TYPE line);
void UnityIgnore(const char* message, const UNITY_LINE_TYPE line);
#endif
void UnityMessage(const char* message, const UNITY_LINE_TYPE line);
#ifndef UNITY_EXCLUDE_FLOAT
void UnityAssertFloatsWithin(const UNITY_FLOAT delta,
const UNITY_FLOAT expected,
const UNITY_FLOAT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber);
void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected,
UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLAGS_T flags);
void UnityAssertFloatSpecial(const UNITY_FLOAT actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLOAT_TRAIT_T style);
#endif
#ifndef UNITY_EXCLUDE_DOUBLE
void UnityAssertDoublesWithin(const UNITY_DOUBLE delta,
const UNITY_DOUBLE expected,
const UNITY_DOUBLE actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber);
void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected,
UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual,
const UNITY_UINT32 num_elements,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLAGS_T flags);
void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual,
const char* msg,
const UNITY_LINE_TYPE lineNumber,
const UNITY_FLOAT_TRAIT_T style);
#endif
/*-------------------------------------------------------
* Helpers
*-------------------------------------------------------*/
UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size);
#ifndef UNITY_EXCLUDE_FLOAT
UNITY_INTERNAL_PTR UnityFloatToPtr(const float num);
#endif
#ifndef UNITY_EXCLUDE_DOUBLE
UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num);
#endif
/*-------------------------------------------------------
* Error Strings We Might Need
*-------------------------------------------------------*/
extern const char UnityStrOk[];
extern const char UnityStrPass[];
extern const char UnityStrFail[];
extern const char UnityStrIgnore[];
extern const char UnityStrErrFloat[];
extern const char UnityStrErrDouble[];
extern const char UnityStrErr64[];
extern const char UnityStrErrShorthand[];
/*-------------------------------------------------------
* Test Running Macros
*-------------------------------------------------------*/
#ifndef UNITY_EXCLUDE_SETJMP_H
#define TEST_PROTECT() (setjmp(Unity.AbortFrame) == 0)
#define TEST_ABORT() longjmp(Unity.AbortFrame, 1)
#else
#define TEST_PROTECT() 1
#define TEST_ABORT() return
#endif
/* This tricky series of macros gives us an optional line argument to treat it as RUN_TEST(func, num=__LINE__) */
#ifndef RUN_TEST
#ifdef __STDC_VERSION__
#if __STDC_VERSION__ >= 199901L
#define UNITY_SUPPORT_VARIADIC_MACROS
#endif
#endif
#ifdef UNITY_SUPPORT_VARIADIC_MACROS
#define RUN_TEST(...) RUN_TEST_AT_LINE(__VA_ARGS__, __LINE__, throwaway)
#define RUN_TEST_AT_LINE(func, line, ...) UnityDefaultTestRun(func, #func, line)
#endif
#endif
/* If we can't do the tricky version, we'll just have to require them to always include the line number */
#ifndef RUN_TEST
#ifdef CMOCK
#define RUN_TEST(func, num) UnityDefaultTestRun(func, #func, num)
#else
#define RUN_TEST(func) UnityDefaultTestRun(func, #func, __LINE__)
#endif
#endif
#define TEST_LINE_NUM (Unity.CurrentTestLineNumber)
#define TEST_IS_IGNORED (Unity.CurrentTestIgnored)
#define UNITY_NEW_TEST(a) \
Unity.CurrentTestName = (a); \
Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)(__LINE__); \
Unity.NumberOfTests++;
#ifndef UNITY_BEGIN
#define UNITY_BEGIN() UnityBegin(__FILE__)
#endif
#ifndef UNITY_END
#define UNITY_END() UnityEnd()
#endif
#ifndef UNITY_SHORTHAND_AS_INT
#ifndef UNITY_SHORTHAND_AS_MEM
#ifndef UNITY_SHORTHAND_AS_NONE
#ifndef UNITY_SHORTHAND_AS_RAW
#define UNITY_SHORTHAND_AS_OLD
#endif
#endif
#endif
#endif
/*-----------------------------------------------
* Command Line Argument Support
*-----------------------------------------------*/
#ifdef UNITY_USE_COMMAND_LINE_ARGS
int UnityParseOptions(int argc, char** argv);
int UnityTestMatches(void);
#endif
/*-------------------------------------------------------
* Basic Fail and Ignore
*-------------------------------------------------------*/
#define UNITY_TEST_FAIL(line, message) UnityFail( (message), (UNITY_LINE_TYPE)(line))
#define UNITY_TEST_IGNORE(line, message) UnityIgnore( (message), (UNITY_LINE_TYPE)(line))
/*-------------------------------------------------------
* Test Asserts
*-------------------------------------------------------*/
#define UNITY_TEST_ASSERT(condition, line, message) do {if (condition) {} else {UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), (message));}} while(0)
#define UNITY_TEST_ASSERT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) == NULL), (UNITY_LINE_TYPE)(line), (message))
#define UNITY_TEST_ASSERT_NOT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) != NULL), (UNITY_LINE_TYPE)(line), (message))
#define UNITY_TEST_ASSERT_EMPTY(pointer, line, message) UNITY_TEST_ASSERT(((pointer[0]) == 0), (UNITY_LINE_TYPE)(line), (message))
#define UNITY_TEST_ASSERT_NOT_EMPTY(pointer, line, message) UNITY_TEST_ASSERT(((pointer[0]) != 0), (UNITY_LINE_TYPE)(line), (message))
#define UNITY_TEST_ASSERT_EQUAL_INT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_EQUAL_INT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_EQUAL_INT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_EQUAL_INT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_EQUAL_UINT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_EQUAL_UINT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_EQUAL_UINT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_EQUAL_UINT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_EQUAL_HEX8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_EQUAL_HEX16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_EQUAL_HEX32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_EQUAL_CHAR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR)
#define UNITY_TEST_ASSERT_BITS(mask, expected, actual, line, message) UnityAssertBits((UNITY_INT)(mask), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line))
#define UNITY_TEST_ASSERT_NOT_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_NOT_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_NOT_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_NOT_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_NOT_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR)
#define UNITY_TEST_ASSERT_GREATER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_GREATER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_GREATER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_GREATER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_GREATER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR)
#define UNITY_TEST_ASSERT_SMALLER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_SMALLER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_SMALLER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_SMALLER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_SMALLER_THAN_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 ) (threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16) (threshold), (UNITY_INT)(UNITY_INT16) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32) (threshold), (UNITY_INT)(UNITY_INT32) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 ) (threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR)
#define UNITY_TEST_ASSERT_INT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin( (delta), (UNITY_INT) (expected), (UNITY_INT) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT)
#define UNITY_TEST_ASSERT_INT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 ) (expected), (UNITY_INT)(UNITY_INT8 ) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8)
#define UNITY_TEST_ASSERT_INT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_INT16) (expected), (UNITY_INT)(UNITY_INT16) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16)
#define UNITY_TEST_ASSERT_INT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_INT32) (expected), (UNITY_INT)(UNITY_INT32) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32)
#define UNITY_TEST_ASSERT_UINT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin( (delta), (UNITY_INT) (expected), (UNITY_INT) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT)
#define UNITY_TEST_ASSERT_UINT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8)
#define UNITY_TEST_ASSERT_UINT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16)
#define UNITY_TEST_ASSERT_UINT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32)
#define UNITY_TEST_ASSERT_HEX8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8)
#define UNITY_TEST_ASSERT_HEX16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16)
#define UNITY_TEST_ASSERT_HEX32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32)
#define UNITY_TEST_ASSERT_CHAR_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 ) (expected), (UNITY_INT)(UNITY_INT8 ) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR)
#define UNITY_TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_PTR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_PTR_TO_INT)(expected), (UNITY_PTR_TO_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER)
#define UNITY_TEST_ASSERT_EQUAL_STRING(expected, actual, line, message) UnityAssertEqualString((const char*)(expected), (const char*)(actual), (message), (UNITY_LINE_TYPE)(line))
#define UNITY_TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len, line, message) UnityAssertEqualStringLen((const char*)(expected), (const char*)(actual), (UNITY_UINT32)(len), (message), (UNITY_LINE_TYPE)(line))
#define UNITY_TEST_ASSERT_EQUAL_MEMORY(expected, actual, len, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), 1, (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), (UNITY_INT_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), (UNITY_INT_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT16)(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT32)(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_PTR_TO_INT) (expected), (UNITY_POINTER_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_VAL)
#ifdef UNITY_SUPPORT_64
#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#define UNITY_TEST_ASSERT_NOT_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64)
#define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY)
#else
#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64)
#endif
#ifdef UNITY_EXCLUDE_FLOAT
#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat)
#else
#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UnityAssertFloatsWithin((UNITY_FLOAT)(delta), (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line))
#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((UNITY_FLOAT)(expected) * (UNITY_FLOAT)UNITY_FLOAT_PRECISION, (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (UNITY_LINE_TYPE)(line), (message))
#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray((UNITY_FLOAT*)(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray(UnityFloatToPtr(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF)
#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF)
#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN)
#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN)
#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET)
#endif
#ifdef UNITY_EXCLUDE_DOUBLE
#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble)
#else
#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UnityAssertDoublesWithin((UNITY_DOUBLE)(delta), (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line))
#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((UNITY_DOUBLE)(expected) * (UNITY_DOUBLE)UNITY_DOUBLE_PRECISION, (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (UNITY_LINE_TYPE)(line), (message))
#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray((UNITY_DOUBLE*)(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY)
#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray(UnityDoubleToPtr(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL)
#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN)
#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN)
#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET)
#endif
/* End of UNITY_INTERNALS_H */
#endif
#endif /*LV_BUILD_TEST*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/unity/unity_internals.h | C | apache-2.0 | 87,021 |
/**
* @file lv_test_assert.c
*
* Copyright 2002-2010 Guillaume Cottenceau.
*
* This software may be freely redistributed under the terms
* of the X11 license.
*
*/
/*********************
* INCLUDES
*********************/
#if LV_BUILD_TEST
#include "../lvgl.h"
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include "unity.h"
#define PNG_DEBUG 3
#include <png.h>
/*********************
* DEFINES
*********************/
//#define REF_IMGS_PATH "lvgl/tests/lv_test_ref_imgs/"
#define REF_IMGS_PATH "ref_imgs/"
/**********************
* TYPEDEFS
**********************/
typedef struct {
int width, height;
png_byte color_type;
png_byte bit_depth;
png_structp png_ptr;
png_infop info_ptr;
int number_of_passes;
png_bytep * row_pointers;
}png_img_t;
/**********************
* STATIC PROTOTYPES
**********************/
static int read_png_file(png_img_t * p, const char* file_name);
static void png_release(png_img_t * p);
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
bool lv_test_assert_img_eq(const char * fn_ref)
{
char fn_ref_full[512];
sprintf(fn_ref_full, "%s%s", REF_IMGS_PATH, fn_ref);
png_img_t p;
int res = read_png_file(&p, fn_ref_full);
if(res < 0) return false;
uint8_t * screen_buf;
lv_obj_invalidate(lv_scr_act());
lv_refr_now(NULL);
extern lv_color_t test_fb[];
screen_buf = (uint8_t *)test_fb;
uint8_t * ptr_act = NULL;
const png_byte* ptr_ref = NULL;
bool err = false;
int x, y, i_buf = 0;
for (y = 0; y < p.height; y++) {
png_byte* row = p.row_pointers[y];
//printf("\n");
for (x = 0; x < p.width; x++) {
ptr_ref = &(row[x*3]);
ptr_act = &(screen_buf[i_buf*4]);
uint32_t ref_px = 0;
uint32_t act_px = 0;
memcpy(&ref_px, ptr_ref, 3);
memcpy(&act_px, ptr_act, 3);
//printf("0xFF%06x, ", act_px);
uint8_t act_swap[3] = {ptr_act[2], ptr_act[1], ptr_act[0]};
if(memcmp(act_swap, ptr_ref, 3) != 0) {
err = true;
break;
}
i_buf++;
}
if(err) break;
}
png_release(&p);
if(err) {
uint32_t ref_px = 0;
uint32_t act_px = 0;
memcpy(&ref_px, ptr_ref, 3);
memcpy(&act_px, ptr_act, 3);
TEST_PRINTF("Diff in %s at (%d;%d), %x instead of %x)", fn_ref, x, y, act_px, ref_px);
FILE * f = fopen("../test_screenshot_error.h", "w");
fprintf(f, "static const uint32_t test_screenshot_error_data[] = {\n");
i_buf = 0;
for (y = 0; y < 480; y++) {
fprintf(f, "\n");
for (x = 0; x < 800; x++) {
ptr_act = &(screen_buf[i_buf * 4]);
act_px = 0;
memcpy(&act_px, ptr_act, 3);
fprintf(f, "0xFF%06X, ", act_px);
i_buf++;
}
}
fprintf(f, "};\n\n");
fprintf(f, "static lv_img_dsc_t test_screenshot_error_dsc = { \n"
" .header.w = 800,\n"
" .header.h = 480,\n"
" .header.always_zero = 0,\n"
" .header.cf = LV_IMG_CF_TRUE_COLOR,\n"
" .data_size = 800 * 480 * 4,\n"
" .data = test_screenshot_error_data};\n\n"
"static inline void test_screenshot_error_show(void)\n"
"{\n"
" lv_obj_t * img = lv_img_create(lv_scr_act());\n"
" lv_img_set_src(img, &test_screenshot_error_dsc);\n"
"}\n");
fclose(f);
return false;
}
return true;
}
/**********************
* STATIC FUNCTIONS
**********************/
static int read_png_file(png_img_t * p, const char* file_name)
{
char header[8]; // 8 is the maximum size that can be checked
/*open file and test for it being a png*/
FILE *fp = fopen(file_name, "rb");
if (!fp) {
TEST_PRINTF("%s", "PNG file %s could not be opened for reading");
return -1;
}
size_t rcnt = fread(header, 1, 8, fp);
if (rcnt != 8 || png_sig_cmp((png_const_bytep)header, 0, 8)) {
TEST_PRINTF("%s is not recognized as a PNG file", file_name);
return -1;
}
/*initialize stuff*/
p->png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!p->png_ptr) {
TEST_PRINTF("%s", "png_create_read_struct failed");
return -1;
}
p->info_ptr = png_create_info_struct(p->png_ptr);
if (!p->info_ptr) {
TEST_PRINTF("%s", "png_create_info_struct failed");
return -1;
}
if (setjmp(png_jmpbuf(p->png_ptr))) {
TEST_PRINTF("%s", "Error during init_io");
return -1;
}
png_init_io(p->png_ptr, fp);
png_set_sig_bytes(p->png_ptr, 8);
png_read_info(p->png_ptr, p->info_ptr);
p->width = png_get_image_width(p->png_ptr, p->info_ptr);
p->height = png_get_image_height(p->png_ptr, p->info_ptr);
p->color_type = png_get_color_type(p->png_ptr, p->info_ptr);
p->bit_depth = png_get_bit_depth(p->png_ptr, p->info_ptr);
p->number_of_passes = png_set_interlace_handling(p->png_ptr);
png_read_update_info(p->png_ptr, p->info_ptr);
/*read file*/
if (setjmp(png_jmpbuf(p->png_ptr))) {
TEST_PRINTF("%s", "Error during read_image");
return -1;
}
p->row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * p->height);
int y;
for (y=0; y<p->height; y++)
p->row_pointers[y] = (png_byte*) malloc(png_get_rowbytes(p->png_ptr,p->info_ptr));
png_read_image(p->png_ptr, p->row_pointers);
fclose(fp);
return 0;
}
static void png_release(png_img_t * p)
{
int y;
for (y=0; y<p->height; y++) free(p->row_pointers[y]);
free(p->row_pointers);
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/unity/unity_support.c | C | apache-2.0 | 5,831 |
#ifndef LV_UNITY_SUPPORT_H
#define LV_UNITY_SUPPORT_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include "../../lvgl.h"
bool lv_test_assert_img_eq(const char * fn_ref);
#if LV_COLOR_DEPTH != 32
# define TEST_ASSERT_EQUAL_SCREENSHOT(path) TEST_IGNORE_MESSAGE("Requires LV_COLOR_DEPTH 32");
# define TEST_ASSERT_EQUAL_SCREENSHOT_MESSAGE(path, msg) TEST_PRINTF(msg); TEST_IGNORE_MESSAGE("Requires LV_COLOR_DEPTH 32");
#else
# define TEST_ASSERT_EQUAL_SCREENSHOT(path) if(LV_HOR_RES != 800 || LV_VER_RES != 480) { \
TEST_IGNORE_MESSAGE("Requires 800x480 resolution"); \
} else { \
TEST_ASSERT(lv_test_assert_img_eq(path)); \
}
# define TEST_ASSERT_EQUAL_SCREENSHOT_MESSAGE(path, msg) if(LV_HOR_RES != 800 || LV_VER_RES != 480) { \
TEST_PRINTF(msg); \
TEST_IGNORE_MESSAGE("Requires 800x480 resolution"); \
} else { \
TEST_ASSERT_MESSAGE(lv_test_assert_img_eq(path), msg); \
}
#endif
# define TEST_ASSERT_EQUAL_COLOR(c1, c2) TEST_ASSERT_EQUAL_UINT32(c1.full, c2.full)
# define TEST_ASSERT_EQUAL_COLOR_MESSAGE(c1, c2, msg) TEST_ASSERT_EQUAL_UINT32_MESSAGE(c1.full, c2.full, msg)
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_UNITY_SUPPORT_H*/
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/lvgl/tests/unity/unity_support.h | C | apache-2.0 | 2,070 |
find_package(Python3 REQUIRED COMPONENTS Interpreter)
find_program(AWK awk mawk gawk)
set(LV_BINDINGS_DIR ${CMAKE_CURRENT_LIST_DIR})
# Common function for creating LV bindings
function(lv_bindings)
set(_options)
set(_one_value_args OUTPUT)
set(_multi_value_args INPUT DEPENDS COMPILE_OPTIONS PP_OPTIONS GEN_OPTIONS FILTER)
cmake_parse_arguments(
PARSE_ARGV 0 LV
"${_options}"
"${_one_value_args}"
"${_multi_value_args}"
)
set(LV_PP ${LV_OUTPUT}.pp)
set(LV_MPY_METADATA ${LV_OUTPUT}.json)
add_custom_command(
OUTPUT
${LV_PP}
COMMAND
${CMAKE_C_COMPILER} -E -DPYCPARSER ${LV_COMPILE_OPTIONS} ${LV_PP_OPTIONS} "${LV_CFLAGS}" -I ${LV_BINDINGS_DIR}/pycparser/utils/fake_libc_include ${MICROPY_CPP_FLAGS} ${LV_INPUT} > ${LV_PP}
DEPENDS
${LV_INPUT}
${LV_DEPENDS}
${LV_BINDINGS_DIR}/pycparser/utils/fake_libc_include
IMPLICIT_DEPENDS
C ${LV_INPUT}
VERBATIM
COMMAND_EXPAND_LISTS
)
if(ESP_PLATFORM)
target_compile_options(${COMPONENT_LIB} PRIVATE ${LV_COMPILE_OPTIONS})
else()
target_compile_options(usermod_lv_bindings INTERFACE ${LV_COMPILE_OPTIONS})
endif()
if (DEFINED LV_FILTER)
set(LV_PP_FILTERED ${LV_PP}.filtered)
set(LV_AWK_CONDITION)
foreach(_f ${LV_FILTER})
string(APPEND LV_AWK_CONDITION "\$3!~\"${_f}\" && ")
endforeach()
string(APPEND LV_AWK_COMMAND "\$1==\"#\"{p=(${LV_AWK_CONDITION} 1)} p{print}")
# message("AWK COMMAND: ${LV_AWK_COMMAND}")
add_custom_command(
OUTPUT
${LV_PP_FILTERED}
COMMAND
${AWK} ${LV_AWK_COMMAND} ${LV_PP} > ${LV_PP_FILTERED}
DEPENDS
${LV_PP}
VERBATIM
COMMAND_EXPAND_LISTS
)
else()
set(LV_PP_FILTERED ${LV_PP})
endif()
add_custom_command(
OUTPUT
${LV_OUTPUT}
COMMAND
${Python3_EXECUTABLE} ${LV_BINDINGS_DIR}/gen/gen_mpy.py ${LV_GEN_OPTIONS} -MD ${LV_MPY_METADATA} -E ${LV_PP_FILTERED} ${LV_INPUT} > ${LV_OUTPUT} || (rm -f ${LV_OUTPUT} && /bin/false)
DEPENDS
${LV_BINDINGS_DIR}/gen/gen_mpy.py
${LV_PP_FILTERED}
COMMAND_EXPAND_LISTS
)
endfunction()
# Definitions for specific bindings
if(NOT LVGL_DIR)
set(LVGL_DIR ${LV_BINDINGS_DIR}/lvgl)
endif()
set(LV_PNG_DIR ${LV_BINDINGS_DIR}/driver/png/lodepng)
set(LV_MP ${CMAKE_BINARY_DIR}/lv_mp.c)
set(LV_PNG ${CMAKE_BINARY_DIR}/lv_png.c)
set(LV_PNG_C ${CMAKE_BINARY_DIR}/lv_png_c.c)
if(ESP_PLATFORM)
idf_build_get_property(LV_ESPIDF_ENABLE LV_ESPIDF_ENABLE)
if(LV_ESPIDF_ENABLE)
set(LV_ESPIDF ${CMAKE_BINARY_DIR}/lv_espidf.c)
endif()
endif()
# Function for creating all specific bindings
function(all_lv_bindings)
# LVGL bindings
if(LV_CONFIG_DIR)
file(GLOB_RECURSE LVGL_HEADERS ${LVGL_DIR}/src/*.h ${LV_CONFIG_DIR}/lv_conf.h)
else()
file(GLOB_RECURSE LVGL_HEADERS ${LVGL_DIR}/src/*.h ${LV_BINDINGS_DIR}/lv_conf.h)
endif()
lv_bindings(
OUTPUT
${LV_MP}
INPUT
${LVGL_DIR}/lvgl.h
DEPENDS
${LVGL_HEADERS}
GEN_OPTIONS
-M lvgl -MP lv
)
# LODEPNG bindings
file(GLOB_RECURSE LV_PNG_HEADERS ${LV_PNG_DIR}/*.h)
configure_file(${LV_PNG_DIR}/lodepng.cpp ${LV_PNG_C} COPYONLY)
lv_bindings(
OUTPUT
${LV_PNG}
INPUT
${LV_PNG_DIR}/lodepng.h
DEPENDS
${LV_PNG_HEADERS}
COMPILE_OPTIONS
-DLODEPNG_NO_COMPILE_ENCODER -DLODEPNG_NO_COMPILE_ALLOCATORS
GEN_OPTIONS
-M lodepng
)
# ESPIDF bindings
if(ESP_PLATFORM)
idf_build_get_property(LV_ESPIDF_ENABLE LV_ESPIDF_ENABLE)
if(LV_ESPIDF_ENABLE)
file(GLOB_RECURSE LV_ESPIDF_HEADERS ${IDF_PATH}/components/*.h ${LV_BINDINGS_DIR}/driver/esp32/*.h)
lv_bindings(
OUTPUT
${LV_ESPIDF}
INPUT
${LV_BINDINGS_DIR}/driver/esp32/espidf.h
DEPENDS
${LV_ESPIDF_HEADERS}
GEN_OPTIONS
-M espidf
FILTER
i2s_ll.h
i2s_hal.h
esp_intr_alloc.h
soc/spi_periph.h
rom/ets_sys.h
soc/sens_struct.h
soc/rtc.h
driver/periph_ctrl.h
include/esp_private
)
endif()
endif()
endfunction()
# Add includes to CMake component
set(LV_INCLUDE
${LV_BINDINGS_DIR}
${LV_PNG_DIR}
)
# Add sources to CMake component
set(LV_SRC
${LV_MP}
${LV_PNG}
# ${LV_PNG_C}
${LV_BINDINGS_DIR}/driver/png/mp_lodepng.c
)
if(ESP_PLATFORM)
idf_build_get_property(LV_ESPIDF_ENABLE LV_ESPIDF_ENABLE)
if(LV_ESPIDF_ENABLE)
LIST(APPEND LV_SRC
${LV_BINDINGS_DIR}/driver/esp32/espidf.c
${LV_BINDINGS_DIR}/driver/esp32/modrtch.c
${LV_BINDINGS_DIR}/driver/esp32/sh2lib.c
${LV_ESPIDF}
)
endif()
endif(ESP_PLATFORM)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/mkrules.cmake | CMake | apache-2.0 | 5,356 |
# Cleanup all tables and PYC files to ensure no PLY stuff is cached
from __future__ import print_function
import itertools
import fnmatch
import os, shutil
file_patterns = ('yacctab.*', 'lextab.*', '*.pyc', '__pycache__')
def do_cleanup(root):
for path, dirs, files in os.walk(root):
for file in itertools.chain(dirs, files):
try:
for pattern in file_patterns:
if fnmatch.fnmatch(file, pattern):
fullpath = os.path.join(path, file)
if os.path.isdir(fullpath):
shutil.rmtree(fullpath, ignore_errors=False)
else:
os.unlink(fullpath)
print('Deleted', fullpath)
except OSError:
pass
if __name__ == "__main__":
do_cleanup('.')
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/_clean_tables.py | Python | apache-2.0 | 871 |
#------------------------------------------------------------------------------
# pycparser: c-to-c.py
#
# Example of using pycparser.c_generator, serving as a simplistic translator
# from C to AST and back to C.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#------------------------------------------------------------------------------
from __future__ import print_function
import sys
# This is not required if you've installed pycparser into
# your site-packages/ with setup.py
sys.path.extend(['.', '..'])
from pycparser import parse_file, c_generator
def translate_to_c(filename):
""" Simply use the c_generator module to emit a parsed AST.
"""
ast = parse_file(filename, use_cpp=True)
generator = c_generator.CGenerator()
print(generator.visit(ast))
if __name__ == "__main__":
if len(sys.argv) > 1:
translate_to_c(sys.argv[1])
else:
print("Please provide a filename as argument")
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/c-to-c.py | Python | apache-2.0 | 957 |
char foo(void)
{
return '1';
}
int maxout_in(int paste, char** matrix)
{
char o = foo();
return (int) matrix[1][2] * 5 - paste;
}
int main()
{
auto char* multi = "a multi";
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/c_files/funky.c | C | apache-2.0 | 206 |
/*
** C implementation of a hash table ADT
*/
typedef enum tagReturnCode {SUCCESS, FAIL} ReturnCode;
typedef struct tagEntry
{
char* key;
char* value;
} Entry;
typedef struct tagNode
{
Entry* entry;
struct tagNode* next;
} Node;
typedef struct tagHash
{
unsigned int table_size;
Node** heads;
} Hash;
static unsigned int hash_func(const char* str, unsigned int table_size)
{
unsigned int hash_value;
unsigned int a = 127;
for (hash_value = 0; *str != 0; ++str)
hash_value = (a*hash_value + *str) % table_size;
return hash_value;
}
ReturnCode HashCreate(Hash** hash, unsigned int table_size)
{
unsigned int i;
if (table_size < 1)
return FAIL;
//
// Allocate space for the Hash
//
if (((*hash) = malloc(sizeof(**hash))) == NULL)
return FAIL;
//
// Allocate space for the array of list heads
//
if (((*hash)->heads = malloc(table_size*sizeof(*((*hash)->heads)))) == NULL)
return FAIL;
//
// Initialize Hash info
//
for (i = 0; i < table_size; ++i)
{
(*hash)->heads[i] = NULL;
}
(*hash)->table_size = table_size;
return SUCCESS;
}
ReturnCode HashInsert(Hash* hash, const Entry* entry)
{
unsigned int index = hash_func(entry->key, hash->table_size);
Node* temp = hash->heads[index];
HashRemove(hash, entry->key);
if ((hash->heads[index] = malloc(sizeof(Node))) == NULL)
return FAIL;
hash->heads[index]->entry = malloc(sizeof(Entry));
hash->heads[index]->entry->key = malloc(strlen(entry->key)+1);
hash->heads[index]->entry->value = malloc(strlen(entry->value)+1);
strcpy(hash->heads[index]->entry->key, entry->key);
strcpy(hash->heads[index]->entry->value, entry->value);
hash->heads[index]->next = temp;
return SUCCESS;
}
const Entry* HashFind(const Hash* hash, const char* key)
{
unsigned int index = hash_func(key, hash->table_size);
Node* temp = hash->heads[index];
while (temp != NULL)
{
if (!strcmp(key, temp->entry->key))
return temp->entry;
temp = temp->next;
}
return NULL;
}
ReturnCode HashRemove(Hash* hash, const char* key)
{
unsigned int index = hash_func(key, hash->table_size);
Node* temp1 = hash->heads[index];
Node* temp2 = temp1;
while (temp1 != NULL)
{
if (!strcmp(key, temp1->entry->key))
{
if (temp1 == hash->heads[index])
hash->heads[index] = hash->heads[index]->next;
else
temp2->next = temp1->next;
free(temp1->entry->key);
free(temp1->entry->value);
free(temp1->entry);
free(temp1);
temp1 = NULL;
return SUCCESS;
}
temp2 = temp1;
temp1 = temp1->next;
}
return FAIL;
}
void HashPrint(Hash* hash, void (*PrintFunc)(char*, char*))
{
unsigned int i;
if (hash == NULL || hash->heads == NULL)
return;
for (i = 0; i < hash->table_size; ++i)
{
Node* temp = hash->heads[i];
while (temp != NULL)
{
PrintFunc(temp->entry->key, temp->entry->value);
temp = temp->next;
}
}
}
void HashDestroy(Hash* hash)
{
unsigned int i;
if (hash == NULL)
return;
for (i = 0; i < hash->table_size; ++i)
{
Node* temp = hash->heads[i];
while (temp != NULL)
{
Node* temp2 = temp;
free(temp->entry->key);
free(temp->entry->value);
free(temp->entry);
temp = temp->next;
free(temp2);
}
}
free(hash->heads);
hash->heads = NULL;
free(hash);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/c_files/hash.c | C | apache-2.0 | 3,790 |
//----------------------------------------------------------------
// Statically-allocated memory manager
//
// by Eli Bendersky (eliben@gmail.com)
//
// This code is in the public domain.
//----------------------------------------------------------------
#include "memmgr.h"
typedef ulong Align;
union mem_header_union
{
struct
{
// Pointer to the next block in the free list
//
union mem_header_union* next;
// Size of the block (in quantas of sizeof(mem_header_t))
//
ulong size;
} s;
// Used to align headers in memory to a boundary
//
Align align_dummy;
};
typedef union mem_header_union mem_header_t;
// Initial empty list
//
static mem_header_t base;
// Start of free list
//
static mem_header_t* freep = 0;
// Static pool for new allocations
//
static byte pool[POOL_SIZE] = {0};
static ulong pool_free_pos = 0;
void memmgr_init()
{
base.s.next = 0;
base.s.size = 0;
freep = 0;
pool_free_pos = 0;
}
static mem_header_t* get_mem_from_pool(ulong nquantas)
{
ulong total_req_size;
mem_header_t* h;
if (nquantas < MIN_POOL_ALLOC_QUANTAS)
nquantas = MIN_POOL_ALLOC_QUANTAS;
total_req_size = nquantas * sizeof(mem_header_t);
if (pool_free_pos + total_req_size <= POOL_SIZE)
{
h = (mem_header_t*) (pool + pool_free_pos);
h->s.size = nquantas;
memmgr_free((void*) (h + 1));
pool_free_pos += total_req_size;
}
else
{
return 0;
}
return freep;
}
// Allocations are done in 'quantas' of header size.
// The search for a free block of adequate size begins at the point 'freep'
// where the last block was found.
// If a too-big block is found, it is split and the tail is returned (this
// way the header of the original needs only to have its size adjusted).
// The pointer returned to the user points to the free space within the block,
// which begins one quanta after the header.
//
void* memmgr_alloc(ulong nbytes)
{
mem_header_t* p;
mem_header_t* prevp;
// Calculate how many quantas are required: we need enough to house all
// the requested bytes, plus the header. The -1 and +1 are there to make sure
// that if nbytes is a multiple of nquantas, we don't allocate too much
//
ulong nquantas = (nbytes + sizeof(mem_header_t) - 1) / sizeof(mem_header_t) + 1;
// First alloc call, and no free list yet ? Use 'base' for an initial
// denegerate block of size 0, which points to itself
//
if ((prevp = freep) == 0)
{
base.s.next = freep = prevp = &base;
base.s.size = 0;
}
for (p = prevp->s.next; ; prevp = p, p = p->s.next)
{
// big enough ?
if (p->s.size >= nquantas)
{
// exactly ?
if (p->s.size == nquantas)
{
// just eliminate this block from the free list by pointing
// its prev's next to its next
//
prevp->s.next = p->s.next;
}
else // too big
{
p->s.size -= nquantas;
p += p->s.size;
p->s.size = nquantas;
}
freep = prevp;
return (void*) (p + 1);
}
// Reached end of free list ?
// Try to allocate the block from the pool. If that succeeds,
// get_mem_from_pool adds the new block to the free list and
// it will be found in the following iterations. If the call
// to get_mem_from_pool doesn't succeed, we've run out of
// memory
//
else if (p == freep)
{
if ((p = get_mem_from_pool(nquantas)) == 0)
{
#ifdef DEBUG_MEMMGR_FATAL
printf("!! Memory allocation failed !!\n");
#endif
return 0;
}
}
}
}
// Scans the free list, starting at freep, looking the the place to insert the
// free block. This is either between two existing blocks or at the end of the
// list. In any case, if the block being freed is adjacent to either neighbor,
// the adjacent blocks are combined.
//
void memmgr_free(void* ap)
{
mem_header_t* block;
mem_header_t* p;
// acquire pointer to block header
block = ((mem_header_t*) ap) - 1;
// Find the correct place to place the block in (the free list is sorted by
// address, increasing order)
//
for (p = freep; !(block > p && block < p->s.next); p = p->s.next)
{
// Since the free list is circular, there is one link where a
// higher-addressed block points to a lower-addressed block.
// This condition checks if the block should be actually
// inserted between them
//
if (p >= p->s.next && (block > p || block < p->s.next))
break;
}
// Try to combine with the higher neighbor
//
if (block + block->s.size == p->s.next)
{
block->s.size += p->s.next->s.size;
block->s.next = p->s.next->s.next;
}
else
{
block->s.next = p->s.next;
}
// Try to combine with the lower neighbor
//
if (p + p->s.size == block)
{
p->s.size += block->s.size;
p->s.next = block->s.next;
}
else
{
p->s.next = block;
}
freep = p;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/c_files/memmgr.c | C | apache-2.0 | 5,379 |
//----------------------------------------------------------------
// Statically-allocated memory manager
//
// by Eli Bendersky (eliben@gmail.com)
//
// This code is in the public domain.
//----------------------------------------------------------------
#ifndef MEMMGR_H
#define MEMMGR_H
//
// Memory manager: dynamically allocates memory from
// a fixed pool that is allocated statically at link-time.
//
// Usage: after calling memmgr_init() in your
// initialization routine, just use memmgr_alloc() instead
// of malloc() and memmgr_free() instead of free().
// Naturally, you can use the preprocessor to define
// malloc() and free() as aliases to memmgr_alloc() and
// memmgr_free(). This way the manager will be a drop-in
// replacement for the standard C library allocators, and can
// be useful for debugging memory allocation problems and
// leaks.
//
// Preprocessor flags you can define to customize the
// memory manager:
//
// DEBUG_MEMMGR_FATAL
// Allow printing out a message when allocations fail
//
// DEBUG_MEMMGR_SUPPORT_STATS
// Allow printing out of stats in function
// memmgr_print_stats When this is disabled,
// memmgr_print_stats does nothing.
//
// Note that in production code on an embedded system
// you'll probably want to keep those undefined, because
// they cause printf to be called.
//
// POOL_SIZE
// Size of the pool for new allocations. This is
// effectively the heap size of the application, and can
// be changed in accordance with the available memory
// resources.
//
// MIN_POOL_ALLOC_QUANTAS
// Internally, the memory manager allocates memory in
// quantas roughly the size of two ulong objects. To
// minimize pool fragmentation in case of multiple allocations
// and deallocations, it is advisable to not allocate
// blocks that are too small.
// This flag sets the minimal ammount of quantas for
// an allocation. If the size of a ulong is 4 and you
// set this flag to 16, the minimal size of an allocation
// will be 4 * 2 * 16 = 128 bytes
// If you have a lot of small allocations, keep this value
// low to conserve memory. If you have mostly large
// allocations, it is best to make it higher, to avoid
// fragmentation.
//
// Notes:
// 1. This memory manager is *not thread safe*. Use it only
// for single thread/task applications.
//
#define DEBUG_MEMMGR_SUPPORT_STATS 1
#define POOL_SIZE 8 * 1024
#define MIN_POOL_ALLOC_QUANTAS 16
typedef unsigned char byte;
typedef unsigned long ulong;
// Initialize the memory manager. This function should be called
// only once in the beginning of the program.
//
void memmgr_init();
// 'malloc' clone
//
void* memmgr_alloc(ulong nbytes);
// 'free' clone
//
void memmgr_free(void* ap);
// Prints statistics about the current state of the memory
// manager
//
void memmgr_print_stats();
#endif // MEMMGR_H
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/c_files/memmgr.h | C | apache-2.0 | 2,883 |
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void convert(int thousands, int hundreds, int tens, int ones)
{
char *num[] = {"", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine"};
char *for_ten[] = {"", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty",
"Seventy", "Eighty", "Ninty"};
char *af_ten[] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
"Fifteen", "Sixteen", "Seventeen", "Eighteen", "Ninteen"};
printf("\nThe year in words is:\n");
printf("%s thousand", num[thousands]);
if (hundreds != 0)
printf(" %s hundred", num[hundreds]);
if (tens != 1)
printf(" %s %s", for_ten[tens], num[ones]);
else
printf(" %s", af_ten[ones]);
}
int main()
{
int year;
int n1000, n100, n10, n1;
printf("\nEnter the year (4 digits): ");
scanf("%d", &year);
if (year > 9999 || year < 1000)
{
printf("\nError !! The year must contain 4 digits.");
exit(EXIT_FAILURE);
}
n1000 = year/1000;
n100 = ((year)%1000)/100;
n10 = (year%100)/10;
n1 = ((year%10)%10);
convert(n1000, n100, n10, n1);
return 0;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/c_files/year.c | C | apache-2.0 | 1,109 |
#------------------------------------------------------------------------------
# pycparser: c_json.py
#
# by Michael White (@mypalmike)
#
# This example includes functions to serialize and deserialize an ast
# to and from json format. Serializing involves walking the ast and converting
# each node from a python Node object into a python dict. Deserializing
# involves the opposite conversion, walking the tree formed by the
# dict and converting each dict into the specific Node object it represents.
# The dict itself is serialized and deserialized using the python json module.
#
# The dict representation is a fairly direct transformation of the object
# attributes. Each node in the dict gets one metadata field referring to the
# specific node class name, _nodetype. Each local attribute (i.e. not linking
# to child nodes) has a string value or array of string values. Each child
# attribute is either another dict or an array of dicts, exactly as in the
# Node object representation. The "coord" attribute, representing the
# node's location within the source code, is serialized/deserialized from
# a Coord object into a string of the format "filename:line[:column]".
#
# Example TypeDecl node, with IdentifierType child node, represented as a dict:
# "type": {
# "_nodetype": "TypeDecl",
# "coord": "c_files/funky.c:8",
# "declname": "o",
# "quals": [],
# "type": {
# "_nodetype": "IdentifierType",
# "coord": "c_files/funky.c:8",
# "names": [
# "char"
# ]
# }
# }
#------------------------------------------------------------------------------
from __future__ import print_function
import json
import sys
import re
# This is not required if you've installed pycparser into
# your site-packages/ with setup.py
#
sys.path.extend(['.', '..'])
from pycparser import parse_file, c_ast
from pycparser.plyparser import Coord
RE_CHILD_ARRAY = re.compile(r'(.*)\[(.*)\]')
RE_INTERNAL_ATTR = re.compile('__.*__')
class CJsonError(Exception):
pass
def memodict(fn):
""" Fast memoization decorator for a function taking a single argument """
class memodict(dict):
def __missing__(self, key):
ret = self[key] = fn(key)
return ret
return memodict().__getitem__
@memodict
def child_attrs_of(klass):
"""
Given a Node class, get a set of child attrs.
Memoized to avoid highly repetitive string manipulation
"""
non_child_attrs = set(klass.attr_names)
all_attrs = set([i for i in klass.__slots__ if not RE_INTERNAL_ATTR.match(i)])
return all_attrs - non_child_attrs
def to_dict(node):
""" Recursively convert an ast into dict representation. """
klass = node.__class__
result = {}
# Metadata
result['_nodetype'] = klass.__name__
# Local node attributes
for attr in klass.attr_names:
result[attr] = getattr(node, attr)
# Coord object
if node.coord:
result['coord'] = str(node.coord)
else:
result['coord'] = None
# Child attributes
for child_name, child in node.children():
# Child strings are either simple (e.g. 'value') or arrays (e.g. 'block_items[1]')
match = RE_CHILD_ARRAY.match(child_name)
if match:
array_name, array_index = match.groups()
array_index = int(array_index)
# arrays come in order, so we verify and append.
result[array_name] = result.get(array_name, [])
if array_index != len(result[array_name]):
raise CJsonError('Internal ast error. Array {} out of order. '
'Expected index {}, got {}'.format(
array_name, len(result[array_name]), array_index))
result[array_name].append(to_dict(child))
else:
result[child_name] = to_dict(child)
# Any child attributes that were missing need "None" values in the json.
for child_attr in child_attrs_of(klass):
if child_attr not in result:
result[child_attr] = None
return result
def to_json(node, **kwargs):
""" Convert ast node to json string """
return json.dumps(to_dict(node), **kwargs)
def file_to_dict(filename):
""" Load C file into dict representation of ast """
ast = parse_file(filename, use_cpp=True)
return to_dict(ast)
def file_to_json(filename, **kwargs):
""" Load C file into json string representation of ast """
ast = parse_file(filename, use_cpp=True)
return to_json(ast, **kwargs)
def _parse_coord(coord_str):
""" Parse coord string (file:line[:column]) into Coord object. """
if coord_str is None:
return None
vals = coord_str.split(':')
vals.extend([None] * 3)
filename, line, column = vals[:3]
return Coord(filename, line, column)
def _convert_to_obj(value):
"""
Convert an object in the dict representation into an object.
Note: Mutually recursive with from_dict.
"""
value_type = type(value)
if value_type == dict:
return from_dict(value)
elif value_type == list:
return [_convert_to_obj(item) for item in value]
else:
# String
return value
def from_dict(node_dict):
""" Recursively build an ast from dict representation """
class_name = node_dict.pop('_nodetype')
klass = getattr(c_ast, class_name)
# Create a new dict containing the key-value pairs which we can pass
# to node constructors.
objs = {}
for key, value in node_dict.items():
if key == 'coord':
objs[key] = _parse_coord(value)
else:
objs[key] = _convert_to_obj(value)
# Use keyword parameters, which works thanks to beautifully consistent
# ast Node initializers.
return klass(**objs)
def from_json(ast_json):
""" Build an ast from json string representation """
return from_dict(json.loads(ast_json))
#------------------------------------------------------------------------------
if __name__ == "__main__":
if len(sys.argv) > 1:
# Some test code...
# Do trip from C -> ast -> dict -> ast -> json, then print.
ast_dict = file_to_dict(sys.argv[1])
ast = from_dict(ast_dict)
print(to_json(ast, sort_keys=True, indent=4))
else:
print("Please provide a filename as argument")
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/c_json.py | Python | apache-2.0 | 6,398 |
#-----------------------------------------------------------------
# pycparser: dump_ast.py
#
# Basic example of parsing a file and dumping its parsed AST.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
from __future__ import print_function
import argparse
import sys
# This is not required if you've installed pycparser into
# your site-packages/ with setup.py
sys.path.extend(['.', '..'])
from pycparser import c_parser, c_ast, parse_file
if __name__ == "__main__":
argparser = argparse.ArgumentParser('Dump AST')
argparser.add_argument('filename', help='name of file to parse')
argparser.add_argument('--coord', help='show coordinates in the dump',
action='store_true')
args = argparser.parse_args()
ast = parse_file(args.filename, use_cpp=False)
ast.show(showcoord=args.coord)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/dump_ast.py | Python | apache-2.0 | 922 |
#-----------------------------------------------------------------
# pycparser: explore_ast.py
#
# This example demonstrates how to "explore" the AST created by
# pycparser to understand its structure. The AST is a n-nary tree
# of nodes, each node having several children, each with a name.
# Just read the code, and let the comments guide you. The lines
# beginning with #~ can be uncommented to print out useful
# information from the AST.
# It helps to have the pycparser/_c_ast.cfg file in front of you.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
from __future__ import print_function
import sys
# This is not required if you've installed pycparser into
# your site-packages/ with setup.py
#
sys.path.extend(['.', '..'])
from pycparser import c_parser, c_ast
# This is some C source to parse. Note that pycparser must begin
# at the top level of the C file, i.e. with either declarations
# or function definitions (this is called "external declarations"
# in C grammar lingo)
#
# Also, a C parser must have all the types declared in order to
# build the correct AST. It doesn't matter what they're declared
# to, so I've inserted the dummy typedef in the code to let the
# parser know Hash and Node are types. You don't need to do it
# when parsing real, correct C code.
text = r"""
typedef int Node, Hash;
void HashPrint(Hash* hash, void (*PrintFunc)(char*, char*))
{
unsigned int i;
if (hash == NULL || hash->heads == NULL)
return;
for (i = 0; i < hash->table_size; ++i)
{
Node* temp = hash->heads[i];
while (temp != NULL)
{
PrintFunc(temp->entry->key, temp->entry->value);
temp = temp->next;
}
}
}
"""
# Create the parser and ask to parse the text. parse() will throw
# a ParseError if there's an error in the code
#
parser = c_parser.CParser()
ast = parser.parse(text, filename='<none>')
# Uncomment the following line to see the AST in a nice, human
# readable way. show() is the most useful tool in exploring ASTs
# created by pycparser. See the c_ast.py file for the options you
# can pass it.
#ast.show(showcoord=True)
# OK, we've seen that the top node is FileAST. This is always the
# top node of the AST. Its children are "external declarations",
# and are stored in a list called ext[] (see _c_ast.cfg for the
# names and types of Nodes and their children).
# As you see from the printout, our AST has two Typedef children
# and one FuncDef child.
# Let's explore FuncDef more closely. As I've mentioned, the list
# ext[] holds the children of FileAST. Since the function
# definition is the third child, it's ext[2]. Uncomment the
# following line to show it:
#ast.ext[2].show()
# A FuncDef consists of a declaration, a list of parameter
# declarations (for K&R style function definitions), and a body.
# First, let's examine the declaration.
function_decl = ast.ext[2].decl
# function_decl, like any other declaration, is a Decl. Its type child
# is a FuncDecl, which has a return type and arguments stored in a
# ParamList node
#function_decl.type.show()
#function_decl.type.args.show()
# The following displays the name and type of each argument:
#for param_decl in function_decl.type.args.params:
#print('Arg name: %s' % param_decl.name)
#print('Type:')
#param_decl.type.show(offset=6)
# The body is of FuncDef is a Compound, which is a placeholder for a block
# surrounded by {} (You should be reading _c_ast.cfg parallel to this
# explanation and seeing these things with your own eyes).
# Let's see the block's declarations:
function_body = ast.ext[2].body
# The following displays the declarations and statements in the function
# body
#for decl in function_body.block_items:
#decl.show()
# We can see a single variable declaration, i, declared to be a simple type
# declaration of type 'unsigned int', followed by statements.
# block_items is a list, so the third element is the For statement:
for_stmt = function_body.block_items[2]
#for_stmt.show()
# As you can see in _c_ast.cfg, For's children are 'init, cond,
# next' for the respective parts of the 'for' loop specifier,
# and stmt, which is either a single stmt or a Compound if there's
# a block.
#
# Let's dig deeper, to the while statement inside the for loop:
while_stmt = for_stmt.stmt.block_items[1]
#while_stmt.show()
# While is simpler, it only has a condition node and a stmt node.
# The condition:
while_cond = while_stmt.cond
#while_cond.show()
# Note that it's a BinaryOp node - the basic constituent of
# expressions in our AST. BinaryOp is the expression tree, with
# left and right nodes as children. It also has the op attribute,
# which is just the string representation of the operator.
#print(while_cond.op)
#while_cond.left.show()
#while_cond.right.show()
# That's it for the example. I hope you now see how easy it is to explore the
# AST created by pycparser. Although on the surface it is quite complex and has
# a lot of node types, this is the inherent complexity of the C language every
# parser/compiler designer has to cope with.
# Using the tools provided by the c_ast package it's easy to explore the
# structure of AST nodes and write code that processes them.
# Specifically, see the cdecl.py example for a non-trivial demonstration of what
# you can do by recursively going through the AST.
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/explore_ast.py | Python | apache-2.0 | 5,496 |
#-----------------------------------------------------------------
# pycparser: func_calls.py
#
# Using pycparser for printing out all the calls of some function
# in a C file.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
from __future__ import print_function
import sys
# This is not required if you've installed pycparser into
# your site-packages/ with setup.py
sys.path.extend(['.', '..'])
from pycparser import c_parser, c_ast, parse_file
# A visitor with some state information (the funcname it's looking for)
class FuncCallVisitor(c_ast.NodeVisitor):
def __init__(self, funcname):
self.funcname = funcname
def visit_FuncCall(self, node):
if node.name.name == self.funcname:
print('%s called at %s' % (self.funcname, node.name.coord))
# Visit args in case they contain more func calls.
if node.args:
self.visit(node.args)
def show_func_calls(filename, funcname):
ast = parse_file(filename, use_cpp=True)
v = FuncCallVisitor(funcname)
v.visit(ast)
if __name__ == "__main__":
if len(sys.argv) > 2:
filename = sys.argv[1]
func = sys.argv[2]
else:
filename = 'examples/c_files/hash.c'
func = 'malloc'
show_func_calls(filename, func)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/func_calls.py | Python | apache-2.0 | 1,353 |
#-----------------------------------------------------------------
# pycparser: func_defs_add_param.py
#
# Example of rewriting AST nodes to add parameters to function
# definitions. Adds an "int _hidden" to every function.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
from __future__ import print_function
import sys
from pycparser import c_parser, c_ast, c_generator
text = r"""
void foo(int a, int b) {
}
void bar() {
}
"""
class ParamAdder(c_ast.NodeVisitor):
def visit_FuncDecl(self, node):
ty = c_ast.TypeDecl(declname='_hidden',
quals=[],
type=c_ast.IdentifierType(['int']))
newdecl = c_ast.Decl(
name='_hidden',
quals=[],
storage=[],
funcspec=[],
type=ty,
init=None,
bitsize=None,
coord=node.coord)
if node.args:
node.args.params.append(newdecl)
else:
node.args = c_ast.ParamList(params=[newdecl])
if __name__ == '__main__':
parser = c_parser.CParser()
ast = parser.parse(text)
print("AST before change:")
ast.show(offset=2)
v = ParamAdder()
v.visit(ast)
print("\nAST after change:")
ast.show(offset=2)
print("\nCode after change:")
generator = c_generator.CGenerator()
print(generator.visit(ast))
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/func_defs_add_param.py | Python | apache-2.0 | 1,532 |
#-----------------------------------------------------------------
# pycparser: rewrite_ast.py
#
# Tiny example of rewriting a AST node
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
from __future__ import print_function
import sys
from pycparser import c_parser
text = r"""
void func(void)
{
x = 1;
}
"""
if __name__ == '__main__':
parser = c_parser.CParser()
ast = parser.parse(text)
print("Before:")
ast.show(offset=2)
assign = ast.ext[0].body.block_items[0]
assign.lvalue.name = "y"
assign.rvalue.value = 2
print("After:")
ast.show(offset=2)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/rewrite_ast.py | Python | apache-2.0 | 675 |
#-----------------------------------------------------------------
# pycparser: serialize_ast.py
#
# Simple example of serializing AST
#
# Hart Chu [https://github.com/CtheSky]
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
from __future__ import print_function
import pickle
from pycparser import c_parser
text = r"""
void func(void)
{
x = 1;
}
"""
parser = c_parser.CParser()
ast = parser.parse(text)
# Since AST nodes use __slots__ for faster attribute access and
# space saving, it needs Pickle's protocol version >= 2.
# The default version is 3 for python 3.x and 1 for python 2.7.
# You can always select the highest available protocol with the -1 argument.
with open('ast', 'wb') as f:
pickle.dump(ast, f, protocol=-1)
# Deserialize.
with open('ast', 'rb') as f:
ast = pickle.load(f)
ast.show()
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/serialize_ast.py | Python | apache-2.0 | 907 |
#-----------------------------------------------------------------
# pycparser: using_cpp_libc.py
#
# Shows how to use the provided 'cpp' (on Windows, substitute for
# the 'real' cpp if you're on Linux/Unix) and "fake" libc includes
# to parse a file that includes standard C headers.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
import sys
# This is not required if you've installed pycparser into
# your site-packages/ with setup.py
#
sys.path.extend(['.', '..'])
from pycparser import parse_file
if __name__ == "__main__":
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = 'examples/c_files/year.c'
ast = parse_file(filename, use_cpp=True,
cpp_path='cpp',
cpp_args=r'-Iutils/fake_libc_include')
ast.show()
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/using_cpp_libc.py | Python | apache-2.0 | 871 |
#-------------------------------------------------------------------------------
# pycparser: using_gcc_E_libc.py
#
# Similar to the using_cpp_libc.py example, but uses 'gcc -E' instead
# of 'cpp'. The same can be achieved with Clang instead of gcc. If you have
# Clang installed, simply replace 'gcc' with 'clang' here.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-------------------------------------------------------------------------------
import sys
# This is not required if you've installed pycparser into
# your site-packages/ with setup.py
#
sys.path.extend(['.', '..'])
from pycparser import parse_file
if __name__ == "__main__":
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = 'examples/c_files/year.c'
ast = parse_file(filename, use_cpp=True,
cpp_path='gcc',
cpp_args=['-E', r'-Iutils/fake_libc_include'])
ast.show()
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/examples/using_gcc_E_libc.py | Python | apache-2.0 | 929 |
#-----------------------------------------------------------------
# pycparser: __init__.py
#
# This package file exports some convenience functions for
# interacting with pycparser
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
__all__ = ['c_lexer', 'c_parser', 'c_ast']
__version__ = '2.20'
import io
from subprocess import check_output
from .c_parser import CParser
def preprocess_file(filename, cpp_path='cpp', cpp_args=''):
""" Preprocess a file using cpp.
filename:
Name of the file you want to preprocess.
cpp_path:
cpp_args:
Refer to the documentation of parse_file for the meaning of these
arguments.
When successful, returns the preprocessed file's contents.
Errors from cpp will be printed out.
"""
path_list = [cpp_path]
if isinstance(cpp_args, list):
path_list += cpp_args
elif cpp_args != '':
path_list += [cpp_args]
path_list += [filename]
try:
# Note the use of universal_newlines to treat all newlines
# as \n for Python's purpose
text = check_output(path_list, universal_newlines=True)
except OSError as e:
raise RuntimeError("Unable to invoke 'cpp'. " +
'Make sure its path was passed correctly\n' +
('Original error: %s' % e))
return text
def parse_file(filename, use_cpp=False, cpp_path='cpp', cpp_args='',
parser=None):
""" Parse a C file using pycparser.
filename:
Name of the file you want to parse.
use_cpp:
Set to True if you want to execute the C pre-processor
on the file prior to parsing it.
cpp_path:
If use_cpp is True, this is the path to 'cpp' on your
system. If no path is provided, it attempts to just
execute 'cpp', so it must be in your PATH.
cpp_args:
If use_cpp is True, set this to the command line arguments strings
to cpp. Be careful with quotes - it's best to pass a raw string
(r'') here. For example:
r'-I../utils/fake_libc_include'
If several arguments are required, pass a list of strings.
parser:
Optional parser object to be used instead of the default CParser
When successful, an AST is returned. ParseError can be
thrown if the file doesn't parse successfully.
Errors from cpp will be printed out.
"""
if use_cpp:
text = preprocess_file(filename, cpp_path, cpp_args)
else:
with io.open(filename) as f:
text = f.read()
if parser is None:
parser = CParser()
return parser.parse(text, filename)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/__init__.py | Python | apache-2.0 | 2,815 |
#-----------------------------------------------------------------
# _ast_gen.py
#
# Generates the AST Node classes from a specification given in
# a configuration file
#
# The design of this module was inspired by astgen.py from the
# Python 2.5 code-base.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
import pprint
from string import Template
class ASTCodeGenerator(object):
def __init__(self, cfg_filename='_c_ast.cfg'):
""" Initialize the code generator from a configuration
file.
"""
self.cfg_filename = cfg_filename
self.node_cfg = [NodeCfg(name, contents)
for (name, contents) in self.parse_cfgfile(cfg_filename)]
def generate(self, file=None):
""" Generates the code into file, an open file buffer.
"""
src = Template(_PROLOGUE_COMMENT).substitute(
cfg_filename=self.cfg_filename)
src += _PROLOGUE_CODE
for node_cfg in self.node_cfg:
src += node_cfg.generate_source() + '\n\n'
file.write(src)
def parse_cfgfile(self, filename):
""" Parse the configuration file and yield pairs of
(name, contents) for each node.
"""
with open(filename, "r") as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
colon_i = line.find(':')
lbracket_i = line.find('[')
rbracket_i = line.find(']')
if colon_i < 1 or lbracket_i <= colon_i or rbracket_i <= lbracket_i:
raise RuntimeError("Invalid line in %s:\n%s\n" % (filename, line))
name = line[:colon_i]
val = line[lbracket_i + 1:rbracket_i]
vallist = [v.strip() for v in val.split(',')] if val else []
yield name, vallist
class NodeCfg(object):
""" Node configuration.
name: node name
contents: a list of contents - attributes and child nodes
See comment at the top of the configuration file for details.
"""
def __init__(self, name, contents):
self.name = name
self.all_entries = []
self.attr = []
self.child = []
self.seq_child = []
for entry in contents:
clean_entry = entry.rstrip('*')
self.all_entries.append(clean_entry)
if entry.endswith('**'):
self.seq_child.append(clean_entry)
elif entry.endswith('*'):
self.child.append(clean_entry)
else:
self.attr.append(entry)
def generate_source(self):
src = self._gen_init()
src += '\n' + self._gen_children()
src += '\n' + self._gen_iter()
src += '\n' + self._gen_attr_names()
return src
def _gen_init(self):
src = "class %s(Node):\n" % self.name
if self.all_entries:
args = ', '.join(self.all_entries)
slots = ', '.join("'{0}'".format(e) for e in self.all_entries)
slots += ", 'coord', '__weakref__'"
arglist = '(self, %s, coord=None)' % args
else:
slots = "'coord', '__weakref__'"
arglist = '(self, coord=None)'
src += " __slots__ = (%s)\n" % slots
src += " def __init__%s:\n" % arglist
for name in self.all_entries + ['coord']:
src += " self.%s = %s\n" % (name, name)
return src
def _gen_children(self):
src = ' def children(self):\n'
if self.all_entries:
src += ' nodelist = []\n'
for child in self.child:
src += (
' if self.%(child)s is not None:' +
' nodelist.append(("%(child)s", self.%(child)s))\n') % (
dict(child=child))
for seq_child in self.seq_child:
src += (
' for i, child in enumerate(self.%(child)s or []):\n'
' nodelist.append(("%(child)s[%%d]" %% i, child))\n') % (
dict(child=seq_child))
src += ' return tuple(nodelist)\n'
else:
src += ' return ()\n'
return src
def _gen_iter(self):
src = ' def __iter__(self):\n'
if self.all_entries:
for child in self.child:
src += (
' if self.%(child)s is not None:\n' +
' yield self.%(child)s\n') % (dict(child=child))
for seq_child in self.seq_child:
src += (
' for child in (self.%(child)s or []):\n'
' yield child\n') % (dict(child=seq_child))
if not (self.child or self.seq_child):
# Empty generator
src += (
' return\n' +
' yield\n')
else:
# Empty generator
src += (
' return\n' +
' yield\n')
return src
def _gen_attr_names(self):
src = " attr_names = (" + ''.join("%r, " % nm for nm in self.attr) + ')'
return src
_PROLOGUE_COMMENT = \
r'''#-----------------------------------------------------------------
# ** ATTENTION **
# This code was automatically generated from the file:
# $cfg_filename
#
# Do not modify it directly. Modify the configuration file and
# run the generator again.
# ** ** *** ** **
#
# pycparser: c_ast.py
#
# AST Node classes.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
'''
_PROLOGUE_CODE = r'''
import sys
def _repr(obj):
"""
Get the representation of an object, with dedicated pprint-like format for lists.
"""
if isinstance(obj, list):
return '[' + (',\n '.join((_repr(e).replace('\n', '\n ') for e in obj))) + '\n]'
else:
return repr(obj)
class Node(object):
__slots__ = ()
""" Abstract base class for AST nodes.
"""
def __repr__(self):
""" Generates a python representation of the current node
"""
result = self.__class__.__name__ + '('
indent = ''
separator = ''
for name in self.__slots__[:-2]:
result += separator
result += indent
result += name + '=' + (_repr(getattr(self, name)).replace('\n', '\n ' + (' ' * (len(name) + len(self.__class__.__name__)))))
separator = ','
indent = '\n ' + (' ' * len(self.__class__.__name__))
result += indent + ')'
return result
def children(self):
""" A sequence of all children that are Nodes
"""
pass
def show(self, buf=sys.stdout, offset=0, attrnames=False, nodenames=False, showcoord=False, _my_node_name=None):
""" Pretty print the Node and all its attributes and
children (recursively) to a buffer.
buf:
Open IO buffer into which the Node is printed.
offset:
Initial offset (amount of leading spaces)
attrnames:
True if you want to see the attribute names in
name=value pairs. False to only see the values.
nodenames:
True if you want to see the actual node names
within their parents.
showcoord:
Do you want the coordinates of each Node to be
displayed.
"""
lead = ' ' * offset
if nodenames and _my_node_name is not None:
buf.write(lead + self.__class__.__name__+ ' <' + _my_node_name + '>: ')
else:
buf.write(lead + self.__class__.__name__+ ': ')
if self.attr_names:
if attrnames:
nvlist = [(n, getattr(self,n)) for n in self.attr_names]
attrstr = ', '.join('%s=%s' % nv for nv in nvlist)
else:
vlist = [getattr(self, n) for n in self.attr_names]
attrstr = ', '.join('%s' % v for v in vlist)
buf.write(attrstr)
if showcoord:
buf.write(' (at %s)' % self.coord)
buf.write('\n')
for (child_name, child) in self.children():
child.show(
buf,
offset=offset + 2,
attrnames=attrnames,
nodenames=nodenames,
showcoord=showcoord,
_my_node_name=child_name)
class NodeVisitor(object):
""" A base NodeVisitor class for visiting c_ast nodes.
Subclass it and define your own visit_XXX methods, where
XXX is the class name you want to visit with these
methods.
For example:
class ConstantVisitor(NodeVisitor):
def __init__(self):
self.values = []
def visit_Constant(self, node):
self.values.append(node.value)
Creates a list of values of all the constant nodes
encountered below the given node. To use it:
cv = ConstantVisitor()
cv.visit(node)
Notes:
* generic_visit() will be called for AST nodes for which
no visit_XXX method was defined.
* The children of nodes for which a visit_XXX was
defined will not be visited - if you need this, call
generic_visit() on the node.
You can use:
NodeVisitor.generic_visit(self, node)
* Modeled after Python's own AST visiting facilities
(the ast module of Python 3.0)
"""
_method_cache = None
def visit(self, node):
""" Visit a node.
"""
if self._method_cache is None:
self._method_cache = {}
visitor = self._method_cache.get(node.__class__.__name__, None)
if visitor is None:
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
self._method_cache[node.__class__.__name__] = visitor
return visitor(node)
def generic_visit(self, node):
""" Called if no explicit visitor function exists for a
node. Implements preorder visiting of the node.
"""
for c in node:
self.visit(c)
'''
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/_ast_gen.py | Python | apache-2.0 | 10,570 |
#-----------------------------------------------------------------
# pycparser: _build_tables.py
#
# A dummy for generating the lexing/parsing tables and and
# compiling them into .pyc for faster execution in optimized mode.
# Also generates AST code from the configuration file.
# Should be called from the pycparser directory.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
# Insert '.' and '..' as first entries to the search path for modules.
# Restricted environments like embeddable python do not include the
# current working directory on startup.
import sys
sys.path[0:0] = ['.', '..']
# Generate c_ast.py
from _ast_gen import ASTCodeGenerator
ast_gen = ASTCodeGenerator('_c_ast.cfg')
ast_gen.generate(open('c_ast.py', 'w'))
from pycparser import c_parser
# Generates the tables
#
c_parser.CParser(
lex_optimize=True,
yacc_debug=False,
yacc_optimize=True)
# Load to compile into .pyc
#
import lextab
import yacctab
import c_ast
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/_build_tables.py | Python | apache-2.0 | 1,039 |
#------------------------------------------------------------------------------
# pycparser: ast_transforms.py
#
# Some utilities used by the parser to create a friendlier AST.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#------------------------------------------------------------------------------
from . import c_ast
def fix_switch_cases(switch_node):
""" The 'case' statements in a 'switch' come out of parsing with one
child node, so subsequent statements are just tucked to the parent
Compound. Additionally, consecutive (fall-through) case statements
come out messy. This is a peculiarity of the C grammar. The following:
switch (myvar) {
case 10:
k = 10;
p = k + 1;
return 10;
case 20:
case 30:
return 20;
default:
break;
}
Creates this tree (pseudo-dump):
Switch
ID: myvar
Compound:
Case 10:
k = 10
p = k + 1
return 10
Case 20:
Case 30:
return 20
Default:
break
The goal of this transform is to fix this mess, turning it into the
following:
Switch
ID: myvar
Compound:
Case 10:
k = 10
p = k + 1
return 10
Case 20:
Case 30:
return 20
Default:
break
A fixed AST node is returned. The argument may be modified.
"""
assert isinstance(switch_node, c_ast.Switch)
if not isinstance(switch_node.stmt, c_ast.Compound):
return switch_node
# The new Compound child for the Switch, which will collect children in the
# correct order
new_compound = c_ast.Compound([], switch_node.stmt.coord)
# The last Case/Default node
last_case = None
# Goes over the children of the Compound below the Switch, adding them
# either directly below new_compound or below the last Case as appropriate
# (for `switch(cond) {}`, block_items would have been None)
for child in (switch_node.stmt.block_items or []):
if isinstance(child, (c_ast.Case, c_ast.Default)):
# If it's a Case/Default:
# 1. Add it to the Compound and mark as "last case"
# 2. If its immediate child is also a Case or Default, promote it
# to a sibling.
new_compound.block_items.append(child)
_extract_nested_case(child, new_compound.block_items)
last_case = new_compound.block_items[-1]
else:
# Other statements are added as children to the last case, if it
# exists.
if last_case is None:
new_compound.block_items.append(child)
else:
last_case.stmts.append(child)
switch_node.stmt = new_compound
return switch_node
def _extract_nested_case(case_node, stmts_list):
""" Recursively extract consecutive Case statements that are made nested
by the parser and add them to the stmts_list.
"""
if isinstance(case_node.stmts[0], (c_ast.Case, c_ast.Default)):
stmts_list.append(case_node.stmts.pop())
_extract_nested_case(stmts_list[-1], stmts_list)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/ast_transforms.py | Python | apache-2.0 | 3,648 |
#------------------------------------------------------------------------------
# pycparser: c_generator.py
#
# C code generator from pycparser AST nodes.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#------------------------------------------------------------------------------
from . import c_ast
class CGenerator(object):
""" Uses the same visitor pattern as c_ast.NodeVisitor, but modified to
return a value from each visit method, using string accumulation in
generic_visit.
"""
def __init__(self, reduce_parentheses=False):
""" Constructs C-code generator
reduce_parentheses:
if True, eliminates needless parentheses on binary operators
"""
# Statements start with indentation of self.indent_level spaces, using
# the _make_indent method.
self.indent_level = 0
self.reduce_parentheses = reduce_parentheses
def _make_indent(self):
return ' ' * self.indent_level
def visit(self, node):
method = 'visit_' + node.__class__.__name__
return getattr(self, method, self.generic_visit)(node)
def generic_visit(self, node):
if node is None:
return ''
else:
return ''.join(self.visit(c) for c_name, c in node.children())
def visit_Constant(self, n):
return n.value
def visit_ID(self, n):
return n.name
def visit_Pragma(self, n):
ret = '#pragma'
if n.string:
ret += ' ' + n.string
return ret
def visit_ArrayRef(self, n):
arrref = self._parenthesize_unless_simple(n.name)
return arrref + '[' + self.visit(n.subscript) + ']'
def visit_StructRef(self, n):
sref = self._parenthesize_unless_simple(n.name)
return sref + n.type + self.visit(n.field)
def visit_FuncCall(self, n):
fref = self._parenthesize_unless_simple(n.name)
return fref + '(' + self.visit(n.args) + ')'
def visit_UnaryOp(self, n):
if n.op == 'sizeof':
# Always parenthesize the argument of sizeof since it can be
# a name.
return 'sizeof(%s)' % self.visit(n.expr)
else:
operand = self._parenthesize_unless_simple(n.expr)
if n.op == 'p++':
return '%s++' % operand
elif n.op == 'p--':
return '%s--' % operand
else:
return '%s%s' % (n.op, operand)
# Precedence map of binary operators:
precedence_map = {
# Should be in sync with c_parser.CParser.precedence
# Higher numbers are stronger binding
'||': 0, # weakest binding
'&&': 1,
'|': 2,
'^': 3,
'&': 4,
'==': 5, '!=': 5,
'>': 6, '>=': 6, '<': 6, '<=': 6,
'>>': 7, '<<': 7,
'+': 8, '-': 8,
'*': 9, '/': 9, '%': 9 # strongest binding
}
def visit_BinaryOp(self, n):
# Note: all binary operators are left-to-right associative
#
# If `n.left.op` has a stronger or equally binding precedence in
# comparison to `n.op`, no parenthesis are needed for the left:
# e.g., `(a*b) + c` is equivelent to `a*b + c`, as well as
# `(a+b) - c` is equivelent to `a+b - c` (same precedence).
# If the left operator is weaker binding than the current, then
# parentheses are necessary:
# e.g., `(a+b) * c` is NOT equivelent to `a+b * c`.
lval_str = self._parenthesize_if(
n.left,
lambda d: not (self._is_simple_node(d) or
self.reduce_parentheses and isinstance(d, c_ast.BinaryOp) and
self.precedence_map[d.op] >= self.precedence_map[n.op]))
# If `n.right.op` has a stronger -but not equal- binding precedence,
# parenthesis can be omitted on the right:
# e.g., `a + (b*c)` is equivelent to `a + b*c`.
# If the right operator is weaker or equally binding, then parentheses
# are necessary:
# e.g., `a * (b+c)` is NOT equivelent to `a * b+c` and
# `a - (b+c)` is NOT equivelent to `a - b+c` (same precedence).
rval_str = self._parenthesize_if(
n.right,
lambda d: not (self._is_simple_node(d) or
self.reduce_parentheses and isinstance(d, c_ast.BinaryOp) and
self.precedence_map[d.op] > self.precedence_map[n.op]))
return '%s %s %s' % (lval_str, n.op, rval_str)
def visit_Assignment(self, n):
rval_str = self._parenthesize_if(
n.rvalue,
lambda n: isinstance(n, c_ast.Assignment))
return '%s %s %s' % (self.visit(n.lvalue), n.op, rval_str)
def visit_IdentifierType(self, n):
return ' '.join(n.names)
def _visit_expr(self, n):
if isinstance(n, c_ast.InitList):
return '{' + self.visit(n) + '}'
elif isinstance(n, c_ast.ExprList):
return '(' + self.visit(n) + ')'
else:
return self.visit(n)
def visit_Decl(self, n, no_type=False):
# no_type is used when a Decl is part of a DeclList, where the type is
# explicitly only for the first declaration in a list.
#
s = n.name if no_type else self._generate_decl(n)
if n.bitsize: s += ' : ' + self.visit(n.bitsize)
if n.init:
s += ' = ' + self._visit_expr(n.init)
return s
def visit_DeclList(self, n):
s = self.visit(n.decls[0])
if len(n.decls) > 1:
s += ', ' + ', '.join(self.visit_Decl(decl, no_type=True)
for decl in n.decls[1:])
return s
def visit_Typedef(self, n):
s = ''
if n.storage: s += ' '.join(n.storage) + ' '
s += self._generate_type(n.type)
return s
def visit_Cast(self, n):
s = '(' + self._generate_type(n.to_type, emit_declname=False) + ')'
return s + ' ' + self._parenthesize_unless_simple(n.expr)
def visit_ExprList(self, n):
visited_subexprs = []
for expr in n.exprs:
visited_subexprs.append(self._visit_expr(expr))
return ', '.join(visited_subexprs)
def visit_InitList(self, n):
visited_subexprs = []
for expr in n.exprs:
visited_subexprs.append(self._visit_expr(expr))
return ', '.join(visited_subexprs)
def visit_Enum(self, n):
return self._generate_struct_union_enum(n, name='enum')
def visit_Enumerator(self, n):
if not n.value:
return '{indent}{name},\n'.format(
indent=self._make_indent(),
name=n.name,
)
else:
return '{indent}{name} = {value},\n'.format(
indent=self._make_indent(),
name=n.name,
value=self.visit(n.value),
)
def visit_FuncDef(self, n):
decl = self.visit(n.decl)
self.indent_level = 0
body = self.visit(n.body)
if n.param_decls:
knrdecls = ';\n'.join(self.visit(p) for p in n.param_decls)
return decl + '\n' + knrdecls + ';\n' + body + '\n'
else:
return decl + '\n' + body + '\n'
def visit_FileAST(self, n):
s = ''
for ext in n.ext:
if isinstance(ext, c_ast.FuncDef):
s += self.visit(ext)
elif isinstance(ext, c_ast.Pragma):
s += self.visit(ext) + '\n'
else:
s += self.visit(ext) + ';\n'
return s
def visit_Compound(self, n):
s = self._make_indent() + '{\n'
self.indent_level += 2
if n.block_items:
s += ''.join(self._generate_stmt(stmt) for stmt in n.block_items)
self.indent_level -= 2
s += self._make_indent() + '}\n'
return s
def visit_CompoundLiteral(self, n):
return '(' + self.visit(n.type) + '){' + self.visit(n.init) + '}'
def visit_EmptyStatement(self, n):
return ';'
def visit_ParamList(self, n):
return ', '.join(self.visit(param) for param in n.params)
def visit_Return(self, n):
s = 'return'
if n.expr: s += ' ' + self.visit(n.expr)
return s + ';'
def visit_Break(self, n):
return 'break;'
def visit_Continue(self, n):
return 'continue;'
def visit_TernaryOp(self, n):
s = '(' + self._visit_expr(n.cond) + ') ? '
s += '(' + self._visit_expr(n.iftrue) + ') : '
s += '(' + self._visit_expr(n.iffalse) + ')'
return s
def visit_If(self, n):
s = 'if ('
if n.cond: s += self.visit(n.cond)
s += ')\n'
s += self._generate_stmt(n.iftrue, add_indent=True)
if n.iffalse:
s += self._make_indent() + 'else\n'
s += self._generate_stmt(n.iffalse, add_indent=True)
return s
def visit_For(self, n):
s = 'for ('
if n.init: s += self.visit(n.init)
s += ';'
if n.cond: s += ' ' + self.visit(n.cond)
s += ';'
if n.next: s += ' ' + self.visit(n.next)
s += ')\n'
s += self._generate_stmt(n.stmt, add_indent=True)
return s
def visit_While(self, n):
s = 'while ('
if n.cond: s += self.visit(n.cond)
s += ')\n'
s += self._generate_stmt(n.stmt, add_indent=True)
return s
def visit_DoWhile(self, n):
s = 'do\n'
s += self._generate_stmt(n.stmt, add_indent=True)
s += self._make_indent() + 'while ('
if n.cond: s += self.visit(n.cond)
s += ');'
return s
def visit_Switch(self, n):
s = 'switch (' + self.visit(n.cond) + ')\n'
s += self._generate_stmt(n.stmt, add_indent=True)
return s
def visit_Case(self, n):
s = 'case ' + self.visit(n.expr) + ':\n'
for stmt in n.stmts:
s += self._generate_stmt(stmt, add_indent=True)
return s
def visit_Default(self, n):
s = 'default:\n'
for stmt in n.stmts:
s += self._generate_stmt(stmt, add_indent=True)
return s
def visit_Label(self, n):
return n.name + ':\n' + self._generate_stmt(n.stmt)
def visit_Goto(self, n):
return 'goto ' + n.name + ';'
def visit_EllipsisParam(self, n):
return '...'
def visit_Struct(self, n):
return self._generate_struct_union_enum(n, 'struct')
def visit_Typename(self, n):
return self._generate_type(n.type)
def visit_Union(self, n):
return self._generate_struct_union_enum(n, 'union')
def visit_NamedInitializer(self, n):
s = ''
for name in n.name:
if isinstance(name, c_ast.ID):
s += '.' + name.name
else:
s += '[' + self.visit(name) + ']'
s += ' = ' + self._visit_expr(n.expr)
return s
def visit_FuncDecl(self, n):
return self._generate_type(n)
def visit_ArrayDecl(self, n):
return self._generate_type(n, emit_declname=False)
def visit_TypeDecl(self, n):
return self._generate_type(n, emit_declname=False)
def visit_PtrDecl(self, n):
return self._generate_type(n, emit_declname=False)
def _generate_struct_union_enum(self, n, name):
""" Generates code for structs, unions, and enums. name should be
'struct', 'union', or 'enum'.
"""
if name in ('struct', 'union'):
members = n.decls
body_function = self._generate_struct_union_body
else:
assert name == 'enum'
members = None if n.values is None else n.values.enumerators
body_function = self._generate_enum_body
s = name + ' ' + (n.name or '')
if members is not None:
# None means no members
# Empty sequence means an empty list of members
s += '\n'
s += self._make_indent()
self.indent_level += 2
s += '{\n'
s += body_function(members)
self.indent_level -= 2
s += self._make_indent() + '}'
return s
def _generate_struct_union_body(self, members):
return ''.join(self._generate_stmt(decl) for decl in members)
def _generate_enum_body(self, members):
# `[:-2] + '\n'` removes the final `,` from the enumerator list
return ''.join(self.visit(value) for value in members)[:-2] + '\n'
def _generate_stmt(self, n, add_indent=False):
""" Generation from a statement node. This method exists as a wrapper
for individual visit_* methods to handle different treatment of
some statements in this context.
"""
typ = type(n)
if add_indent: self.indent_level += 2
indent = self._make_indent()
if add_indent: self.indent_level -= 2
if typ in (
c_ast.Decl, c_ast.Assignment, c_ast.Cast, c_ast.UnaryOp,
c_ast.BinaryOp, c_ast.TernaryOp, c_ast.FuncCall, c_ast.ArrayRef,
c_ast.StructRef, c_ast.Constant, c_ast.ID, c_ast.Typedef,
c_ast.ExprList):
# These can also appear in an expression context so no semicolon
# is added to them automatically
#
return indent + self.visit(n) + ';\n'
elif typ in (c_ast.Compound,):
# No extra indentation required before the opening brace of a
# compound - because it consists of multiple lines it has to
# compute its own indentation.
#
return self.visit(n)
elif typ in (c_ast.If,):
return indent + self.visit(n)
else:
return indent + self.visit(n) + '\n'
def _generate_decl(self, n):
""" Generation from a Decl node.
"""
s = ''
if n.funcspec: s = ' '.join(n.funcspec) + ' '
if n.storage: s += ' '.join(n.storage) + ' '
s += self._generate_type(n.type)
return s
def _generate_type(self, n, modifiers=[], emit_declname = True):
""" Recursive generation from a type node. n is the type node.
modifiers collects the PtrDecl, ArrayDecl and FuncDecl modifiers
encountered on the way down to a TypeDecl, to allow proper
generation from it.
"""
typ = type(n)
#~ print(n, modifiers)
if typ == c_ast.TypeDecl:
s = ''
if n.quals: s += ' '.join(n.quals) + ' '
s += self.visit(n.type)
nstr = n.declname if n.declname and emit_declname else ''
# Resolve modifiers.
# Wrap in parens to distinguish pointer to array and pointer to
# function syntax.
#
for i, modifier in enumerate(modifiers):
if isinstance(modifier, c_ast.ArrayDecl):
if (i != 0 and
isinstance(modifiers[i - 1], c_ast.PtrDecl)):
nstr = '(' + nstr + ')'
nstr += '['
if modifier.dim_quals:
nstr += ' '.join(modifier.dim_quals) + ' '
nstr += self.visit(modifier.dim) + ']'
elif isinstance(modifier, c_ast.FuncDecl):
if (i != 0 and
isinstance(modifiers[i - 1], c_ast.PtrDecl)):
nstr = '(' + nstr + ')'
nstr += '(' + self.visit(modifier.args) + ')'
elif isinstance(modifier, c_ast.PtrDecl):
if modifier.quals:
nstr = '* %s%s' % (' '.join(modifier.quals),
' ' + nstr if nstr else '')
else:
nstr = '*' + nstr
if nstr: s += ' ' + nstr
return s
elif typ == c_ast.Decl:
return self._generate_decl(n.type)
elif typ == c_ast.Typename:
return self._generate_type(n.type, emit_declname = emit_declname)
elif typ == c_ast.IdentifierType:
return ' '.join(n.names) + ' '
elif typ in (c_ast.ArrayDecl, c_ast.PtrDecl, c_ast.FuncDecl):
return self._generate_type(n.type, modifiers + [n],
emit_declname = emit_declname)
else:
return self.visit(n)
def _parenthesize_if(self, n, condition):
""" Visits 'n' and returns its string representation, parenthesized
if the condition function applied to the node returns True.
"""
s = self._visit_expr(n)
if condition(n):
return '(' + s + ')'
else:
return s
def _parenthesize_unless_simple(self, n):
""" Common use case for _parenthesize_if
"""
return self._parenthesize_if(n, lambda d: not self._is_simple_node(d))
def _is_simple_node(self, n):
""" Returns True for nodes that are "simple" - i.e. nodes that always
have higher precedence than operators.
"""
return isinstance(n, (c_ast.Constant, c_ast.ID, c_ast.ArrayRef,
c_ast.StructRef, c_ast.FuncCall))
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/c_generator.py | Python | apache-2.0 | 17,407 |
#------------------------------------------------------------------------------
# pycparser: c_lexer.py
#
# CLexer class: lexer for the C language
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#------------------------------------------------------------------------------
import re
import sys
from .ply import lex
from .ply.lex import TOKEN
class CLexer(object):
""" A lexer for the C language. After building it, set the
input text with input(), and call token() to get new
tokens.
The public attribute filename can be set to an initial
filename, but the lexer will update it upon #line
directives.
"""
def __init__(self, error_func, on_lbrace_func, on_rbrace_func,
type_lookup_func):
""" Create a new Lexer.
error_func:
An error function. Will be called with an error
message, line and column as arguments, in case of
an error during lexing.
on_lbrace_func, on_rbrace_func:
Called when an LBRACE or RBRACE is encountered
(likely to push/pop type_lookup_func's scope)
type_lookup_func:
A type lookup function. Given a string, it must
return True IFF this string is a name of a type
that was defined with a typedef earlier.
"""
self.error_func = error_func
self.on_lbrace_func = on_lbrace_func
self.on_rbrace_func = on_rbrace_func
self.type_lookup_func = type_lookup_func
self.filename = ''
# Keeps track of the last token returned from self.token()
self.last_token = None
# Allow either "# line" or "# <num>" to support GCC's
# cpp output
#
self.line_pattern = re.compile(r'([ \t]*line\W)|([ \t]*\d+)')
self.pragma_pattern = re.compile(r'[ \t]*pragma\W')
def build(self, **kwargs):
""" Builds the lexer from the specification. Must be
called after the lexer object is created.
This method exists separately, because the PLY
manual warns against calling lex.lex inside
__init__
"""
self.lexer = lex.lex(object=self, **kwargs)
def reset_lineno(self):
""" Resets the internal line number counter of the lexer.
"""
self.lexer.lineno = 1
def input(self, text):
self.lexer.input(text)
def token(self):
self.last_token = self.lexer.token()
return self.last_token
def find_tok_column(self, token):
""" Find the column of the token in its line.
"""
last_cr = self.lexer.lexdata.rfind('\n', 0, token.lexpos)
return token.lexpos - last_cr
######################-- PRIVATE --######################
##
## Internal auxiliary methods
##
def _error(self, msg, token):
location = self._make_tok_location(token)
self.error_func(msg, location[0], location[1])
self.lexer.skip(1)
def _make_tok_location(self, token):
return (token.lineno, self.find_tok_column(token))
##
## Reserved keywords
##
keywords = (
'_BOOL', '_COMPLEX', 'AUTO', 'BREAK', 'CASE', 'CHAR', 'CONST',
'CONTINUE', 'DEFAULT', 'DO', 'DOUBLE', 'ELSE', 'ENUM', 'EXTERN',
'FLOAT', 'FOR', 'GOTO', 'IF', 'INLINE', 'INT', 'LONG',
'REGISTER', 'OFFSETOF',
'RESTRICT', 'RETURN', 'SHORT', 'SIGNED', 'SIZEOF', 'STATIC', 'STRUCT',
'SWITCH', 'TYPEDEF', 'UNION', 'UNSIGNED', 'VOID',
'VOLATILE', 'WHILE', '__INT128',
)
keyword_map = {}
for keyword in keywords:
if keyword == '_BOOL':
keyword_map['_Bool'] = keyword
elif keyword == '_COMPLEX':
keyword_map['_Complex'] = keyword
else:
keyword_map[keyword.lower()] = keyword
##
## All the tokens recognized by the lexer
##
tokens = keywords + (
# Identifiers
'ID',
# Type identifiers (identifiers previously defined as
# types with typedef)
'TYPEID',
# constants
'INT_CONST_DEC', 'INT_CONST_OCT', 'INT_CONST_HEX', 'INT_CONST_BIN', 'INT_CONST_CHAR',
'FLOAT_CONST', 'HEX_FLOAT_CONST',
'CHAR_CONST',
'WCHAR_CONST',
# String literals
'STRING_LITERAL',
'WSTRING_LITERAL',
# Operators
'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MOD',
'OR', 'AND', 'NOT', 'XOR', 'LSHIFT', 'RSHIFT',
'LOR', 'LAND', 'LNOT',
'LT', 'LE', 'GT', 'GE', 'EQ', 'NE',
# Assignment
'EQUALS', 'TIMESEQUAL', 'DIVEQUAL', 'MODEQUAL',
'PLUSEQUAL', 'MINUSEQUAL',
'LSHIFTEQUAL','RSHIFTEQUAL', 'ANDEQUAL', 'XOREQUAL',
'OREQUAL',
# Increment/decrement
'PLUSPLUS', 'MINUSMINUS',
# Structure dereference (->)
'ARROW',
# Conditional operator (?)
'CONDOP',
# Delimeters
'LPAREN', 'RPAREN', # ( )
'LBRACKET', 'RBRACKET', # [ ]
'LBRACE', 'RBRACE', # { }
'COMMA', 'PERIOD', # . ,
'SEMI', 'COLON', # ; :
# Ellipsis (...)
'ELLIPSIS',
# pre-processor
'PPHASH', # '#'
'PPPRAGMA', # 'pragma'
'PPPRAGMASTR',
)
##
## Regexes for use in tokens
##
##
# valid C identifiers (K&R2: A.2.3), plus '$' (supported by some compilers)
identifier = r'[a-zA-Z_$][0-9a-zA-Z_$]*'
hex_prefix = '0[xX]'
hex_digits = '[0-9a-fA-F]+'
bin_prefix = '0[bB]'
bin_digits = '[01]+'
# integer constants (K&R2: A.2.5.1)
integer_suffix_opt = r'(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?'
decimal_constant = '(0'+integer_suffix_opt+')|([1-9][0-9]*'+integer_suffix_opt+')'
octal_constant = '0[0-7]*'+integer_suffix_opt
hex_constant = hex_prefix+hex_digits+integer_suffix_opt
bin_constant = bin_prefix+bin_digits+integer_suffix_opt
bad_octal_constant = '0[0-7]*[89]'
# character constants (K&R2: A.2.5.2)
# Note: a-zA-Z and '.-~^_!=&;,' are allowed as escape chars to support #line
# directives with Windows paths as filenames (..\..\dir\file)
# For the same reason, decimal_escape allows all digit sequences. We want to
# parse all correct code, even if it means to sometimes parse incorrect
# code.
#
# The original regexes were taken verbatim from the C syntax definition,
# and were later modified to avoid worst-case exponential running time.
#
# simple_escape = r"""([a-zA-Z._~!=&\^\-\\?'"])"""
# decimal_escape = r"""(\d+)"""
# hex_escape = r"""(x[0-9a-fA-F]+)"""
# bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-7])"""
#
# The following modifications were made to avoid the ambiguity that allowed backtracking:
# (https://github.com/eliben/pycparser/issues/61)
#
# - \x was removed from simple_escape, unless it was not followed by a hex digit, to avoid ambiguity with hex_escape.
# - hex_escape allows one or more hex characters, but requires that the next character(if any) is not hex
# - decimal_escape allows one or more decimal characters, but requires that the next character(if any) is not a decimal
# - bad_escape does not allow any decimals (8-9), to avoid conflicting with the permissive decimal_escape.
#
# Without this change, python's `re` module would recursively try parsing each ambiguous escape sequence in multiple ways.
# e.g. `\123` could be parsed as `\1`+`23`, `\12`+`3`, and `\123`.
simple_escape = r"""([a-wyzA-Z._~!=&\^\-\\?'"]|x(?![0-9a-fA-F]))"""
decimal_escape = r"""(\d+)(?!\d)"""
hex_escape = r"""(x[0-9a-fA-F]+)(?![0-9a-fA-F])"""
bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-9])"""
escape_sequence = r"""(\\("""+simple_escape+'|'+decimal_escape+'|'+hex_escape+'))'
# This complicated regex with lookahead might be slow for strings, so because all of the valid escapes (including \x) allowed
# 0 or more non-escaped characters after the first character, simple_escape+decimal_escape+hex_escape got simplified to
escape_sequence_start_in_string = r"""(\\[0-9a-zA-Z._~!=&\^\-\\?'"])"""
cconst_char = r"""([^'\\\n]|"""+escape_sequence+')'
char_const = "'"+cconst_char+"'"
wchar_const = 'L'+char_const
multicharacter_constant = "'"+cconst_char+"{2,4}'"
unmatched_quote = "('"+cconst_char+"*\\n)|('"+cconst_char+"*$)"
bad_char_const = r"""('"""+cconst_char+"""[^'\n]+')|('')|('"""+bad_escape+r"""[^'\n]*')"""
# string literals (K&R2: A.2.6)
string_char = r"""([^"\\\n]|"""+escape_sequence_start_in_string+')'
string_literal = '"'+string_char+'*"'
wstring_literal = 'L'+string_literal
bad_string_literal = '"'+string_char+'*'+bad_escape+string_char+'*"'
# floating constants (K&R2: A.2.5.3)
exponent_part = r"""([eE][-+]?[0-9]+)"""
fractional_constant = r"""([0-9]*\.[0-9]+)|([0-9]+\.)"""
floating_constant = '(((('+fractional_constant+')'+exponent_part+'?)|([0-9]+'+exponent_part+'))[FfLl]?)'
binary_exponent_part = r'''([pP][+-]?[0-9]+)'''
hex_fractional_constant = '((('+hex_digits+r""")?\."""+hex_digits+')|('+hex_digits+r"""\.))"""
hex_floating_constant = '('+hex_prefix+'('+hex_digits+'|'+hex_fractional_constant+')'+binary_exponent_part+'[FfLl]?)'
##
## Lexer states: used for preprocessor \n-terminated directives
##
states = (
# ppline: preprocessor line directives
#
('ppline', 'exclusive'),
# pppragma: pragma
#
('pppragma', 'exclusive'),
)
def t_PPHASH(self, t):
r'[ \t]*\#'
if self.line_pattern.match(t.lexer.lexdata, pos=t.lexer.lexpos):
t.lexer.begin('ppline')
self.pp_line = self.pp_filename = None
elif self.pragma_pattern.match(t.lexer.lexdata, pos=t.lexer.lexpos):
t.lexer.begin('pppragma')
else:
t.type = 'PPHASH'
return t
##
## Rules for the ppline state
##
@TOKEN(string_literal)
def t_ppline_FILENAME(self, t):
if self.pp_line is None:
self._error('filename before line number in #line', t)
else:
self.pp_filename = t.value.lstrip('"').rstrip('"')
@TOKEN(decimal_constant)
def t_ppline_LINE_NUMBER(self, t):
if self.pp_line is None:
self.pp_line = t.value
else:
# Ignore: GCC's cpp sometimes inserts a numeric flag
# after the file name
pass
def t_ppline_NEWLINE(self, t):
r'\n'
if self.pp_line is None:
self._error('line number missing in #line', t)
else:
self.lexer.lineno = int(self.pp_line)
if self.pp_filename is not None:
self.filename = self.pp_filename
t.lexer.begin('INITIAL')
def t_ppline_PPLINE(self, t):
r'line'
pass
t_ppline_ignore = ' \t'
def t_ppline_error(self, t):
self._error('invalid #line directive', t)
##
## Rules for the pppragma state
##
def t_pppragma_NEWLINE(self, t):
r'\n'
t.lexer.lineno += 1
t.lexer.begin('INITIAL')
def t_pppragma_PPPRAGMA(self, t):
r'pragma'
return t
t_pppragma_ignore = ' \t'
def t_pppragma_STR(self, t):
'.+'
t.type = 'PPPRAGMASTR'
return t
def t_pppragma_error(self, t):
self._error('invalid #pragma directive', t)
##
## Rules for the normal state
##
t_ignore = ' \t'
# Newlines
def t_NEWLINE(self, t):
r'\n+'
t.lexer.lineno += t.value.count("\n")
# Operators
t_PLUS = r'\+'
t_MINUS = r'-'
t_TIMES = r'\*'
t_DIVIDE = r'/'
t_MOD = r'%'
t_OR = r'\|'
t_AND = r'&'
t_NOT = r'~'
t_XOR = r'\^'
t_LSHIFT = r'<<'
t_RSHIFT = r'>>'
t_LOR = r'\|\|'
t_LAND = r'&&'
t_LNOT = r'!'
t_LT = r'<'
t_GT = r'>'
t_LE = r'<='
t_GE = r'>='
t_EQ = r'=='
t_NE = r'!='
# Assignment operators
t_EQUALS = r'='
t_TIMESEQUAL = r'\*='
t_DIVEQUAL = r'/='
t_MODEQUAL = r'%='
t_PLUSEQUAL = r'\+='
t_MINUSEQUAL = r'-='
t_LSHIFTEQUAL = r'<<='
t_RSHIFTEQUAL = r'>>='
t_ANDEQUAL = r'&='
t_OREQUAL = r'\|='
t_XOREQUAL = r'\^='
# Increment/decrement
t_PLUSPLUS = r'\+\+'
t_MINUSMINUS = r'--'
# ->
t_ARROW = r'->'
# ?
t_CONDOP = r'\?'
# Delimeters
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_LBRACKET = r'\['
t_RBRACKET = r'\]'
t_COMMA = r','
t_PERIOD = r'\.'
t_SEMI = r';'
t_COLON = r':'
t_ELLIPSIS = r'\.\.\.'
# Scope delimiters
# To see why on_lbrace_func is needed, consider:
# typedef char TT;
# void foo(int TT) { TT = 10; }
# TT x = 5;
# Outside the function, TT is a typedef, but inside (starting and ending
# with the braces) it's a parameter. The trouble begins with yacc's
# lookahead token. If we open a new scope in brace_open, then TT has
# already been read and incorrectly interpreted as TYPEID. So, we need
# to open and close scopes from within the lexer.
# Similar for the TT immediately outside the end of the function.
#
@TOKEN(r'\{')
def t_LBRACE(self, t):
self.on_lbrace_func()
return t
@TOKEN(r'\}')
def t_RBRACE(self, t):
self.on_rbrace_func()
return t
t_STRING_LITERAL = string_literal
# The following floating and integer constants are defined as
# functions to impose a strict order (otherwise, decimal
# is placed before the others because its regex is longer,
# and this is bad)
#
@TOKEN(floating_constant)
def t_FLOAT_CONST(self, t):
return t
@TOKEN(hex_floating_constant)
def t_HEX_FLOAT_CONST(self, t):
return t
@TOKEN(hex_constant)
def t_INT_CONST_HEX(self, t):
return t
@TOKEN(bin_constant)
def t_INT_CONST_BIN(self, t):
return t
@TOKEN(bad_octal_constant)
def t_BAD_CONST_OCT(self, t):
msg = "Invalid octal constant"
self._error(msg, t)
@TOKEN(octal_constant)
def t_INT_CONST_OCT(self, t):
return t
@TOKEN(decimal_constant)
def t_INT_CONST_DEC(self, t):
return t
# Must come before bad_char_const, to prevent it from
# catching valid char constants as invalid
#
@TOKEN(multicharacter_constant)
def t_INT_CONST_CHAR(self, t):
return t
@TOKEN(char_const)
def t_CHAR_CONST(self, t):
return t
@TOKEN(wchar_const)
def t_WCHAR_CONST(self, t):
return t
@TOKEN(unmatched_quote)
def t_UNMATCHED_QUOTE(self, t):
msg = "Unmatched '"
self._error(msg, t)
@TOKEN(bad_char_const)
def t_BAD_CHAR_CONST(self, t):
msg = "Invalid char constant %s" % t.value
self._error(msg, t)
@TOKEN(wstring_literal)
def t_WSTRING_LITERAL(self, t):
return t
# unmatched string literals are caught by the preprocessor
@TOKEN(bad_string_literal)
def t_BAD_STRING_LITERAL(self, t):
msg = "String contains invalid escape code"
self._error(msg, t)
@TOKEN(identifier)
def t_ID(self, t):
t.type = self.keyword_map.get(t.value, "ID")
if t.type == 'ID' and self.type_lookup_func(t.value):
t.type = "TYPEID"
return t
def t_error(self, t):
msg = 'Illegal character %s' % repr(t.value[0])
self._error(msg, t)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/c_lexer.py | Python | apache-2.0 | 16,208 |
#------------------------------------------------------------------------------
# pycparser: c_parser.py
#
# CParser class: Parser and AST builder for the C language
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#------------------------------------------------------------------------------
import re
from .ply import yacc
from . import c_ast
from .c_lexer import CLexer
from .plyparser import PLYParser, Coord, ParseError, parameterized, template
from .ast_transforms import fix_switch_cases
@template
class CParser(PLYParser):
def __init__(
self,
lex_optimize=True,
lexer=CLexer,
lextab='pycparser.lextab',
yacc_optimize=True,
yacctab='pycparser.yacctab',
yacc_debug=False,
taboutputdir=''):
""" Create a new CParser.
Some arguments for controlling the debug/optimization
level of the parser are provided. The defaults are
tuned for release/performance mode.
The simple rules for using them are:
*) When tweaking CParser/CLexer, set these to False
*) When releasing a stable parser, set to True
lex_optimize:
Set to False when you're modifying the lexer.
Otherwise, changes in the lexer won't be used, if
some lextab.py file exists.
When releasing with a stable lexer, set to True
to save the re-generation of the lexer table on
each run.
lexer:
Set this parameter to define the lexer to use if
you're not using the default CLexer.
lextab:
Points to the lex table that's used for optimized
mode. Only if you're modifying the lexer and want
some tests to avoid re-generating the table, make
this point to a local lex table file (that's been
earlier generated with lex_optimize=True)
yacc_optimize:
Set to False when you're modifying the parser.
Otherwise, changes in the parser won't be used, if
some parsetab.py file exists.
When releasing with a stable parser, set to True
to save the re-generation of the parser table on
each run.
yacctab:
Points to the yacc table that's used for optimized
mode. Only if you're modifying the parser, make
this point to a local yacc table file
yacc_debug:
Generate a parser.out file that explains how yacc
built the parsing table from the grammar.
taboutputdir:
Set this parameter to control the location of generated
lextab and yacctab files.
"""
self.clex = lexer(
error_func=self._lex_error_func,
on_lbrace_func=self._lex_on_lbrace_func,
on_rbrace_func=self._lex_on_rbrace_func,
type_lookup_func=self._lex_type_lookup_func)
self.clex.build(
optimize=lex_optimize,
lextab=lextab,
outputdir=taboutputdir)
self.tokens = self.clex.tokens
rules_with_opt = [
'abstract_declarator',
'assignment_expression',
'declaration_list',
'declaration_specifiers_no_type',
'designation',
'expression',
'identifier_list',
'init_declarator_list',
'id_init_declarator_list',
'initializer_list',
'parameter_type_list',
'block_item_list',
'type_qualifier_list',
'struct_declarator_list'
]
for rule in rules_with_opt:
self._create_opt_rule(rule)
self.cparser = yacc.yacc(
module=self,
start='translation_unit_or_empty',
debug=yacc_debug,
optimize=yacc_optimize,
tabmodule=yacctab,
outputdir=taboutputdir)
# Stack of scopes for keeping track of symbols. _scope_stack[-1] is
# the current (topmost) scope. Each scope is a dictionary that
# specifies whether a name is a type. If _scope_stack[n][name] is
# True, 'name' is currently a type in the scope. If it's False,
# 'name' is used in the scope but not as a type (for instance, if we
# saw: int name;
# If 'name' is not a key in _scope_stack[n] then 'name' was not defined
# in this scope at all.
self._scope_stack = [dict()]
# Keeps track of the last token given to yacc (the lookahead token)
self._last_yielded_token = None
def parse(self, text, filename='', debuglevel=0):
""" Parses C code and returns an AST.
text:
A string containing the C source code
filename:
Name of the file being parsed (for meaningful
error messages)
debuglevel:
Debug level to yacc
"""
self.clex.filename = filename
self.clex.reset_lineno()
self._scope_stack = [dict()]
self._last_yielded_token = None
return self.cparser.parse(
input=text,
lexer=self.clex,
debug=debuglevel)
######################-- PRIVATE --######################
def _push_scope(self):
self._scope_stack.append(dict())
def _pop_scope(self):
assert len(self._scope_stack) > 1
self._scope_stack.pop()
def _add_typedef_name(self, name, coord):
""" Add a new typedef name (ie a TYPEID) to the current scope
"""
if not self._scope_stack[-1].get(name, True):
self._parse_error(
"Typedef %r previously declared as non-typedef "
"in this scope" % name, coord)
self._scope_stack[-1][name] = True
def _add_identifier(self, name, coord):
""" Add a new object, function, or enum member name (ie an ID) to the
current scope
"""
if self._scope_stack[-1].get(name, False):
self._parse_error(
"Non-typedef %r previously declared as typedef "
"in this scope" % name, coord)
self._scope_stack[-1][name] = False
def _is_type_in_scope(self, name):
""" Is *name* a typedef-name in the current scope?
"""
for scope in reversed(self._scope_stack):
# If name is an identifier in this scope it shadows typedefs in
# higher scopes.
in_scope = scope.get(name)
if in_scope is not None: return in_scope
return False
def _lex_error_func(self, msg, line, column):
self._parse_error(msg, self._coord(line, column))
def _lex_on_lbrace_func(self):
self._push_scope()
def _lex_on_rbrace_func(self):
self._pop_scope()
def _lex_type_lookup_func(self, name):
""" Looks up types that were previously defined with
typedef.
Passed to the lexer for recognizing identifiers that
are types.
"""
is_type = self._is_type_in_scope(name)
return is_type
def _get_yacc_lookahead_token(self):
""" We need access to yacc's lookahead token in certain cases.
This is the last token yacc requested from the lexer, so we
ask the lexer.
"""
return self.clex.last_token
# To understand what's going on here, read sections A.8.5 and
# A.8.6 of K&R2 very carefully.
#
# A C type consists of a basic type declaration, with a list
# of modifiers. For example:
#
# int *c[5];
#
# The basic declaration here is 'int c', and the pointer and
# the array are the modifiers.
#
# Basic declarations are represented by TypeDecl (from module c_ast) and the
# modifiers are FuncDecl, PtrDecl and ArrayDecl.
#
# The standard states that whenever a new modifier is parsed, it should be
# added to the end of the list of modifiers. For example:
#
# K&R2 A.8.6.2: Array Declarators
#
# In a declaration T D where D has the form
# D1 [constant-expression-opt]
# and the type of the identifier in the declaration T D1 is
# "type-modifier T", the type of the
# identifier of D is "type-modifier array of T"
#
# This is what this method does. The declarator it receives
# can be a list of declarators ending with TypeDecl. It
# tacks the modifier to the end of this list, just before
# the TypeDecl.
#
# Additionally, the modifier may be a list itself. This is
# useful for pointers, that can come as a chain from the rule
# p_pointer. In this case, the whole modifier list is spliced
# into the new location.
def _type_modify_decl(self, decl, modifier):
""" Tacks a type modifier on a declarator, and returns
the modified declarator.
Note: the declarator and modifier may be modified
"""
#~ print '****'
#~ decl.show(offset=3)
#~ modifier.show(offset=3)
#~ print '****'
modifier_head = modifier
modifier_tail = modifier
# The modifier may be a nested list. Reach its tail.
#
while modifier_tail.type:
modifier_tail = modifier_tail.type
# If the decl is a basic type, just tack the modifier onto
# it
#
if isinstance(decl, c_ast.TypeDecl):
modifier_tail.type = decl
return modifier
else:
# Otherwise, the decl is a list of modifiers. Reach
# its tail and splice the modifier onto the tail,
# pointing to the underlying basic type.
#
decl_tail = decl
while not isinstance(decl_tail.type, c_ast.TypeDecl):
decl_tail = decl_tail.type
modifier_tail.type = decl_tail.type
decl_tail.type = modifier_head
return decl
# Due to the order in which declarators are constructed,
# they have to be fixed in order to look like a normal AST.
#
# When a declaration arrives from syntax construction, it has
# these problems:
# * The innermost TypeDecl has no type (because the basic
# type is only known at the uppermost declaration level)
# * The declaration has no variable name, since that is saved
# in the innermost TypeDecl
# * The typename of the declaration is a list of type
# specifiers, and not a node. Here, basic identifier types
# should be separated from more complex types like enums
# and structs.
#
# This method fixes these problems.
#
def _fix_decl_name_type(self, decl, typename):
""" Fixes a declaration. Modifies decl.
"""
# Reach the underlying basic type
#
type = decl
while not isinstance(type, c_ast.TypeDecl):
type = type.type
decl.name = type.declname
type.quals = decl.quals
# The typename is a list of types. If any type in this
# list isn't an IdentifierType, it must be the only
# type in the list (it's illegal to declare "int enum ..")
# If all the types are basic, they're collected in the
# IdentifierType holder.
#
for tn in typename:
if not isinstance(tn, c_ast.IdentifierType):
if len(typename) > 1:
self._parse_error(
"Invalid multiple types specified", tn.coord)
else:
type.type = tn
return decl
if not typename:
# Functions default to returning int
#
if not isinstance(decl.type, c_ast.FuncDecl):
self._parse_error(
"Missing type in declaration", decl.coord)
type.type = c_ast.IdentifierType(
['int'],
coord=decl.coord)
else:
# At this point, we know that typename is a list of IdentifierType
# nodes. Concatenate all the names into a single list.
#
type.type = c_ast.IdentifierType(
[name for id in typename for name in id.names],
coord=typename[0].coord)
return decl
def _add_declaration_specifier(self, declspec, newspec, kind, append=False):
""" Declaration specifiers are represented by a dictionary
with the entries:
* qual: a list of type qualifiers
* storage: a list of storage type qualifiers
* type: a list of type specifiers
* function: a list of function specifiers
This method is given a declaration specifier, and a
new specifier of a given kind.
If `append` is True, the new specifier is added to the end of
the specifiers list, otherwise it's added at the beginning.
Returns the declaration specifier, with the new
specifier incorporated.
"""
spec = declspec or dict(qual=[], storage=[], type=[], function=[])
if append:
spec[kind].append(newspec)
else:
spec[kind].insert(0, newspec)
return spec
def _build_declarations(self, spec, decls, typedef_namespace=False):
""" Builds a list of declarations all sharing the given specifiers.
If typedef_namespace is true, each declared name is added
to the "typedef namespace", which also includes objects,
functions, and enum constants.
"""
is_typedef = 'typedef' in spec['storage']
declarations = []
# Bit-fields are allowed to be unnamed.
#
if decls[0].get('bitsize') is not None:
pass
# When redeclaring typedef names as identifiers in inner scopes, a
# problem can occur where the identifier gets grouped into
# spec['type'], leaving decl as None. This can only occur for the
# first declarator.
#
elif decls[0]['decl'] is None:
if len(spec['type']) < 2 or len(spec['type'][-1].names) != 1 or \
not self._is_type_in_scope(spec['type'][-1].names[0]):
coord = '?'
for t in spec['type']:
if hasattr(t, 'coord'):
coord = t.coord
break
self._parse_error('Invalid declaration', coord)
# Make this look as if it came from "direct_declarator:ID"
decls[0]['decl'] = c_ast.TypeDecl(
declname=spec['type'][-1].names[0],
type=None,
quals=None,
coord=spec['type'][-1].coord)
# Remove the "new" type's name from the end of spec['type']
del spec['type'][-1]
# A similar problem can occur where the declaration ends up looking
# like an abstract declarator. Give it a name if this is the case.
#
elif not isinstance(decls[0]['decl'], (
c_ast.Enum, c_ast.Struct, c_ast.Union, c_ast.IdentifierType)):
decls_0_tail = decls[0]['decl']
while not isinstance(decls_0_tail, c_ast.TypeDecl):
decls_0_tail = decls_0_tail.type
if decls_0_tail.declname is None:
decls_0_tail.declname = spec['type'][-1].names[0]
del spec['type'][-1]
for decl in decls:
assert decl['decl'] is not None
if is_typedef:
declaration = c_ast.Typedef(
name=None,
quals=spec['qual'],
storage=spec['storage'],
type=decl['decl'],
coord=decl['decl'].coord)
else:
declaration = c_ast.Decl(
name=None,
quals=spec['qual'],
storage=spec['storage'],
funcspec=spec['function'],
type=decl['decl'],
init=decl.get('init'),
bitsize=decl.get('bitsize'),
coord=decl['decl'].coord)
if isinstance(declaration.type, (
c_ast.Enum, c_ast.Struct, c_ast.Union,
c_ast.IdentifierType)):
fixed_decl = declaration
else:
fixed_decl = self._fix_decl_name_type(declaration, spec['type'])
# Add the type name defined by typedef to a
# symbol table (for usage in the lexer)
#
if typedef_namespace:
if is_typedef:
self._add_typedef_name(fixed_decl.name, fixed_decl.coord)
else:
self._add_identifier(fixed_decl.name, fixed_decl.coord)
declarations.append(fixed_decl)
return declarations
def _build_function_definition(self, spec, decl, param_decls, body):
""" Builds a function definition.
"""
if 'typedef' in spec['storage']:
self._parse_error("Invalid typedef", decl.coord)
declaration = self._build_declarations(
spec=spec,
decls=[dict(decl=decl, init=None)],
typedef_namespace=True)[0]
return c_ast.FuncDef(
decl=declaration,
param_decls=param_decls,
body=body,
coord=decl.coord)
def _select_struct_union_class(self, token):
""" Given a token (either STRUCT or UNION), selects the
appropriate AST class.
"""
if token == 'struct':
return c_ast.Struct
else:
return c_ast.Union
##
## Precedence and associativity of operators
##
# If this changes, c_generator.CGenerator.precedence_map needs to change as well
precedence = (
('left', 'LOR'),
('left', 'LAND'),
('left', 'OR'),
('left', 'XOR'),
('left', 'AND'),
('left', 'EQ', 'NE'),
('left', 'GT', 'GE', 'LT', 'LE'),
('left', 'RSHIFT', 'LSHIFT'),
('left', 'PLUS', 'MINUS'),
('left', 'TIMES', 'DIVIDE', 'MOD')
)
##
## Grammar productions
## Implementation of the BNF defined in K&R2 A.13
##
# Wrapper around a translation unit, to allow for empty input.
# Not strictly part of the C99 Grammar, but useful in practice.
#
def p_translation_unit_or_empty(self, p):
""" translation_unit_or_empty : translation_unit
| empty
"""
if p[1] is None:
p[0] = c_ast.FileAST([])
else:
p[0] = c_ast.FileAST(p[1])
def p_translation_unit_1(self, p):
""" translation_unit : external_declaration
"""
# Note: external_declaration is already a list
#
p[0] = p[1]
def p_translation_unit_2(self, p):
""" translation_unit : translation_unit external_declaration
"""
p[1].extend(p[2])
p[0] = p[1]
# Declarations always come as lists (because they can be
# several in one line), so we wrap the function definition
# into a list as well, to make the return value of
# external_declaration homogenous.
#
def p_external_declaration_1(self, p):
""" external_declaration : function_definition
"""
p[0] = [p[1]]
def p_external_declaration_2(self, p):
""" external_declaration : declaration
"""
p[0] = p[1]
def p_external_declaration_3(self, p):
""" external_declaration : pp_directive
| pppragma_directive
"""
p[0] = [p[1]]
def p_external_declaration_4(self, p):
""" external_declaration : SEMI
"""
p[0] = []
def p_pp_directive(self, p):
""" pp_directive : PPHASH
"""
self._parse_error('Directives not supported yet',
self._token_coord(p, 1))
def p_pppragma_directive(self, p):
""" pppragma_directive : PPPRAGMA
| PPPRAGMA PPPRAGMASTR
"""
if len(p) == 3:
p[0] = c_ast.Pragma(p[2], self._token_coord(p, 2))
else:
p[0] = c_ast.Pragma("", self._token_coord(p, 1))
# In function definitions, the declarator can be followed by
# a declaration list, for old "K&R style" function definitios.
#
def p_function_definition_1(self, p):
""" function_definition : id_declarator declaration_list_opt compound_statement
"""
# no declaration specifiers - 'int' becomes the default type
spec = dict(
qual=[],
storage=[],
type=[c_ast.IdentifierType(['int'],
coord=self._token_coord(p, 1))],
function=[])
p[0] = self._build_function_definition(
spec=spec,
decl=p[1],
param_decls=p[2],
body=p[3])
def p_function_definition_2(self, p):
""" function_definition : declaration_specifiers id_declarator declaration_list_opt compound_statement
"""
spec = p[1]
p[0] = self._build_function_definition(
spec=spec,
decl=p[2],
param_decls=p[3],
body=p[4])
def p_statement(self, p):
""" statement : labeled_statement
| expression_statement
| compound_statement
| selection_statement
| iteration_statement
| jump_statement
| pppragma_directive
"""
p[0] = p[1]
# A pragma is generally considered a decorator rather than an actual statement.
# Still, for the purposes of analyzing an abstract syntax tree of C code,
# pragma's should not be ignored and were previously treated as a statement.
# This presents a problem for constructs that take a statement such as labeled_statements,
# selection_statements, and iteration_statements, causing a misleading structure
# in the AST. For example, consider the following C code.
#
# for (int i = 0; i < 3; i++)
# #pragma omp critical
# sum += 1;
#
# This code will compile and execute "sum += 1;" as the body of the for loop.
# Previous implementations of PyCParser would render the AST for this
# block of code as follows:
#
# For:
# DeclList:
# Decl: i, [], [], []
# TypeDecl: i, []
# IdentifierType: ['int']
# Constant: int, 0
# BinaryOp: <
# ID: i
# Constant: int, 3
# UnaryOp: p++
# ID: i
# Pragma: omp critical
# Assignment: +=
# ID: sum
# Constant: int, 1
#
# This AST misleadingly takes the Pragma as the body of the loop and the
# assignment then becomes a sibling of the loop.
#
# To solve edge cases like these, the pragmacomp_or_statement rule groups
# a pragma and its following statement (which would otherwise be orphaned)
# using a compound block, effectively turning the above code into:
#
# for (int i = 0; i < 3; i++) {
# #pragma omp critical
# sum += 1;
# }
def p_pragmacomp_or_statement(self, p):
""" pragmacomp_or_statement : pppragma_directive statement
| statement
"""
if isinstance(p[1], c_ast.Pragma) and len(p) == 3:
p[0] = c_ast.Compound(
block_items=[p[1], p[2]],
coord=self._token_coord(p, 1))
else:
p[0] = p[1]
# In C, declarations can come several in a line:
# int x, *px, romulo = 5;
#
# However, for the AST, we will split them to separate Decl
# nodes.
#
# This rule splits its declarations and always returns a list
# of Decl nodes, even if it's one element long.
#
def p_decl_body(self, p):
""" decl_body : declaration_specifiers init_declarator_list_opt
| declaration_specifiers_no_type id_init_declarator_list_opt
"""
spec = p[1]
# p[2] (init_declarator_list_opt) is either a list or None
#
if p[2] is None:
# By the standard, you must have at least one declarator unless
# declaring a structure tag, a union tag, or the members of an
# enumeration.
#
ty = spec['type']
s_u_or_e = (c_ast.Struct, c_ast.Union, c_ast.Enum)
if len(ty) == 1 and isinstance(ty[0], s_u_or_e):
decls = [c_ast.Decl(
name=None,
quals=spec['qual'],
storage=spec['storage'],
funcspec=spec['function'],
type=ty[0],
init=None,
bitsize=None,
coord=ty[0].coord)]
# However, this case can also occur on redeclared identifiers in
# an inner scope. The trouble is that the redeclared type's name
# gets grouped into declaration_specifiers; _build_declarations
# compensates for this.
#
else:
decls = self._build_declarations(
spec=spec,
decls=[dict(decl=None, init=None)],
typedef_namespace=True)
else:
decls = self._build_declarations(
spec=spec,
decls=p[2],
typedef_namespace=True)
p[0] = decls
# The declaration has been split to a decl_body sub-rule and
# SEMI, because having them in a single rule created a problem
# for defining typedefs.
#
# If a typedef line was directly followed by a line using the
# type defined with the typedef, the type would not be
# recognized. This is because to reduce the declaration rule,
# the parser's lookahead asked for the token after SEMI, which
# was the type from the next line, and the lexer had no chance
# to see the updated type symbol table.
#
# Splitting solves this problem, because after seeing SEMI,
# the parser reduces decl_body, which actually adds the new
# type into the table to be seen by the lexer before the next
# line is reached.
def p_declaration(self, p):
""" declaration : decl_body SEMI
"""
p[0] = p[1]
# Since each declaration is a list of declarations, this
# rule will combine all the declarations and return a single
# list
#
def p_declaration_list(self, p):
""" declaration_list : declaration
| declaration_list declaration
"""
p[0] = p[1] if len(p) == 2 else p[1] + p[2]
# To know when declaration-specifiers end and declarators begin,
# we require declaration-specifiers to have at least one
# type-specifier, and disallow typedef-names after we've seen any
# type-specifier. These are both required by the spec.
#
def p_declaration_specifiers_no_type_1(self, p):
""" declaration_specifiers_no_type : type_qualifier declaration_specifiers_no_type_opt
"""
p[0] = self._add_declaration_specifier(p[2], p[1], 'qual')
def p_declaration_specifiers_no_type_2(self, p):
""" declaration_specifiers_no_type : storage_class_specifier declaration_specifiers_no_type_opt
"""
p[0] = self._add_declaration_specifier(p[2], p[1], 'storage')
def p_declaration_specifiers_no_type_3(self, p):
""" declaration_specifiers_no_type : function_specifier declaration_specifiers_no_type_opt
"""
p[0] = self._add_declaration_specifier(p[2], p[1], 'function')
def p_declaration_specifiers_1(self, p):
""" declaration_specifiers : declaration_specifiers type_qualifier
"""
p[0] = self._add_declaration_specifier(p[1], p[2], 'qual', append=True)
def p_declaration_specifiers_2(self, p):
""" declaration_specifiers : declaration_specifiers storage_class_specifier
"""
p[0] = self._add_declaration_specifier(p[1], p[2], 'storage', append=True)
def p_declaration_specifiers_3(self, p):
""" declaration_specifiers : declaration_specifiers function_specifier
"""
p[0] = self._add_declaration_specifier(p[1], p[2], 'function', append=True)
def p_declaration_specifiers_4(self, p):
""" declaration_specifiers : declaration_specifiers type_specifier_no_typeid
"""
p[0] = self._add_declaration_specifier(p[1], p[2], 'type', append=True)
def p_declaration_specifiers_5(self, p):
""" declaration_specifiers : type_specifier
"""
p[0] = self._add_declaration_specifier(None, p[1], 'type')
def p_declaration_specifiers_6(self, p):
""" declaration_specifiers : declaration_specifiers_no_type type_specifier
"""
p[0] = self._add_declaration_specifier(p[1], p[2], 'type', append=True)
def p_storage_class_specifier(self, p):
""" storage_class_specifier : AUTO
| REGISTER
| STATIC
| EXTERN
| TYPEDEF
"""
p[0] = p[1]
def p_function_specifier(self, p):
""" function_specifier : INLINE
"""
p[0] = p[1]
def p_type_specifier_no_typeid(self, p):
""" type_specifier_no_typeid : VOID
| _BOOL
| CHAR
| SHORT
| INT
| LONG
| FLOAT
| DOUBLE
| _COMPLEX
| SIGNED
| UNSIGNED
| __INT128
"""
p[0] = c_ast.IdentifierType([p[1]], coord=self._token_coord(p, 1))
def p_type_specifier(self, p):
""" type_specifier : typedef_name
| enum_specifier
| struct_or_union_specifier
| type_specifier_no_typeid
"""
p[0] = p[1]
def p_type_qualifier(self, p):
""" type_qualifier : CONST
| RESTRICT
| VOLATILE
"""
p[0] = p[1]
def p_init_declarator_list(self, p):
""" init_declarator_list : init_declarator
| init_declarator_list COMMA init_declarator
"""
p[0] = p[1] + [p[3]] if len(p) == 4 else [p[1]]
# Returns a {decl=<declarator> : init=<initializer>} dictionary
# If there's no initializer, uses None
#
def p_init_declarator(self, p):
""" init_declarator : declarator
| declarator EQUALS initializer
"""
p[0] = dict(decl=p[1], init=(p[3] if len(p) > 2 else None))
def p_id_init_declarator_list(self, p):
""" id_init_declarator_list : id_init_declarator
| id_init_declarator_list COMMA init_declarator
"""
p[0] = p[1] + [p[3]] if len(p) == 4 else [p[1]]
def p_id_init_declarator(self, p):
""" id_init_declarator : id_declarator
| id_declarator EQUALS initializer
"""
p[0] = dict(decl=p[1], init=(p[3] if len(p) > 2 else None))
# Require at least one type specifier in a specifier-qualifier-list
#
def p_specifier_qualifier_list_1(self, p):
""" specifier_qualifier_list : specifier_qualifier_list type_specifier_no_typeid
"""
p[0] = self._add_declaration_specifier(p[1], p[2], 'type', append=True)
def p_specifier_qualifier_list_2(self, p):
""" specifier_qualifier_list : specifier_qualifier_list type_qualifier
"""
p[0] = self._add_declaration_specifier(p[1], p[2], 'qual', append=True)
def p_specifier_qualifier_list_3(self, p):
""" specifier_qualifier_list : type_specifier
"""
p[0] = self._add_declaration_specifier(None, p[1], 'type')
def p_specifier_qualifier_list_4(self, p):
""" specifier_qualifier_list : type_qualifier_list type_specifier
"""
spec = dict(qual=p[1], storage=[], type=[], function=[])
p[0] = self._add_declaration_specifier(spec, p[2], 'type', append=True)
# TYPEID is allowed here (and in other struct/enum related tag names), because
# struct/enum tags reside in their own namespace and can be named the same as types
#
def p_struct_or_union_specifier_1(self, p):
""" struct_or_union_specifier : struct_or_union ID
| struct_or_union TYPEID
"""
klass = self._select_struct_union_class(p[1])
# None means no list of members
p[0] = klass(
name=p[2],
decls=None,
coord=self._token_coord(p, 2))
def p_struct_or_union_specifier_2(self, p):
""" struct_or_union_specifier : struct_or_union brace_open struct_declaration_list brace_close
| struct_or_union brace_open brace_close
"""
klass = self._select_struct_union_class(p[1])
if len(p) == 4:
# Empty sequence means an empty list of members
p[0] = klass(
name=None,
decls=[],
coord=self._token_coord(p, 2))
else:
p[0] = klass(
name=None,
decls=p[3],
coord=self._token_coord(p, 2))
def p_struct_or_union_specifier_3(self, p):
""" struct_or_union_specifier : struct_or_union ID brace_open struct_declaration_list brace_close
| struct_or_union ID brace_open brace_close
| struct_or_union TYPEID brace_open struct_declaration_list brace_close
| struct_or_union TYPEID brace_open brace_close
"""
klass = self._select_struct_union_class(p[1])
if len(p) == 5:
# Empty sequence means an empty list of members
p[0] = klass(
name=p[2],
decls=[],
coord=self._token_coord(p, 2))
else:
p[0] = klass(
name=p[2],
decls=p[4],
coord=self._token_coord(p, 2))
def p_struct_or_union(self, p):
""" struct_or_union : STRUCT
| UNION
"""
p[0] = p[1]
# Combine all declarations into a single list
#
def p_struct_declaration_list(self, p):
""" struct_declaration_list : struct_declaration
| struct_declaration_list struct_declaration
"""
if len(p) == 2:
p[0] = p[1] or []
else:
p[0] = p[1] + (p[2] or [])
def p_struct_declaration_1(self, p):
""" struct_declaration : specifier_qualifier_list struct_declarator_list_opt SEMI
"""
spec = p[1]
assert 'typedef' not in spec['storage']
if p[2] is not None:
decls = self._build_declarations(
spec=spec,
decls=p[2])
elif len(spec['type']) == 1:
# Anonymous struct/union, gcc extension, C1x feature.
# Although the standard only allows structs/unions here, I see no
# reason to disallow other types since some compilers have typedefs
# here, and pycparser isn't about rejecting all invalid code.
#
node = spec['type'][0]
if isinstance(node, c_ast.Node):
decl_type = node
else:
decl_type = c_ast.IdentifierType(node)
decls = self._build_declarations(
spec=spec,
decls=[dict(decl=decl_type)])
else:
# Structure/union members can have the same names as typedefs.
# The trouble is that the member's name gets grouped into
# specifier_qualifier_list; _build_declarations compensates.
#
decls = self._build_declarations(
spec=spec,
decls=[dict(decl=None, init=None)])
p[0] = decls
def p_struct_declaration_2(self, p):
""" struct_declaration : SEMI
"""
p[0] = None
def p_struct_declaration_3(self, p):
""" struct_declaration : pppragma_directive
"""
p[0] = [p[1]]
def p_struct_declarator_list(self, p):
""" struct_declarator_list : struct_declarator
| struct_declarator_list COMMA struct_declarator
"""
p[0] = p[1] + [p[3]] if len(p) == 4 else [p[1]]
# struct_declarator passes up a dict with the keys: decl (for
# the underlying declarator) and bitsize (for the bitsize)
#
def p_struct_declarator_1(self, p):
""" struct_declarator : declarator
"""
p[0] = {'decl': p[1], 'bitsize': None}
def p_struct_declarator_2(self, p):
""" struct_declarator : declarator COLON constant_expression
| COLON constant_expression
"""
if len(p) > 3:
p[0] = {'decl': p[1], 'bitsize': p[3]}
else:
p[0] = {'decl': c_ast.TypeDecl(None, None, None), 'bitsize': p[2]}
def p_enum_specifier_1(self, p):
""" enum_specifier : ENUM ID
| ENUM TYPEID
"""
p[0] = c_ast.Enum(p[2], None, self._token_coord(p, 1))
def p_enum_specifier_2(self, p):
""" enum_specifier : ENUM brace_open enumerator_list brace_close
"""
p[0] = c_ast.Enum(None, p[3], self._token_coord(p, 1))
def p_enum_specifier_3(self, p):
""" enum_specifier : ENUM ID brace_open enumerator_list brace_close
| ENUM TYPEID brace_open enumerator_list brace_close
"""
p[0] = c_ast.Enum(p[2], p[4], self._token_coord(p, 1))
def p_enumerator_list(self, p):
""" enumerator_list : enumerator
| enumerator_list COMMA
| enumerator_list COMMA enumerator
"""
if len(p) == 2:
p[0] = c_ast.EnumeratorList([p[1]], p[1].coord)
elif len(p) == 3:
p[0] = p[1]
else:
p[1].enumerators.append(p[3])
p[0] = p[1]
def p_enumerator(self, p):
""" enumerator : ID
| ID EQUALS constant_expression
"""
if len(p) == 2:
enumerator = c_ast.Enumerator(
p[1], None,
self._token_coord(p, 1))
else:
enumerator = c_ast.Enumerator(
p[1], p[3],
self._token_coord(p, 1))
self._add_identifier(enumerator.name, enumerator.coord)
p[0] = enumerator
def p_declarator(self, p):
""" declarator : id_declarator
| typeid_declarator
"""
p[0] = p[1]
@parameterized(('id', 'ID'), ('typeid', 'TYPEID'), ('typeid_noparen', 'TYPEID'))
def p_xxx_declarator_1(self, p):
""" xxx_declarator : direct_xxx_declarator
"""
p[0] = p[1]
@parameterized(('id', 'ID'), ('typeid', 'TYPEID'), ('typeid_noparen', 'TYPEID'))
def p_xxx_declarator_2(self, p):
""" xxx_declarator : pointer direct_xxx_declarator
"""
p[0] = self._type_modify_decl(p[2], p[1])
@parameterized(('id', 'ID'), ('typeid', 'TYPEID'), ('typeid_noparen', 'TYPEID'))
def p_direct_xxx_declarator_1(self, p):
""" direct_xxx_declarator : yyy
"""
p[0] = c_ast.TypeDecl(
declname=p[1],
type=None,
quals=None,
coord=self._token_coord(p, 1))
@parameterized(('id', 'ID'), ('typeid', 'TYPEID'))
def p_direct_xxx_declarator_2(self, p):
""" direct_xxx_declarator : LPAREN xxx_declarator RPAREN
"""
p[0] = p[2]
@parameterized(('id', 'ID'), ('typeid', 'TYPEID'), ('typeid_noparen', 'TYPEID'))
def p_direct_xxx_declarator_3(self, p):
""" direct_xxx_declarator : direct_xxx_declarator LBRACKET type_qualifier_list_opt assignment_expression_opt RBRACKET
"""
quals = (p[3] if len(p) > 5 else []) or []
# Accept dimension qualifiers
# Per C99 6.7.5.3 p7
arr = c_ast.ArrayDecl(
type=None,
dim=p[4] if len(p) > 5 else p[3],
dim_quals=quals,
coord=p[1].coord)
p[0] = self._type_modify_decl(decl=p[1], modifier=arr)
@parameterized(('id', 'ID'), ('typeid', 'TYPEID'), ('typeid_noparen', 'TYPEID'))
def p_direct_xxx_declarator_4(self, p):
""" direct_xxx_declarator : direct_xxx_declarator LBRACKET STATIC type_qualifier_list_opt assignment_expression RBRACKET
| direct_xxx_declarator LBRACKET type_qualifier_list STATIC assignment_expression RBRACKET
"""
# Using slice notation for PLY objects doesn't work in Python 3 for the
# version of PLY embedded with pycparser; see PLY Google Code issue 30.
# Work around that here by listing the two elements separately.
listed_quals = [item if isinstance(item, list) else [item]
for item in [p[3],p[4]]]
dim_quals = [qual for sublist in listed_quals for qual in sublist
if qual is not None]
arr = c_ast.ArrayDecl(
type=None,
dim=p[5],
dim_quals=dim_quals,
coord=p[1].coord)
p[0] = self._type_modify_decl(decl=p[1], modifier=arr)
# Special for VLAs
#
@parameterized(('id', 'ID'), ('typeid', 'TYPEID'), ('typeid_noparen', 'TYPEID'))
def p_direct_xxx_declarator_5(self, p):
""" direct_xxx_declarator : direct_xxx_declarator LBRACKET type_qualifier_list_opt TIMES RBRACKET
"""
arr = c_ast.ArrayDecl(
type=None,
dim=c_ast.ID(p[4], self._token_coord(p, 4)),
dim_quals=p[3] if p[3] != None else [],
coord=p[1].coord)
p[0] = self._type_modify_decl(decl=p[1], modifier=arr)
@parameterized(('id', 'ID'), ('typeid', 'TYPEID'), ('typeid_noparen', 'TYPEID'))
def p_direct_xxx_declarator_6(self, p):
""" direct_xxx_declarator : direct_xxx_declarator LPAREN parameter_type_list RPAREN
| direct_xxx_declarator LPAREN identifier_list_opt RPAREN
"""
func = c_ast.FuncDecl(
args=p[3],
type=None,
coord=p[1].coord)
# To see why _get_yacc_lookahead_token is needed, consider:
# typedef char TT;
# void foo(int TT) { TT = 10; }
# Outside the function, TT is a typedef, but inside (starting and
# ending with the braces) it's a parameter. The trouble begins with
# yacc's lookahead token. We don't know if we're declaring or
# defining a function until we see LBRACE, but if we wait for yacc to
# trigger a rule on that token, then TT will have already been read
# and incorrectly interpreted as TYPEID. We need to add the
# parameters to the scope the moment the lexer sees LBRACE.
#
if self._get_yacc_lookahead_token().type == "LBRACE":
if func.args is not None:
for param in func.args.params:
if isinstance(param, c_ast.EllipsisParam): break
self._add_identifier(param.name, param.coord)
p[0] = self._type_modify_decl(decl=p[1], modifier=func)
def p_pointer(self, p):
""" pointer : TIMES type_qualifier_list_opt
| TIMES type_qualifier_list_opt pointer
"""
coord = self._token_coord(p, 1)
# Pointer decls nest from inside out. This is important when different
# levels have different qualifiers. For example:
#
# char * const * p;
#
# Means "pointer to const pointer to char"
#
# While:
#
# char ** const p;
#
# Means "const pointer to pointer to char"
#
# So when we construct PtrDecl nestings, the leftmost pointer goes in
# as the most nested type.
nested_type = c_ast.PtrDecl(quals=p[2] or [], type=None, coord=coord)
if len(p) > 3:
tail_type = p[3]
while tail_type.type is not None:
tail_type = tail_type.type
tail_type.type = nested_type
p[0] = p[3]
else:
p[0] = nested_type
def p_type_qualifier_list(self, p):
""" type_qualifier_list : type_qualifier
| type_qualifier_list type_qualifier
"""
p[0] = [p[1]] if len(p) == 2 else p[1] + [p[2]]
def p_parameter_type_list(self, p):
""" parameter_type_list : parameter_list
| parameter_list COMMA ELLIPSIS
"""
if len(p) > 2:
p[1].params.append(c_ast.EllipsisParam(self._token_coord(p, 3)))
p[0] = p[1]
def p_parameter_list(self, p):
""" parameter_list : parameter_declaration
| parameter_list COMMA parameter_declaration
"""
if len(p) == 2: # single parameter
p[0] = c_ast.ParamList([p[1]], p[1].coord)
else:
p[1].params.append(p[3])
p[0] = p[1]
# From ISO/IEC 9899:TC2, 6.7.5.3.11:
# "If, in a parameter declaration, an identifier can be treated either
# as a typedef name or as a parameter name, it shall be taken as a
# typedef name."
#
# Inside a parameter declaration, once we've reduced declaration specifiers,
# if we shift in an LPAREN and see a TYPEID, it could be either an abstract
# declarator or a declarator nested inside parens. This rule tells us to
# always treat it as an abstract declarator. Therefore, we only accept
# `id_declarator`s and `typeid_noparen_declarator`s.
def p_parameter_declaration_1(self, p):
""" parameter_declaration : declaration_specifiers id_declarator
| declaration_specifiers typeid_noparen_declarator
"""
spec = p[1]
if not spec['type']:
spec['type'] = [c_ast.IdentifierType(['int'],
coord=self._token_coord(p, 1))]
p[0] = self._build_declarations(
spec=spec,
decls=[dict(decl=p[2])])[0]
def p_parameter_declaration_2(self, p):
""" parameter_declaration : declaration_specifiers abstract_declarator_opt
"""
spec = p[1]
if not spec['type']:
spec['type'] = [c_ast.IdentifierType(['int'],
coord=self._token_coord(p, 1))]
# Parameters can have the same names as typedefs. The trouble is that
# the parameter's name gets grouped into declaration_specifiers, making
# it look like an old-style declaration; compensate.
#
if len(spec['type']) > 1 and len(spec['type'][-1].names) == 1 and \
self._is_type_in_scope(spec['type'][-1].names[0]):
decl = self._build_declarations(
spec=spec,
decls=[dict(decl=p[2], init=None)])[0]
# This truly is an old-style parameter declaration
#
else:
decl = c_ast.Typename(
name='',
quals=spec['qual'],
type=p[2] or c_ast.TypeDecl(None, None, None),
coord=self._token_coord(p, 2))
typename = spec['type']
decl = self._fix_decl_name_type(decl, typename)
p[0] = decl
def p_identifier_list(self, p):
""" identifier_list : identifier
| identifier_list COMMA identifier
"""
if len(p) == 2: # single parameter
p[0] = c_ast.ParamList([p[1]], p[1].coord)
else:
p[1].params.append(p[3])
p[0] = p[1]
def p_initializer_1(self, p):
""" initializer : assignment_expression
"""
p[0] = p[1]
def p_initializer_2(self, p):
""" initializer : brace_open initializer_list_opt brace_close
| brace_open initializer_list COMMA brace_close
"""
if p[2] is None:
p[0] = c_ast.InitList([], self._token_coord(p, 1))
else:
p[0] = p[2]
def p_initializer_list(self, p):
""" initializer_list : designation_opt initializer
| initializer_list COMMA designation_opt initializer
"""
if len(p) == 3: # single initializer
init = p[2] if p[1] is None else c_ast.NamedInitializer(p[1], p[2])
p[0] = c_ast.InitList([init], p[2].coord)
else:
init = p[4] if p[3] is None else c_ast.NamedInitializer(p[3], p[4])
p[1].exprs.append(init)
p[0] = p[1]
def p_designation(self, p):
""" designation : designator_list EQUALS
"""
p[0] = p[1]
# Designators are represented as a list of nodes, in the order in which
# they're written in the code.
#
def p_designator_list(self, p):
""" designator_list : designator
| designator_list designator
"""
p[0] = [p[1]] if len(p) == 2 else p[1] + [p[2]]
def p_designator(self, p):
""" designator : LBRACKET constant_expression RBRACKET
| PERIOD identifier
"""
p[0] = p[2]
def p_type_name(self, p):
""" type_name : specifier_qualifier_list abstract_declarator_opt
"""
typename = c_ast.Typename(
name='',
quals=p[1]['qual'],
type=p[2] or c_ast.TypeDecl(None, None, None),
coord=self._token_coord(p, 2))
p[0] = self._fix_decl_name_type(typename, p[1]['type'])
def p_abstract_declarator_1(self, p):
""" abstract_declarator : pointer
"""
dummytype = c_ast.TypeDecl(None, None, None)
p[0] = self._type_modify_decl(
decl=dummytype,
modifier=p[1])
def p_abstract_declarator_2(self, p):
""" abstract_declarator : pointer direct_abstract_declarator
"""
p[0] = self._type_modify_decl(p[2], p[1])
def p_abstract_declarator_3(self, p):
""" abstract_declarator : direct_abstract_declarator
"""
p[0] = p[1]
# Creating and using direct_abstract_declarator_opt here
# instead of listing both direct_abstract_declarator and the
# lack of it in the beginning of _1 and _2 caused two
# shift/reduce errors.
#
def p_direct_abstract_declarator_1(self, p):
""" direct_abstract_declarator : LPAREN abstract_declarator RPAREN """
p[0] = p[2]
def p_direct_abstract_declarator_2(self, p):
""" direct_abstract_declarator : direct_abstract_declarator LBRACKET assignment_expression_opt RBRACKET
"""
arr = c_ast.ArrayDecl(
type=None,
dim=p[3],
dim_quals=[],
coord=p[1].coord)
p[0] = self._type_modify_decl(decl=p[1], modifier=arr)
def p_direct_abstract_declarator_3(self, p):
""" direct_abstract_declarator : LBRACKET type_qualifier_list_opt assignment_expression_opt RBRACKET
"""
quals = (p[2] if len(p) > 4 else []) or []
p[0] = c_ast.ArrayDecl(
type=c_ast.TypeDecl(None, None, None),
dim=p[3] if len(p) > 4 else p[2],
dim_quals=quals,
coord=self._token_coord(p, 1))
def p_direct_abstract_declarator_4(self, p):
""" direct_abstract_declarator : direct_abstract_declarator LBRACKET TIMES RBRACKET
"""
arr = c_ast.ArrayDecl(
type=None,
dim=c_ast.ID(p[3], self._token_coord(p, 3)),
dim_quals=[],
coord=p[1].coord)
p[0] = self._type_modify_decl(decl=p[1], modifier=arr)
def p_direct_abstract_declarator_5(self, p):
""" direct_abstract_declarator : LBRACKET TIMES RBRACKET
"""
p[0] = c_ast.ArrayDecl(
type=c_ast.TypeDecl(None, None, None),
dim=c_ast.ID(p[3], self._token_coord(p, 3)),
dim_quals=[],
coord=self._token_coord(p, 1))
def p_direct_abstract_declarator_6(self, p):
""" direct_abstract_declarator : direct_abstract_declarator LPAREN parameter_type_list_opt RPAREN
"""
func = c_ast.FuncDecl(
args=p[3],
type=None,
coord=p[1].coord)
p[0] = self._type_modify_decl(decl=p[1], modifier=func)
def p_direct_abstract_declarator_7(self, p):
""" direct_abstract_declarator : LPAREN parameter_type_list_opt RPAREN
"""
p[0] = c_ast.FuncDecl(
args=p[2],
type=c_ast.TypeDecl(None, None, None),
coord=self._token_coord(p, 1))
# declaration is a list, statement isn't. To make it consistent, block_item
# will always be a list
#
def p_block_item(self, p):
""" block_item : declaration
| statement
"""
p[0] = p[1] if isinstance(p[1], list) else [p[1]]
# Since we made block_item a list, this just combines lists
#
def p_block_item_list(self, p):
""" block_item_list : block_item
| block_item_list block_item
"""
# Empty block items (plain ';') produce [None], so ignore them
p[0] = p[1] if (len(p) == 2 or p[2] == [None]) else p[1] + p[2]
def p_compound_statement_1(self, p):
""" compound_statement : brace_open block_item_list_opt brace_close """
p[0] = c_ast.Compound(
block_items=p[2],
coord=self._token_coord(p, 1))
def p_labeled_statement_1(self, p):
""" labeled_statement : ID COLON pragmacomp_or_statement """
p[0] = c_ast.Label(p[1], p[3], self._token_coord(p, 1))
def p_labeled_statement_2(self, p):
""" labeled_statement : CASE constant_expression COLON pragmacomp_or_statement """
p[0] = c_ast.Case(p[2], [p[4]], self._token_coord(p, 1))
def p_labeled_statement_3(self, p):
""" labeled_statement : DEFAULT COLON pragmacomp_or_statement """
p[0] = c_ast.Default([p[3]], self._token_coord(p, 1))
def p_selection_statement_1(self, p):
""" selection_statement : IF LPAREN expression RPAREN pragmacomp_or_statement """
p[0] = c_ast.If(p[3], p[5], None, self._token_coord(p, 1))
def p_selection_statement_2(self, p):
""" selection_statement : IF LPAREN expression RPAREN statement ELSE pragmacomp_or_statement """
p[0] = c_ast.If(p[3], p[5], p[7], self._token_coord(p, 1))
def p_selection_statement_3(self, p):
""" selection_statement : SWITCH LPAREN expression RPAREN pragmacomp_or_statement """
p[0] = fix_switch_cases(
c_ast.Switch(p[3], p[5], self._token_coord(p, 1)))
def p_iteration_statement_1(self, p):
""" iteration_statement : WHILE LPAREN expression RPAREN pragmacomp_or_statement """
p[0] = c_ast.While(p[3], p[5], self._token_coord(p, 1))
def p_iteration_statement_2(self, p):
""" iteration_statement : DO pragmacomp_or_statement WHILE LPAREN expression RPAREN SEMI """
p[0] = c_ast.DoWhile(p[5], p[2], self._token_coord(p, 1))
def p_iteration_statement_3(self, p):
""" iteration_statement : FOR LPAREN expression_opt SEMI expression_opt SEMI expression_opt RPAREN pragmacomp_or_statement """
p[0] = c_ast.For(p[3], p[5], p[7], p[9], self._token_coord(p, 1))
def p_iteration_statement_4(self, p):
""" iteration_statement : FOR LPAREN declaration expression_opt SEMI expression_opt RPAREN pragmacomp_or_statement """
p[0] = c_ast.For(c_ast.DeclList(p[3], self._token_coord(p, 1)),
p[4], p[6], p[8], self._token_coord(p, 1))
def p_jump_statement_1(self, p):
""" jump_statement : GOTO ID SEMI """
p[0] = c_ast.Goto(p[2], self._token_coord(p, 1))
def p_jump_statement_2(self, p):
""" jump_statement : BREAK SEMI """
p[0] = c_ast.Break(self._token_coord(p, 1))
def p_jump_statement_3(self, p):
""" jump_statement : CONTINUE SEMI """
p[0] = c_ast.Continue(self._token_coord(p, 1))
def p_jump_statement_4(self, p):
""" jump_statement : RETURN expression SEMI
| RETURN SEMI
"""
p[0] = c_ast.Return(p[2] if len(p) == 4 else None, self._token_coord(p, 1))
def p_expression_statement(self, p):
""" expression_statement : expression_opt SEMI """
if p[1] is None:
p[0] = c_ast.EmptyStatement(self._token_coord(p, 2))
else:
p[0] = p[1]
def p_expression(self, p):
""" expression : assignment_expression
| expression COMMA assignment_expression
"""
if len(p) == 2:
p[0] = p[1]
else:
if not isinstance(p[1], c_ast.ExprList):
p[1] = c_ast.ExprList([p[1]], p[1].coord)
p[1].exprs.append(p[3])
p[0] = p[1]
def p_typedef_name(self, p):
""" typedef_name : TYPEID """
p[0] = c_ast.IdentifierType([p[1]], coord=self._token_coord(p, 1))
def p_assignment_expression(self, p):
""" assignment_expression : conditional_expression
| unary_expression assignment_operator assignment_expression
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = c_ast.Assignment(p[2], p[1], p[3], p[1].coord)
# K&R2 defines these as many separate rules, to encode
# precedence and associativity. Why work hard ? I'll just use
# the built in precedence/associativity specification feature
# of PLY. (see precedence declaration above)
#
def p_assignment_operator(self, p):
""" assignment_operator : EQUALS
| XOREQUAL
| TIMESEQUAL
| DIVEQUAL
| MODEQUAL
| PLUSEQUAL
| MINUSEQUAL
| LSHIFTEQUAL
| RSHIFTEQUAL
| ANDEQUAL
| OREQUAL
"""
p[0] = p[1]
def p_constant_expression(self, p):
""" constant_expression : conditional_expression """
p[0] = p[1]
def p_conditional_expression(self, p):
""" conditional_expression : binary_expression
| binary_expression CONDOP expression COLON conditional_expression
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = c_ast.TernaryOp(p[1], p[3], p[5], p[1].coord)
def p_binary_expression(self, p):
""" binary_expression : cast_expression
| binary_expression TIMES binary_expression
| binary_expression DIVIDE binary_expression
| binary_expression MOD binary_expression
| binary_expression PLUS binary_expression
| binary_expression MINUS binary_expression
| binary_expression RSHIFT binary_expression
| binary_expression LSHIFT binary_expression
| binary_expression LT binary_expression
| binary_expression LE binary_expression
| binary_expression GE binary_expression
| binary_expression GT binary_expression
| binary_expression EQ binary_expression
| binary_expression NE binary_expression
| binary_expression AND binary_expression
| binary_expression OR binary_expression
| binary_expression XOR binary_expression
| binary_expression LAND binary_expression
| binary_expression LOR binary_expression
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = c_ast.BinaryOp(p[2], p[1], p[3], p[1].coord)
def p_cast_expression_1(self, p):
""" cast_expression : unary_expression """
p[0] = p[1]
def p_cast_expression_2(self, p):
""" cast_expression : LPAREN type_name RPAREN cast_expression """
p[0] = c_ast.Cast(p[2], p[4], self._token_coord(p, 1))
def p_unary_expression_1(self, p):
""" unary_expression : postfix_expression """
p[0] = p[1]
def p_unary_expression_2(self, p):
""" unary_expression : PLUSPLUS unary_expression
| MINUSMINUS unary_expression
| unary_operator cast_expression
"""
p[0] = c_ast.UnaryOp(p[1], p[2], p[2].coord)
def p_unary_expression_3(self, p):
""" unary_expression : SIZEOF unary_expression
| SIZEOF LPAREN type_name RPAREN
"""
p[0] = c_ast.UnaryOp(
p[1],
p[2] if len(p) == 3 else p[3],
self._token_coord(p, 1))
def p_unary_operator(self, p):
""" unary_operator : AND
| TIMES
| PLUS
| MINUS
| NOT
| LNOT
"""
p[0] = p[1]
def p_postfix_expression_1(self, p):
""" postfix_expression : primary_expression """
p[0] = p[1]
def p_postfix_expression_2(self, p):
""" postfix_expression : postfix_expression LBRACKET expression RBRACKET """
p[0] = c_ast.ArrayRef(p[1], p[3], p[1].coord)
def p_postfix_expression_3(self, p):
""" postfix_expression : postfix_expression LPAREN argument_expression_list RPAREN
| postfix_expression LPAREN RPAREN
"""
p[0] = c_ast.FuncCall(p[1], p[3] if len(p) == 5 else None, p[1].coord)
def p_postfix_expression_4(self, p):
""" postfix_expression : postfix_expression PERIOD ID
| postfix_expression PERIOD TYPEID
| postfix_expression ARROW ID
| postfix_expression ARROW TYPEID
"""
field = c_ast.ID(p[3], self._token_coord(p, 3))
p[0] = c_ast.StructRef(p[1], p[2], field, p[1].coord)
def p_postfix_expression_5(self, p):
""" postfix_expression : postfix_expression PLUSPLUS
| postfix_expression MINUSMINUS
"""
p[0] = c_ast.UnaryOp('p' + p[2], p[1], p[1].coord)
def p_postfix_expression_6(self, p):
""" postfix_expression : LPAREN type_name RPAREN brace_open initializer_list brace_close
| LPAREN type_name RPAREN brace_open initializer_list COMMA brace_close
"""
p[0] = c_ast.CompoundLiteral(p[2], p[5])
def p_primary_expression_1(self, p):
""" primary_expression : identifier """
p[0] = p[1]
def p_primary_expression_2(self, p):
""" primary_expression : constant """
p[0] = p[1]
def p_primary_expression_3(self, p):
""" primary_expression : unified_string_literal
| unified_wstring_literal
"""
p[0] = p[1]
def p_primary_expression_4(self, p):
""" primary_expression : LPAREN expression RPAREN """
p[0] = p[2]
def p_primary_expression_5(self, p):
""" primary_expression : OFFSETOF LPAREN type_name COMMA offsetof_member_designator RPAREN
"""
coord = self._token_coord(p, 1)
p[0] = c_ast.FuncCall(c_ast.ID(p[1], coord),
c_ast.ExprList([p[3], p[5]], coord),
coord)
def p_offsetof_member_designator(self, p):
""" offsetof_member_designator : identifier
| offsetof_member_designator PERIOD identifier
| offsetof_member_designator LBRACKET expression RBRACKET
"""
if len(p) == 2:
p[0] = p[1]
elif len(p) == 4:
p[0] = c_ast.StructRef(p[1], p[2], p[3], p[1].coord)
elif len(p) == 5:
p[0] = c_ast.ArrayRef(p[1], p[3], p[1].coord)
else:
raise NotImplementedError("Unexpected parsing state. len(p): %u" % len(p))
def p_argument_expression_list(self, p):
""" argument_expression_list : assignment_expression
| argument_expression_list COMMA assignment_expression
"""
if len(p) == 2: # single expr
p[0] = c_ast.ExprList([p[1]], p[1].coord)
else:
p[1].exprs.append(p[3])
p[0] = p[1]
def p_identifier(self, p):
""" identifier : ID """
p[0] = c_ast.ID(p[1], self._token_coord(p, 1))
def p_constant_1(self, p):
""" constant : INT_CONST_DEC
| INT_CONST_OCT
| INT_CONST_HEX
| INT_CONST_BIN
| INT_CONST_CHAR
"""
uCount = 0
lCount = 0
for x in p[1][-3:]:
if x in ('l', 'L'):
lCount += 1
elif x in ('u', 'U'):
uCount += 1
t = ''
if uCount > 1:
raise ValueError('Constant cannot have more than one u/U suffix.')
elif lCount > 2:
raise ValueError('Constant cannot have more than two l/L suffix.')
prefix = 'unsigned ' * uCount + 'long ' * lCount
p[0] = c_ast.Constant(
prefix + 'int', p[1], self._token_coord(p, 1))
def p_constant_2(self, p):
""" constant : FLOAT_CONST
| HEX_FLOAT_CONST
"""
if 'x' in p[1].lower():
t = 'float'
else:
if p[1][-1] in ('f', 'F'):
t = 'float'
elif p[1][-1] in ('l', 'L'):
t = 'long double'
else:
t = 'double'
p[0] = c_ast.Constant(
t, p[1], self._token_coord(p, 1))
def p_constant_3(self, p):
""" constant : CHAR_CONST
| WCHAR_CONST
"""
p[0] = c_ast.Constant(
'char', p[1], self._token_coord(p, 1))
# The "unified" string and wstring literal rules are for supporting
# concatenation of adjacent string literals.
# I.e. "hello " "world" is seen by the C compiler as a single string literal
# with the value "hello world"
#
def p_unified_string_literal(self, p):
""" unified_string_literal : STRING_LITERAL
| unified_string_literal STRING_LITERAL
"""
if len(p) == 2: # single literal
p[0] = c_ast.Constant(
'string', p[1], self._token_coord(p, 1))
else:
p[1].value = p[1].value[:-1] + p[2][1:]
p[0] = p[1]
def p_unified_wstring_literal(self, p):
""" unified_wstring_literal : WSTRING_LITERAL
| unified_wstring_literal WSTRING_LITERAL
"""
if len(p) == 2: # single literal
p[0] = c_ast.Constant(
'string', p[1], self._token_coord(p, 1))
else:
p[1].value = p[1].value.rstrip()[:-1] + p[2][2:]
p[0] = p[1]
def p_brace_open(self, p):
""" brace_open : LBRACE
"""
p[0] = p[1]
p.set_lineno(0, p.lineno(1))
def p_brace_close(self, p):
""" brace_close : RBRACE
"""
p[0] = p[1]
p.set_lineno(0, p.lineno(1))
def p_empty(self, p):
'empty : '
p[0] = None
def p_error(self, p):
# If error recovery is added here in the future, make sure
# _get_yacc_lookahead_token still works!
#
if p:
self._parse_error(
'before: %s' % p.value,
self._coord(lineno=p.lineno,
column=self.clex.find_tok_column(p)))
else:
self._parse_error('At end of input', self.clex.filename)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/c_parser.py | Python | apache-2.0 | 69,931 |
# PLY package
# Author: David Beazley (dave@dabeaz.com)
__version__ = '3.9'
__all__ = ['lex','yacc']
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/ply/__init__.py | Python | apache-2.0 | 102 |
# -----------------------------------------------------------------------------
# cpp.py
#
# Author: David Beazley (http://www.dabeaz.com)
# Copyright (C) 2017
# All rights reserved
#
# This module implements an ANSI-C style lexical preprocessor for PLY.
# -----------------------------------------------------------------------------
import sys
# Some Python 3 compatibility shims
if sys.version_info.major < 3:
STRING_TYPES = (str, unicode)
else:
STRING_TYPES = str
xrange = range
# -----------------------------------------------------------------------------
# Default preprocessor lexer definitions. These tokens are enough to get
# a basic preprocessor working. Other modules may import these if they want
# -----------------------------------------------------------------------------
tokens = (
'CPP_ID','CPP_INTEGER', 'CPP_FLOAT', 'CPP_STRING', 'CPP_CHAR', 'CPP_WS', 'CPP_COMMENT1', 'CPP_COMMENT2', 'CPP_POUND','CPP_DPOUND'
)
literals = "+-*/%|&~^<>=!?()[]{}.,;:\\\'\""
# Whitespace
def t_CPP_WS(t):
r'\s+'
t.lexer.lineno += t.value.count("\n")
return t
t_CPP_POUND = r'\#'
t_CPP_DPOUND = r'\#\#'
# Identifier
t_CPP_ID = r'[A-Za-z_][\w_]*'
# Integer literal
def CPP_INTEGER(t):
r'(((((0x)|(0X))[0-9a-fA-F]+)|(\d+))([uU][lL]|[lL][uU]|[uU]|[lL])?)'
return t
t_CPP_INTEGER = CPP_INTEGER
# Floating literal
t_CPP_FLOAT = r'((\d+)(\.\d+)(e(\+|-)?(\d+))? | (\d+)e(\+|-)?(\d+))([lL]|[fF])?'
# String literal
def t_CPP_STRING(t):
r'\"([^\\\n]|(\\(.|\n)))*?\"'
t.lexer.lineno += t.value.count("\n")
return t
# Character constant 'c' or L'c'
def t_CPP_CHAR(t):
r'(L)?\'([^\\\n]|(\\(.|\n)))*?\''
t.lexer.lineno += t.value.count("\n")
return t
# Comment
def t_CPP_COMMENT1(t):
r'(/\*(.|\n)*?\*/)'
ncr = t.value.count("\n")
t.lexer.lineno += ncr
# replace with one space or a number of '\n'
t.type = 'CPP_WS'; t.value = '\n' * ncr if ncr else ' '
return t
# Line comment
def t_CPP_COMMENT2(t):
r'(//.*?(\n|$))'
# replace with '/n'
t.type = 'CPP_WS'; t.value = '\n'
return t
def t_error(t):
t.type = t.value[0]
t.value = t.value[0]
t.lexer.skip(1)
return t
import re
import copy
import time
import os.path
# -----------------------------------------------------------------------------
# trigraph()
#
# Given an input string, this function replaces all trigraph sequences.
# The following mapping is used:
#
# ??= #
# ??/ \
# ??' ^
# ??( [
# ??) ]
# ??! |
# ??< {
# ??> }
# ??- ~
# -----------------------------------------------------------------------------
_trigraph_pat = re.compile(r'''\?\?[=/\'\(\)\!<>\-]''')
_trigraph_rep = {
'=':'#',
'/':'\\',
"'":'^',
'(':'[',
')':']',
'!':'|',
'<':'{',
'>':'}',
'-':'~'
}
def trigraph(input):
return _trigraph_pat.sub(lambda g: _trigraph_rep[g.group()[-1]],input)
# ------------------------------------------------------------------
# Macro object
#
# This object holds information about preprocessor macros
#
# .name - Macro name (string)
# .value - Macro value (a list of tokens)
# .arglist - List of argument names
# .variadic - Boolean indicating whether or not variadic macro
# .vararg - Name of the variadic parameter
#
# When a macro is created, the macro replacement token sequence is
# pre-scanned and used to create patch lists that are later used
# during macro expansion
# ------------------------------------------------------------------
class Macro(object):
def __init__(self,name,value,arglist=None,variadic=False):
self.name = name
self.value = value
self.arglist = arglist
self.variadic = variadic
if variadic:
self.vararg = arglist[-1]
self.source = None
# ------------------------------------------------------------------
# Preprocessor object
#
# Object representing a preprocessor. Contains macro definitions,
# include directories, and other information
# ------------------------------------------------------------------
class Preprocessor(object):
def __init__(self,lexer=None):
if lexer is None:
lexer = lex.lexer
self.lexer = lexer
self.macros = { }
self.path = []
self.temp_path = []
# Probe the lexer for selected tokens
self.lexprobe()
tm = time.localtime()
self.define("__DATE__ \"%s\"" % time.strftime("%b %d %Y",tm))
self.define("__TIME__ \"%s\"" % time.strftime("%H:%M:%S",tm))
self.parser = None
# -----------------------------------------------------------------------------
# tokenize()
#
# Utility function. Given a string of text, tokenize into a list of tokens
# -----------------------------------------------------------------------------
def tokenize(self,text):
tokens = []
self.lexer.input(text)
while True:
tok = self.lexer.token()
if not tok: break
tokens.append(tok)
return tokens
# ---------------------------------------------------------------------
# error()
#
# Report a preprocessor error/warning of some kind
# ----------------------------------------------------------------------
def error(self,file,line,msg):
print("%s:%d %s" % (file,line,msg))
# ----------------------------------------------------------------------
# lexprobe()
#
# This method probes the preprocessor lexer object to discover
# the token types of symbols that are important to the preprocessor.
# If this works right, the preprocessor will simply "work"
# with any suitable lexer regardless of how tokens have been named.
# ----------------------------------------------------------------------
def lexprobe(self):
# Determine the token type for identifiers
self.lexer.input("identifier")
tok = self.lexer.token()
if not tok or tok.value != "identifier":
print("Couldn't determine identifier type")
else:
self.t_ID = tok.type
# Determine the token type for integers
self.lexer.input("12345")
tok = self.lexer.token()
if not tok or int(tok.value) != 12345:
print("Couldn't determine integer type")
else:
self.t_INTEGER = tok.type
self.t_INTEGER_TYPE = type(tok.value)
# Determine the token type for strings enclosed in double quotes
self.lexer.input("\"filename\"")
tok = self.lexer.token()
if not tok or tok.value != "\"filename\"":
print("Couldn't determine string type")
else:
self.t_STRING = tok.type
# Determine the token type for whitespace--if any
self.lexer.input(" ")
tok = self.lexer.token()
if not tok or tok.value != " ":
self.t_SPACE = None
else:
self.t_SPACE = tok.type
# Determine the token type for newlines
self.lexer.input("\n")
tok = self.lexer.token()
if not tok or tok.value != "\n":
self.t_NEWLINE = None
print("Couldn't determine token for newlines")
else:
self.t_NEWLINE = tok.type
self.t_WS = (self.t_SPACE, self.t_NEWLINE)
# Check for other characters used by the preprocessor
chars = [ '<','>','#','##','\\','(',')',',','.']
for c in chars:
self.lexer.input(c)
tok = self.lexer.token()
if not tok or tok.value != c:
print("Unable to lex '%s' required for preprocessor" % c)
# ----------------------------------------------------------------------
# add_path()
#
# Adds a search path to the preprocessor.
# ----------------------------------------------------------------------
def add_path(self,path):
self.path.append(path)
# ----------------------------------------------------------------------
# group_lines()
#
# Given an input string, this function splits it into lines. Trailing whitespace
# is removed. Any line ending with \ is grouped with the next line. This
# function forms the lowest level of the preprocessor---grouping into text into
# a line-by-line format.
# ----------------------------------------------------------------------
def group_lines(self,input):
lex = self.lexer.clone()
lines = [x.rstrip() for x in input.splitlines()]
for i in xrange(len(lines)):
j = i+1
while lines[i].endswith('\\') and (j < len(lines)):
lines[i] = lines[i][:-1]+lines[j]
lines[j] = ""
j += 1
input = "\n".join(lines)
lex.input(input)
lex.lineno = 1
current_line = []
while True:
tok = lex.token()
if not tok:
break
current_line.append(tok)
if tok.type in self.t_WS and '\n' in tok.value:
yield current_line
current_line = []
if current_line:
yield current_line
# ----------------------------------------------------------------------
# tokenstrip()
#
# Remove leading/trailing whitespace tokens from a token list
# ----------------------------------------------------------------------
def tokenstrip(self,tokens):
i = 0
while i < len(tokens) and tokens[i].type in self.t_WS:
i += 1
del tokens[:i]
i = len(tokens)-1
while i >= 0 and tokens[i].type in self.t_WS:
i -= 1
del tokens[i+1:]
return tokens
# ----------------------------------------------------------------------
# collect_args()
#
# Collects comma separated arguments from a list of tokens. The arguments
# must be enclosed in parenthesis. Returns a tuple (tokencount,args,positions)
# where tokencount is the number of tokens consumed, args is a list of arguments,
# and positions is a list of integers containing the starting index of each
# argument. Each argument is represented by a list of tokens.
#
# When collecting arguments, leading and trailing whitespace is removed
# from each argument.
#
# This function properly handles nested parenthesis and commas---these do not
# define new arguments.
# ----------------------------------------------------------------------
def collect_args(self,tokenlist):
args = []
positions = []
current_arg = []
nesting = 1
tokenlen = len(tokenlist)
# Search for the opening '('.
i = 0
while (i < tokenlen) and (tokenlist[i].type in self.t_WS):
i += 1
if (i < tokenlen) and (tokenlist[i].value == '('):
positions.append(i+1)
else:
self.error(self.source,tokenlist[0].lineno,"Missing '(' in macro arguments")
return 0, [], []
i += 1
while i < tokenlen:
t = tokenlist[i]
if t.value == '(':
current_arg.append(t)
nesting += 1
elif t.value == ')':
nesting -= 1
if nesting == 0:
if current_arg:
args.append(self.tokenstrip(current_arg))
positions.append(i)
return i+1,args,positions
current_arg.append(t)
elif t.value == ',' and nesting == 1:
args.append(self.tokenstrip(current_arg))
positions.append(i+1)
current_arg = []
else:
current_arg.append(t)
i += 1
# Missing end argument
self.error(self.source,tokenlist[-1].lineno,"Missing ')' in macro arguments")
return 0, [],[]
# ----------------------------------------------------------------------
# macro_prescan()
#
# Examine the macro value (token sequence) and identify patch points
# This is used to speed up macro expansion later on---we'll know
# right away where to apply patches to the value to form the expansion
# ----------------------------------------------------------------------
def macro_prescan(self,macro):
macro.patch = [] # Standard macro arguments
macro.str_patch = [] # String conversion expansion
macro.var_comma_patch = [] # Variadic macro comma patch
i = 0
while i < len(macro.value):
if macro.value[i].type == self.t_ID and macro.value[i].value in macro.arglist:
argnum = macro.arglist.index(macro.value[i].value)
# Conversion of argument to a string
if i > 0 and macro.value[i-1].value == '#':
macro.value[i] = copy.copy(macro.value[i])
macro.value[i].type = self.t_STRING
del macro.value[i-1]
macro.str_patch.append((argnum,i-1))
continue
# Concatenation
elif (i > 0 and macro.value[i-1].value == '##'):
macro.patch.append(('c',argnum,i-1))
del macro.value[i-1]
continue
elif ((i+1) < len(macro.value) and macro.value[i+1].value == '##'):
macro.patch.append(('c',argnum,i))
i += 1
continue
# Standard expansion
else:
macro.patch.append(('e',argnum,i))
elif macro.value[i].value == '##':
if macro.variadic and (i > 0) and (macro.value[i-1].value == ',') and \
((i+1) < len(macro.value)) and (macro.value[i+1].type == self.t_ID) and \
(macro.value[i+1].value == macro.vararg):
macro.var_comma_patch.append(i-1)
i += 1
macro.patch.sort(key=lambda x: x[2],reverse=True)
# ----------------------------------------------------------------------
# macro_expand_args()
#
# Given a Macro and list of arguments (each a token list), this method
# returns an expanded version of a macro. The return value is a token sequence
# representing the replacement macro tokens
# ----------------------------------------------------------------------
def macro_expand_args(self,macro,args):
# Make a copy of the macro token sequence
rep = [copy.copy(_x) for _x in macro.value]
# Make string expansion patches. These do not alter the length of the replacement sequence
str_expansion = {}
for argnum, i in macro.str_patch:
if argnum not in str_expansion:
str_expansion[argnum] = ('"%s"' % "".join([x.value for x in args[argnum]])).replace("\\","\\\\")
rep[i] = copy.copy(rep[i])
rep[i].value = str_expansion[argnum]
# Make the variadic macro comma patch. If the variadic macro argument is empty, we get rid
comma_patch = False
if macro.variadic and not args[-1]:
for i in macro.var_comma_patch:
rep[i] = None
comma_patch = True
# Make all other patches. The order of these matters. It is assumed that the patch list
# has been sorted in reverse order of patch location since replacements will cause the
# size of the replacement sequence to expand from the patch point.
expanded = { }
for ptype, argnum, i in macro.patch:
# Concatenation. Argument is left unexpanded
if ptype == 'c':
rep[i:i+1] = args[argnum]
# Normal expansion. Argument is macro expanded first
elif ptype == 'e':
if argnum not in expanded:
expanded[argnum] = self.expand_macros(args[argnum])
rep[i:i+1] = expanded[argnum]
# Get rid of removed comma if necessary
if comma_patch:
rep = [_i for _i in rep if _i]
return rep
# ----------------------------------------------------------------------
# expand_macros()
#
# Given a list of tokens, this function performs macro expansion.
# The expanded argument is a dictionary that contains macros already
# expanded. This is used to prevent infinite recursion.
# ----------------------------------------------------------------------
def expand_macros(self,tokens,expanded=None):
if expanded is None:
expanded = {}
i = 0
while i < len(tokens):
t = tokens[i]
if t.type == self.t_ID:
if t.value in self.macros and t.value not in expanded:
# Yes, we found a macro match
expanded[t.value] = True
m = self.macros[t.value]
if not m.arglist:
# A simple macro
ex = self.expand_macros([copy.copy(_x) for _x in m.value],expanded)
for e in ex:
e.lineno = t.lineno
tokens[i:i+1] = ex
i += len(ex)
else:
# A macro with arguments
j = i + 1
while j < len(tokens) and tokens[j].type in self.t_WS:
j += 1
if tokens[j].value == '(':
tokcount,args,positions = self.collect_args(tokens[j:])
if not m.variadic and len(args) != len(m.arglist):
self.error(self.source,t.lineno,"Macro %s requires %d arguments" % (t.value,len(m.arglist)))
i = j + tokcount
elif m.variadic and len(args) < len(m.arglist)-1:
if len(m.arglist) > 2:
self.error(self.source,t.lineno,"Macro %s must have at least %d arguments" % (t.value, len(m.arglist)-1))
else:
self.error(self.source,t.lineno,"Macro %s must have at least %d argument" % (t.value, len(m.arglist)-1))
i = j + tokcount
else:
if m.variadic:
if len(args) == len(m.arglist)-1:
args.append([])
else:
args[len(m.arglist)-1] = tokens[j+positions[len(m.arglist)-1]:j+tokcount-1]
del args[len(m.arglist):]
# Get macro replacement text
rep = self.macro_expand_args(m,args)
rep = self.expand_macros(rep,expanded)
for r in rep:
r.lineno = t.lineno
tokens[i:j+tokcount] = rep
i += len(rep)
del expanded[t.value]
continue
elif t.value == '__LINE__':
t.type = self.t_INTEGER
t.value = self.t_INTEGER_TYPE(t.lineno)
i += 1
return tokens
# ----------------------------------------------------------------------
# evalexpr()
#
# Evaluate an expression token sequence for the purposes of evaluating
# integral expressions.
# ----------------------------------------------------------------------
def evalexpr(self,tokens):
# tokens = tokenize(line)
# Search for defined macros
i = 0
while i < len(tokens):
if tokens[i].type == self.t_ID and tokens[i].value == 'defined':
j = i + 1
needparen = False
result = "0L"
while j < len(tokens):
if tokens[j].type in self.t_WS:
j += 1
continue
elif tokens[j].type == self.t_ID:
if tokens[j].value in self.macros:
result = "1L"
else:
result = "0L"
if not needparen: break
elif tokens[j].value == '(':
needparen = True
elif tokens[j].value == ')':
break
else:
self.error(self.source,tokens[i].lineno,"Malformed defined()")
j += 1
tokens[i].type = self.t_INTEGER
tokens[i].value = self.t_INTEGER_TYPE(result)
del tokens[i+1:j+1]
i += 1
tokens = self.expand_macros(tokens)
for i,t in enumerate(tokens):
if t.type == self.t_ID:
tokens[i] = copy.copy(t)
tokens[i].type = self.t_INTEGER
tokens[i].value = self.t_INTEGER_TYPE("0L")
elif t.type == self.t_INTEGER:
tokens[i] = copy.copy(t)
# Strip off any trailing suffixes
tokens[i].value = str(tokens[i].value)
while tokens[i].value[-1] not in "0123456789abcdefABCDEF":
tokens[i].value = tokens[i].value[:-1]
expr = "".join([str(x.value) for x in tokens])
expr = expr.replace("&&"," and ")
expr = expr.replace("||"," or ")
expr = expr.replace("!"," not ")
try:
result = eval(expr)
except Exception:
self.error(self.source,tokens[0].lineno,"Couldn't evaluate expression")
result = 0
return result
# ----------------------------------------------------------------------
# parsegen()
#
# Parse an input string/
# ----------------------------------------------------------------------
def parsegen(self,input,source=None):
# Replace trigraph sequences
t = trigraph(input)
lines = self.group_lines(t)
if not source:
source = ""
self.define("__FILE__ \"%s\"" % source)
self.source = source
chunk = []
enable = True
iftrigger = False
ifstack = []
for x in lines:
for i,tok in enumerate(x):
if tok.type not in self.t_WS: break
if tok.value == '#':
# Preprocessor directive
# insert necessary whitespace instead of eaten tokens
for tok in x:
if tok.type in self.t_WS and '\n' in tok.value:
chunk.append(tok)
dirtokens = self.tokenstrip(x[i+1:])
if dirtokens:
name = dirtokens[0].value
args = self.tokenstrip(dirtokens[1:])
else:
name = ""
args = []
if name == 'define':
if enable:
for tok in self.expand_macros(chunk):
yield tok
chunk = []
self.define(args)
elif name == 'include':
if enable:
for tok in self.expand_macros(chunk):
yield tok
chunk = []
oldfile = self.macros['__FILE__']
for tok in self.include(args):
yield tok
self.macros['__FILE__'] = oldfile
self.source = source
elif name == 'undef':
if enable:
for tok in self.expand_macros(chunk):
yield tok
chunk = []
self.undef(args)
elif name == 'ifdef':
ifstack.append((enable,iftrigger))
if enable:
if not args[0].value in self.macros:
enable = False
iftrigger = False
else:
iftrigger = True
elif name == 'ifndef':
ifstack.append((enable,iftrigger))
if enable:
if args[0].value in self.macros:
enable = False
iftrigger = False
else:
iftrigger = True
elif name == 'if':
ifstack.append((enable,iftrigger))
if enable:
result = self.evalexpr(args)
if not result:
enable = False
iftrigger = False
else:
iftrigger = True
elif name == 'elif':
if ifstack:
if ifstack[-1][0]: # We only pay attention if outer "if" allows this
if enable: # If already true, we flip enable False
enable = False
elif not iftrigger: # If False, but not triggered yet, we'll check expression
result = self.evalexpr(args)
if result:
enable = True
iftrigger = True
else:
self.error(self.source,dirtokens[0].lineno,"Misplaced #elif")
elif name == 'else':
if ifstack:
if ifstack[-1][0]:
if enable:
enable = False
elif not iftrigger:
enable = True
iftrigger = True
else:
self.error(self.source,dirtokens[0].lineno,"Misplaced #else")
elif name == 'endif':
if ifstack:
enable,iftrigger = ifstack.pop()
else:
self.error(self.source,dirtokens[0].lineno,"Misplaced #endif")
else:
# Unknown preprocessor directive
pass
else:
# Normal text
if enable:
chunk.extend(x)
for tok in self.expand_macros(chunk):
yield tok
chunk = []
# ----------------------------------------------------------------------
# include()
#
# Implementation of file-inclusion
# ----------------------------------------------------------------------
def include(self,tokens):
# Try to extract the filename and then process an include file
if not tokens:
return
if tokens:
if tokens[0].value != '<' and tokens[0].type != self.t_STRING:
tokens = self.expand_macros(tokens)
if tokens[0].value == '<':
# Include <...>
i = 1
while i < len(tokens):
if tokens[i].value == '>':
break
i += 1
else:
print("Malformed #include <...>")
return
filename = "".join([x.value for x in tokens[1:i]])
path = self.path + [""] + self.temp_path
elif tokens[0].type == self.t_STRING:
filename = tokens[0].value[1:-1]
path = self.temp_path + [""] + self.path
else:
print("Malformed #include statement")
return
for p in path:
iname = os.path.join(p,filename)
try:
data = open(iname,"r").read()
dname = os.path.dirname(iname)
if dname:
self.temp_path.insert(0,dname)
for tok in self.parsegen(data,filename):
yield tok
if dname:
del self.temp_path[0]
break
except IOError:
pass
else:
print("Couldn't find '%s'" % filename)
# ----------------------------------------------------------------------
# define()
#
# Define a new macro
# ----------------------------------------------------------------------
def define(self,tokens):
if isinstance(tokens,STRING_TYPES):
tokens = self.tokenize(tokens)
linetok = tokens
try:
name = linetok[0]
if len(linetok) > 1:
mtype = linetok[1]
else:
mtype = None
if not mtype:
m = Macro(name.value,[])
self.macros[name.value] = m
elif mtype.type in self.t_WS:
# A normal macro
m = Macro(name.value,self.tokenstrip(linetok[2:]))
self.macros[name.value] = m
elif mtype.value == '(':
# A macro with arguments
tokcount, args, positions = self.collect_args(linetok[1:])
variadic = False
for a in args:
if variadic:
print("No more arguments may follow a variadic argument")
break
astr = "".join([str(_i.value) for _i in a])
if astr == "...":
variadic = True
a[0].type = self.t_ID
a[0].value = '__VA_ARGS__'
variadic = True
del a[1:]
continue
elif astr[-3:] == "..." and a[0].type == self.t_ID:
variadic = True
del a[1:]
# If, for some reason, "." is part of the identifier, strip off the name for the purposes
# of macro expansion
if a[0].value[-3:] == '...':
a[0].value = a[0].value[:-3]
continue
if len(a) > 1 or a[0].type != self.t_ID:
print("Invalid macro argument")
break
else:
mvalue = self.tokenstrip(linetok[1+tokcount:])
i = 0
while i < len(mvalue):
if i+1 < len(mvalue):
if mvalue[i].type in self.t_WS and mvalue[i+1].value == '##':
del mvalue[i]
continue
elif mvalue[i].value == '##' and mvalue[i+1].type in self.t_WS:
del mvalue[i+1]
i += 1
m = Macro(name.value,mvalue,[x[0].value for x in args],variadic)
self.macro_prescan(m)
self.macros[name.value] = m
else:
print("Bad macro definition")
except LookupError:
print("Bad macro definition")
# ----------------------------------------------------------------------
# undef()
#
# Undefine a macro
# ----------------------------------------------------------------------
def undef(self,tokens):
id = tokens[0].value
try:
del self.macros[id]
except LookupError:
pass
# ----------------------------------------------------------------------
# parse()
#
# Parse input text.
# ----------------------------------------------------------------------
def parse(self,input,source=None,ignore={}):
self.ignore = ignore
self.parser = self.parsegen(input,source)
# ----------------------------------------------------------------------
# token()
#
# Method to return individual tokens
# ----------------------------------------------------------------------
def token(self):
try:
while True:
tok = next(self.parser)
if tok.type not in self.ignore: return tok
except StopIteration:
self.parser = None
return None
if __name__ == '__main__':
import ply.lex as lex
lexer = lex.lex()
# Run a preprocessor
import sys
f = open(sys.argv[1])
input = f.read()
p = Preprocessor(lexer)
p.parse(input,sys.argv[1])
while True:
tok = p.token()
if not tok: break
print(p.source, tok)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/ply/cpp.py | Python | apache-2.0 | 33,282 |
# ----------------------------------------------------------------------
# ctokens.py
#
# Token specifications for symbols in ANSI C and C++. This file is
# meant to be used as a library in other tokenizers.
# ----------------------------------------------------------------------
# Reserved words
tokens = [
# Literals (identifier, integer constant, float constant, string constant, char const)
'ID', 'TYPEID', 'INTEGER', 'FLOAT', 'STRING', 'CHARACTER',
# Operators (+,-,*,/,%,|,&,~,^,<<,>>, ||, &&, !, <, <=, >, >=, ==, !=)
'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MODULO',
'OR', 'AND', 'NOT', 'XOR', 'LSHIFT', 'RSHIFT',
'LOR', 'LAND', 'LNOT',
'LT', 'LE', 'GT', 'GE', 'EQ', 'NE',
# Assignment (=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=)
'EQUALS', 'TIMESEQUAL', 'DIVEQUAL', 'MODEQUAL', 'PLUSEQUAL', 'MINUSEQUAL',
'LSHIFTEQUAL','RSHIFTEQUAL', 'ANDEQUAL', 'XOREQUAL', 'OREQUAL',
# Increment/decrement (++,--)
'INCREMENT', 'DECREMENT',
# Structure dereference (->)
'ARROW',
# Ternary operator (?)
'TERNARY',
# Delimeters ( ) [ ] { } , . ; :
'LPAREN', 'RPAREN',
'LBRACKET', 'RBRACKET',
'LBRACE', 'RBRACE',
'COMMA', 'PERIOD', 'SEMI', 'COLON',
# Ellipsis (...)
'ELLIPSIS',
]
# Operators
t_PLUS = r'\+'
t_MINUS = r'-'
t_TIMES = r'\*'
t_DIVIDE = r'/'
t_MODULO = r'%'
t_OR = r'\|'
t_AND = r'&'
t_NOT = r'~'
t_XOR = r'\^'
t_LSHIFT = r'<<'
t_RSHIFT = r'>>'
t_LOR = r'\|\|'
t_LAND = r'&&'
t_LNOT = r'!'
t_LT = r'<'
t_GT = r'>'
t_LE = r'<='
t_GE = r'>='
t_EQ = r'=='
t_NE = r'!='
# Assignment operators
t_EQUALS = r'='
t_TIMESEQUAL = r'\*='
t_DIVEQUAL = r'/='
t_MODEQUAL = r'%='
t_PLUSEQUAL = r'\+='
t_MINUSEQUAL = r'-='
t_LSHIFTEQUAL = r'<<='
t_RSHIFTEQUAL = r'>>='
t_ANDEQUAL = r'&='
t_OREQUAL = r'\|='
t_XOREQUAL = r'\^='
# Increment/decrement
t_INCREMENT = r'\+\+'
t_DECREMENT = r'--'
# ->
t_ARROW = r'->'
# ?
t_TERNARY = r'\?'
# Delimeters
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_LBRACKET = r'\['
t_RBRACKET = r'\]'
t_LBRACE = r'\{'
t_RBRACE = r'\}'
t_COMMA = r','
t_PERIOD = r'\.'
t_SEMI = r';'
t_COLON = r':'
t_ELLIPSIS = r'\.\.\.'
# Identifiers
t_ID = r'[A-Za-z_][A-Za-z0-9_]*'
# Integer literal
t_INTEGER = r'\d+([uU]|[lL]|[uU][lL]|[lL][uU])?'
# Floating literal
t_FLOAT = r'((\d+)(\.\d+)(e(\+|-)?(\d+))? | (\d+)e(\+|-)?(\d+))([lL]|[fF])?'
# String literal
t_STRING = r'\"([^\\\n]|(\\.))*?\"'
# Character constant 'c' or L'c'
t_CHARACTER = r'(L)?\'([^\\\n]|(\\.))*?\''
# Comment (C-Style)
def t_COMMENT(t):
r'/\*(.|\n)*?\*/'
t.lexer.lineno += t.value.count('\n')
return t
# Comment (C++-Style)
def t_CPPCOMMENT(t):
r'//.*\n'
t.lexer.lineno += 1
return t
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/ply/ctokens.py | Python | apache-2.0 | 3,177 |
# -----------------------------------------------------------------------------
# ply: lex.py
#
# Copyright (C) 2001-2017
# David M. Beazley (Dabeaz LLC)
# 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 the David Beazley or Dabeaz LLC 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.
# -----------------------------------------------------------------------------
__version__ = '3.10'
__tabversion__ = '3.10'
import re
import sys
import types
import copy
import os
import inspect
# This tuple contains known string types
try:
# Python 2.6
StringTypes = (types.StringType, types.UnicodeType)
except AttributeError:
# Python 3.0
StringTypes = (str, bytes)
# This regular expression is used to match valid token names
_is_identifier = re.compile(r'^[a-zA-Z0-9_]+$')
# Exception thrown when invalid token encountered and no default error
# handler is defined.
class LexError(Exception):
def __init__(self, message, s):
self.args = (message,)
self.text = s
# Token class. This class is used to represent the tokens produced.
class LexToken(object):
def __str__(self):
return 'LexToken(%s,%r,%d,%d)' % (self.type, self.value, self.lineno, self.lexpos)
def __repr__(self):
return str(self)
# This object is a stand-in for a logging object created by the
# logging module.
class PlyLogger(object):
def __init__(self, f):
self.f = f
def critical(self, msg, *args, **kwargs):
self.f.write((msg % args) + '\n')
def warning(self, msg, *args, **kwargs):
self.f.write('WARNING: ' + (msg % args) + '\n')
def error(self, msg, *args, **kwargs):
self.f.write('ERROR: ' + (msg % args) + '\n')
info = critical
debug = critical
# Null logger is used when no output is generated. Does nothing.
class NullLogger(object):
def __getattribute__(self, name):
return self
def __call__(self, *args, **kwargs):
return self
# -----------------------------------------------------------------------------
# === Lexing Engine ===
#
# The following Lexer class implements the lexer runtime. There are only
# a few public methods and attributes:
#
# input() - Store a new string in the lexer
# token() - Get the next token
# clone() - Clone the lexer
#
# lineno - Current line number
# lexpos - Current position in the input string
# -----------------------------------------------------------------------------
class Lexer:
def __init__(self):
self.lexre = None # Master regular expression. This is a list of
# tuples (re, findex) where re is a compiled
# regular expression and findex is a list
# mapping regex group numbers to rules
self.lexretext = None # Current regular expression strings
self.lexstatere = {} # Dictionary mapping lexer states to master regexs
self.lexstateretext = {} # Dictionary mapping lexer states to regex strings
self.lexstaterenames = {} # Dictionary mapping lexer states to symbol names
self.lexstate = 'INITIAL' # Current lexer state
self.lexstatestack = [] # Stack of lexer states
self.lexstateinfo = None # State information
self.lexstateignore = {} # Dictionary of ignored characters for each state
self.lexstateerrorf = {} # Dictionary of error functions for each state
self.lexstateeoff = {} # Dictionary of eof functions for each state
self.lexreflags = 0 # Optional re compile flags
self.lexdata = None # Actual input data (as a string)
self.lexpos = 0 # Current position in input text
self.lexlen = 0 # Length of the input text
self.lexerrorf = None # Error rule (if any)
self.lexeoff = None # EOF rule (if any)
self.lextokens = None # List of valid tokens
self.lexignore = '' # Ignored characters
self.lexliterals = '' # Literal characters that can be passed through
self.lexmodule = None # Module
self.lineno = 1 # Current line number
self.lexoptimize = False # Optimized mode
def clone(self, object=None):
c = copy.copy(self)
# If the object parameter has been supplied, it means we are attaching the
# lexer to a new object. In this case, we have to rebind all methods in
# the lexstatere and lexstateerrorf tables.
if object:
newtab = {}
for key, ritem in self.lexstatere.items():
newre = []
for cre, findex in ritem:
newfindex = []
for f in findex:
if not f or not f[0]:
newfindex.append(f)
continue
newfindex.append((getattr(object, f[0].__name__), f[1]))
newre.append((cre, newfindex))
newtab[key] = newre
c.lexstatere = newtab
c.lexstateerrorf = {}
for key, ef in self.lexstateerrorf.items():
c.lexstateerrorf[key] = getattr(object, ef.__name__)
c.lexmodule = object
return c
# ------------------------------------------------------------
# writetab() - Write lexer information to a table file
# ------------------------------------------------------------
def writetab(self, lextab, outputdir=''):
if isinstance(lextab, types.ModuleType):
raise IOError("Won't overwrite existing lextab module")
basetabmodule = lextab.split('.')[-1]
filename = os.path.join(outputdir, basetabmodule) + '.py'
with open(filename, 'w') as tf:
tf.write('# %s.py. This file automatically created by PLY (version %s). Don\'t edit!\n' % (basetabmodule, __version__))
tf.write('_tabversion = %s\n' % repr(__tabversion__))
tf.write('_lextokens = set(%s)\n' % repr(tuple(self.lextokens)))
tf.write('_lexreflags = %s\n' % repr(self.lexreflags))
tf.write('_lexliterals = %s\n' % repr(self.lexliterals))
tf.write('_lexstateinfo = %s\n' % repr(self.lexstateinfo))
# Rewrite the lexstatere table, replacing function objects with function names
tabre = {}
for statename, lre in self.lexstatere.items():
titem = []
for (pat, func), retext, renames in zip(lre, self.lexstateretext[statename], self.lexstaterenames[statename]):
titem.append((retext, _funcs_to_names(func, renames)))
tabre[statename] = titem
tf.write('_lexstatere = %s\n' % repr(tabre))
tf.write('_lexstateignore = %s\n' % repr(self.lexstateignore))
taberr = {}
for statename, ef in self.lexstateerrorf.items():
taberr[statename] = ef.__name__ if ef else None
tf.write('_lexstateerrorf = %s\n' % repr(taberr))
tabeof = {}
for statename, ef in self.lexstateeoff.items():
tabeof[statename] = ef.__name__ if ef else None
tf.write('_lexstateeoff = %s\n' % repr(tabeof))
# ------------------------------------------------------------
# readtab() - Read lexer information from a tab file
# ------------------------------------------------------------
def readtab(self, tabfile, fdict):
if isinstance(tabfile, types.ModuleType):
lextab = tabfile
else:
exec('import %s' % tabfile)
lextab = sys.modules[tabfile]
if getattr(lextab, '_tabversion', '0.0') != __tabversion__:
raise ImportError('Inconsistent PLY version')
self.lextokens = lextab._lextokens
self.lexreflags = lextab._lexreflags
self.lexliterals = lextab._lexliterals
self.lextokens_all = self.lextokens | set(self.lexliterals)
self.lexstateinfo = lextab._lexstateinfo
self.lexstateignore = lextab._lexstateignore
self.lexstatere = {}
self.lexstateretext = {}
for statename, lre in lextab._lexstatere.items():
titem = []
txtitem = []
for pat, func_name in lre:
titem.append((re.compile(pat, lextab._lexreflags), _names_to_funcs(func_name, fdict)))
self.lexstatere[statename] = titem
self.lexstateretext[statename] = txtitem
self.lexstateerrorf = {}
for statename, ef in lextab._lexstateerrorf.items():
self.lexstateerrorf[statename] = fdict[ef]
self.lexstateeoff = {}
for statename, ef in lextab._lexstateeoff.items():
self.lexstateeoff[statename] = fdict[ef]
self.begin('INITIAL')
# ------------------------------------------------------------
# input() - Push a new string into the lexer
# ------------------------------------------------------------
def input(self, s):
# Pull off the first character to see if s looks like a string
c = s[:1]
if not isinstance(c, StringTypes):
raise ValueError('Expected a string')
self.lexdata = s
self.lexpos = 0
self.lexlen = len(s)
# ------------------------------------------------------------
# begin() - Changes the lexing state
# ------------------------------------------------------------
def begin(self, state):
if state not in self.lexstatere:
raise ValueError('Undefined state')
self.lexre = self.lexstatere[state]
self.lexretext = self.lexstateretext[state]
self.lexignore = self.lexstateignore.get(state, '')
self.lexerrorf = self.lexstateerrorf.get(state, None)
self.lexeoff = self.lexstateeoff.get(state, None)
self.lexstate = state
# ------------------------------------------------------------
# push_state() - Changes the lexing state and saves old on stack
# ------------------------------------------------------------
def push_state(self, state):
self.lexstatestack.append(self.lexstate)
self.begin(state)
# ------------------------------------------------------------
# pop_state() - Restores the previous state
# ------------------------------------------------------------
def pop_state(self):
self.begin(self.lexstatestack.pop())
# ------------------------------------------------------------
# current_state() - Returns the current lexing state
# ------------------------------------------------------------
def current_state(self):
return self.lexstate
# ------------------------------------------------------------
# skip() - Skip ahead n characters
# ------------------------------------------------------------
def skip(self, n):
self.lexpos += n
# ------------------------------------------------------------
# opttoken() - Return the next token from the Lexer
#
# Note: This function has been carefully implemented to be as fast
# as possible. Don't make changes unless you really know what
# you are doing
# ------------------------------------------------------------
def token(self):
# Make local copies of frequently referenced attributes
lexpos = self.lexpos
lexlen = self.lexlen
lexignore = self.lexignore
lexdata = self.lexdata
while lexpos < lexlen:
# This code provides some short-circuit code for whitespace, tabs, and other ignored characters
if lexdata[lexpos] in lexignore:
lexpos += 1
continue
# Look for a regular expression match
for lexre, lexindexfunc in self.lexre:
m = lexre.match(lexdata, lexpos)
if not m:
continue
# Create a token for return
tok = LexToken()
tok.value = m.group()
tok.lineno = self.lineno
tok.lexpos = lexpos
i = m.lastindex
func, tok.type = lexindexfunc[i]
if not func:
# If no token type was set, it's an ignored token
if tok.type:
self.lexpos = m.end()
return tok
else:
lexpos = m.end()
break
lexpos = m.end()
# If token is processed by a function, call it
tok.lexer = self # Set additional attributes useful in token rules
self.lexmatch = m
self.lexpos = lexpos
newtok = func(tok)
# Every function must return a token, if nothing, we just move to next token
if not newtok:
lexpos = self.lexpos # This is here in case user has updated lexpos.
lexignore = self.lexignore # This is here in case there was a state change
break
# Verify type of the token. If not in the token map, raise an error
if not self.lexoptimize:
if newtok.type not in self.lextokens_all:
raise LexError("%s:%d: Rule '%s' returned an unknown token type '%s'" % (
func.__code__.co_filename, func.__code__.co_firstlineno,
func.__name__, newtok.type), lexdata[lexpos:])
return newtok
else:
# No match, see if in literals
if lexdata[lexpos] in self.lexliterals:
tok = LexToken()
tok.value = lexdata[lexpos]
tok.lineno = self.lineno
tok.type = tok.value
tok.lexpos = lexpos
self.lexpos = lexpos + 1
return tok
# No match. Call t_error() if defined.
if self.lexerrorf:
tok = LexToken()
tok.value = self.lexdata[lexpos:]
tok.lineno = self.lineno
tok.type = 'error'
tok.lexer = self
tok.lexpos = lexpos
self.lexpos = lexpos
newtok = self.lexerrorf(tok)
if lexpos == self.lexpos:
# Error method didn't change text position at all. This is an error.
raise LexError("Scanning error. Illegal character '%s'" % (lexdata[lexpos]), lexdata[lexpos:])
lexpos = self.lexpos
if not newtok:
continue
return newtok
self.lexpos = lexpos
raise LexError("Illegal character '%s' at index %d" % (lexdata[lexpos], lexpos), lexdata[lexpos:])
if self.lexeoff:
tok = LexToken()
tok.type = 'eof'
tok.value = ''
tok.lineno = self.lineno
tok.lexpos = lexpos
tok.lexer = self
self.lexpos = lexpos
newtok = self.lexeoff(tok)
return newtok
self.lexpos = lexpos + 1
if self.lexdata is None:
raise RuntimeError('No input string given with input()')
return None
# Iterator interface
def __iter__(self):
return self
def next(self):
t = self.token()
if t is None:
raise StopIteration
return t
__next__ = next
# -----------------------------------------------------------------------------
# ==== Lex Builder ===
#
# The functions and classes below are used to collect lexing information
# and build a Lexer object from it.
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# _get_regex(func)
#
# Returns the regular expression assigned to a function either as a doc string
# or as a .regex attribute attached by the @TOKEN decorator.
# -----------------------------------------------------------------------------
def _get_regex(func):
return getattr(func, 'regex', func.__doc__)
# -----------------------------------------------------------------------------
# get_caller_module_dict()
#
# This function returns a dictionary containing all of the symbols defined within
# a caller further down the call stack. This is used to get the environment
# associated with the yacc() call if none was provided.
# -----------------------------------------------------------------------------
def get_caller_module_dict(levels):
f = sys._getframe(levels)
ldict = f.f_globals.copy()
if f.f_globals != f.f_locals:
ldict.update(f.f_locals)
return ldict
# -----------------------------------------------------------------------------
# _funcs_to_names()
#
# Given a list of regular expression functions, this converts it to a list
# suitable for output to a table file
# -----------------------------------------------------------------------------
def _funcs_to_names(funclist, namelist):
result = []
for f, name in zip(funclist, namelist):
if f and f[0]:
result.append((name, f[1]))
else:
result.append(f)
return result
# -----------------------------------------------------------------------------
# _names_to_funcs()
#
# Given a list of regular expression function names, this converts it back to
# functions.
# -----------------------------------------------------------------------------
def _names_to_funcs(namelist, fdict):
result = []
for n in namelist:
if n and n[0]:
result.append((fdict[n[0]], n[1]))
else:
result.append(n)
return result
# -----------------------------------------------------------------------------
# _form_master_re()
#
# This function takes a list of all of the regex components and attempts to
# form the master regular expression. Given limitations in the Python re
# module, it may be necessary to break the master regex into separate expressions.
# -----------------------------------------------------------------------------
def _form_master_re(relist, reflags, ldict, toknames):
if not relist:
return []
regex = '|'.join(relist)
try:
lexre = re.compile(regex, reflags)
# Build the index to function map for the matching engine
lexindexfunc = [None] * (max(lexre.groupindex.values()) + 1)
lexindexnames = lexindexfunc[:]
for f, i in lexre.groupindex.items():
handle = ldict.get(f, None)
if type(handle) in (types.FunctionType, types.MethodType):
lexindexfunc[i] = (handle, toknames[f])
lexindexnames[i] = f
elif handle is not None:
lexindexnames[i] = f
if f.find('ignore_') > 0:
lexindexfunc[i] = (None, None)
else:
lexindexfunc[i] = (None, toknames[f])
return [(lexre, lexindexfunc)], [regex], [lexindexnames]
except Exception:
m = int(len(relist)/2)
if m == 0:
m = 1
llist, lre, lnames = _form_master_re(relist[:m], reflags, ldict, toknames)
rlist, rre, rnames = _form_master_re(relist[m:], reflags, ldict, toknames)
return (llist+rlist), (lre+rre), (lnames+rnames)
# -----------------------------------------------------------------------------
# def _statetoken(s,names)
#
# Given a declaration name s of the form "t_" and a dictionary whose keys are
# state names, this function returns a tuple (states,tokenname) where states
# is a tuple of state names and tokenname is the name of the token. For example,
# calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM')
# -----------------------------------------------------------------------------
def _statetoken(s, names):
nonstate = 1
parts = s.split('_')
for i, part in enumerate(parts[1:], 1):
if part not in names and part != 'ANY':
break
if i > 1:
states = tuple(parts[1:i])
else:
states = ('INITIAL',)
if 'ANY' in states:
states = tuple(names)
tokenname = '_'.join(parts[i:])
return (states, tokenname)
# -----------------------------------------------------------------------------
# LexerReflect()
#
# This class represents information needed to build a lexer as extracted from a
# user's input file.
# -----------------------------------------------------------------------------
class LexerReflect(object):
def __init__(self, ldict, log=None, reflags=0):
self.ldict = ldict
self.error_func = None
self.tokens = []
self.reflags = reflags
self.stateinfo = {'INITIAL': 'inclusive'}
self.modules = set()
self.error = False
self.log = PlyLogger(sys.stderr) if log is None else log
# Get all of the basic information
def get_all(self):
self.get_tokens()
self.get_literals()
self.get_states()
self.get_rules()
# Validate all of the information
def validate_all(self):
self.validate_tokens()
self.validate_literals()
self.validate_rules()
return self.error
# Get the tokens map
def get_tokens(self):
tokens = self.ldict.get('tokens', None)
if not tokens:
self.log.error('No token list is defined')
self.error = True
return
if not isinstance(tokens, (list, tuple)):
self.log.error('tokens must be a list or tuple')
self.error = True
return
if not tokens:
self.log.error('tokens is empty')
self.error = True
return
self.tokens = tokens
# Validate the tokens
def validate_tokens(self):
terminals = {}
for n in self.tokens:
if not _is_identifier.match(n):
self.log.error("Bad token name '%s'", n)
self.error = True
if n in terminals:
self.log.warning("Token '%s' multiply defined", n)
terminals[n] = 1
# Get the literals specifier
def get_literals(self):
self.literals = self.ldict.get('literals', '')
if not self.literals:
self.literals = ''
# Validate literals
def validate_literals(self):
try:
for c in self.literals:
if not isinstance(c, StringTypes) or len(c) > 1:
self.log.error('Invalid literal %s. Must be a single character', repr(c))
self.error = True
except TypeError:
self.log.error('Invalid literals specification. literals must be a sequence of characters')
self.error = True
def get_states(self):
self.states = self.ldict.get('states', None)
# Build statemap
if self.states:
if not isinstance(self.states, (tuple, list)):
self.log.error('states must be defined as a tuple or list')
self.error = True
else:
for s in self.states:
if not isinstance(s, tuple) or len(s) != 2:
self.log.error("Invalid state specifier %s. Must be a tuple (statename,'exclusive|inclusive')", repr(s))
self.error = True
continue
name, statetype = s
if not isinstance(name, StringTypes):
self.log.error('State name %s must be a string', repr(name))
self.error = True
continue
if not (statetype == 'inclusive' or statetype == 'exclusive'):
self.log.error("State type for state %s must be 'inclusive' or 'exclusive'", name)
self.error = True
continue
if name in self.stateinfo:
self.log.error("State '%s' already defined", name)
self.error = True
continue
self.stateinfo[name] = statetype
# Get all of the symbols with a t_ prefix and sort them into various
# categories (functions, strings, error functions, and ignore characters)
def get_rules(self):
tsymbols = [f for f in self.ldict if f[:2] == 't_']
# Now build up a list of functions and a list of strings
self.toknames = {} # Mapping of symbols to token names
self.funcsym = {} # Symbols defined as functions
self.strsym = {} # Symbols defined as strings
self.ignore = {} # Ignore strings by state
self.errorf = {} # Error functions by state
self.eoff = {} # EOF functions by state
for s in self.stateinfo:
self.funcsym[s] = []
self.strsym[s] = []
if len(tsymbols) == 0:
self.log.error('No rules of the form t_rulename are defined')
self.error = True
return
for f in tsymbols:
t = self.ldict[f]
states, tokname = _statetoken(f, self.stateinfo)
self.toknames[f] = tokname
if hasattr(t, '__call__'):
if tokname == 'error':
for s in states:
self.errorf[s] = t
elif tokname == 'eof':
for s in states:
self.eoff[s] = t
elif tokname == 'ignore':
line = t.__code__.co_firstlineno
file = t.__code__.co_filename
self.log.error("%s:%d: Rule '%s' must be defined as a string", file, line, t.__name__)
self.error = True
else:
for s in states:
self.funcsym[s].append((f, t))
elif isinstance(t, StringTypes):
if tokname == 'ignore':
for s in states:
self.ignore[s] = t
if '\\' in t:
self.log.warning("%s contains a literal backslash '\\'", f)
elif tokname == 'error':
self.log.error("Rule '%s' must be defined as a function", f)
self.error = True
else:
for s in states:
self.strsym[s].append((f, t))
else:
self.log.error('%s not defined as a function or string', f)
self.error = True
# Sort the functions by line number
for f in self.funcsym.values():
f.sort(key=lambda x: x[1].__code__.co_firstlineno)
# Sort the strings by regular expression length
for s in self.strsym.values():
s.sort(key=lambda x: len(x[1]), reverse=True)
# Validate all of the t_rules collected
def validate_rules(self):
for state in self.stateinfo:
# Validate all rules defined by functions
for fname, f in self.funcsym[state]:
line = f.__code__.co_firstlineno
file = f.__code__.co_filename
module = inspect.getmodule(f)
self.modules.add(module)
tokname = self.toknames[fname]
if isinstance(f, types.MethodType):
reqargs = 2
else:
reqargs = 1
nargs = f.__code__.co_argcount
if nargs > reqargs:
self.log.error("%s:%d: Rule '%s' has too many arguments", file, line, f.__name__)
self.error = True
continue
if nargs < reqargs:
self.log.error("%s:%d: Rule '%s' requires an argument", file, line, f.__name__)
self.error = True
continue
if not _get_regex(f):
self.log.error("%s:%d: No regular expression defined for rule '%s'", file, line, f.__name__)
self.error = True
continue
try:
c = re.compile('(?P<%s>%s)' % (fname, _get_regex(f)), self.reflags)
if c.match(''):
self.log.error("%s:%d: Regular expression for rule '%s' matches empty string", file, line, f.__name__)
self.error = True
except re.error as e:
self.log.error("%s:%d: Invalid regular expression for rule '%s'. %s", file, line, f.__name__, e)
if '#' in _get_regex(f):
self.log.error("%s:%d. Make sure '#' in rule '%s' is escaped with '\\#'", file, line, f.__name__)
self.error = True
# Validate all rules defined by strings
for name, r in self.strsym[state]:
tokname = self.toknames[name]
if tokname == 'error':
self.log.error("Rule '%s' must be defined as a function", name)
self.error = True
continue
if tokname not in self.tokens and tokname.find('ignore_') < 0:
self.log.error("Rule '%s' defined for an unspecified token %s", name, tokname)
self.error = True
continue
try:
c = re.compile('(?P<%s>%s)' % (name, r), self.reflags)
if (c.match('')):
self.log.error("Regular expression for rule '%s' matches empty string", name)
self.error = True
except re.error as e:
self.log.error("Invalid regular expression for rule '%s'. %s", name, e)
if '#' in r:
self.log.error("Make sure '#' in rule '%s' is escaped with '\\#'", name)
self.error = True
if not self.funcsym[state] and not self.strsym[state]:
self.log.error("No rules defined for state '%s'", state)
self.error = True
# Validate the error function
efunc = self.errorf.get(state, None)
if efunc:
f = efunc
line = f.__code__.co_firstlineno
file = f.__code__.co_filename
module = inspect.getmodule(f)
self.modules.add(module)
if isinstance(f, types.MethodType):
reqargs = 2
else:
reqargs = 1
nargs = f.__code__.co_argcount
if nargs > reqargs:
self.log.error("%s:%d: Rule '%s' has too many arguments", file, line, f.__name__)
self.error = True
if nargs < reqargs:
self.log.error("%s:%d: Rule '%s' requires an argument", file, line, f.__name__)
self.error = True
for module in self.modules:
self.validate_module(module)
# -----------------------------------------------------------------------------
# validate_module()
#
# This checks to see if there are duplicated t_rulename() functions or strings
# in the parser input file. This is done using a simple regular expression
# match on each line in the source code of the given module.
# -----------------------------------------------------------------------------
def validate_module(self, module):
try:
lines, linen = inspect.getsourcelines(module)
except IOError:
return
fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(')
sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=')
counthash = {}
linen += 1
for line in lines:
m = fre.match(line)
if not m:
m = sre.match(line)
if m:
name = m.group(1)
prev = counthash.get(name)
if not prev:
counthash[name] = linen
else:
filename = inspect.getsourcefile(module)
self.log.error('%s:%d: Rule %s redefined. Previously defined on line %d', filename, linen, name, prev)
self.error = True
linen += 1
# -----------------------------------------------------------------------------
# lex(module)
#
# Build all of the regular expression rules from definitions in the supplied module
# -----------------------------------------------------------------------------
def lex(module=None, object=None, debug=False, optimize=False, lextab='lextab',
reflags=int(re.VERBOSE), nowarn=False, outputdir=None, debuglog=None, errorlog=None):
if lextab is None:
lextab = 'lextab'
global lexer
ldict = None
stateinfo = {'INITIAL': 'inclusive'}
lexobj = Lexer()
lexobj.lexoptimize = optimize
global token, input
if errorlog is None:
errorlog = PlyLogger(sys.stderr)
if debug:
if debuglog is None:
debuglog = PlyLogger(sys.stderr)
# Get the module dictionary used for the lexer
if object:
module = object
# Get the module dictionary used for the parser
if module:
_items = [(k, getattr(module, k)) for k in dir(module)]
ldict = dict(_items)
# If no __file__ attribute is available, try to obtain it from the __module__ instead
if '__file__' not in ldict:
ldict['__file__'] = sys.modules[ldict['__module__']].__file__
else:
ldict = get_caller_module_dict(2)
# Determine if the module is package of a package or not.
# If so, fix the tabmodule setting so that tables load correctly
pkg = ldict.get('__package__')
if pkg and isinstance(lextab, str):
if '.' not in lextab:
lextab = pkg + '.' + lextab
# Collect parser information from the dictionary
linfo = LexerReflect(ldict, log=errorlog, reflags=reflags)
linfo.get_all()
if not optimize:
if linfo.validate_all():
raise SyntaxError("Can't build lexer")
if optimize and lextab:
try:
lexobj.readtab(lextab, ldict)
token = lexobj.token
input = lexobj.input
lexer = lexobj
return lexobj
except ImportError:
pass
# Dump some basic debugging information
if debug:
debuglog.info('lex: tokens = %r', linfo.tokens)
debuglog.info('lex: literals = %r', linfo.literals)
debuglog.info('lex: states = %r', linfo.stateinfo)
# Build a dictionary of valid token names
lexobj.lextokens = set()
for n in linfo.tokens:
lexobj.lextokens.add(n)
# Get literals specification
if isinstance(linfo.literals, (list, tuple)):
lexobj.lexliterals = type(linfo.literals[0])().join(linfo.literals)
else:
lexobj.lexliterals = linfo.literals
lexobj.lextokens_all = lexobj.lextokens | set(lexobj.lexliterals)
# Get the stateinfo dictionary
stateinfo = linfo.stateinfo
regexs = {}
# Build the master regular expressions
for state in stateinfo:
regex_list = []
# Add rules defined by functions first
for fname, f in linfo.funcsym[state]:
line = f.__code__.co_firstlineno
file = f.__code__.co_filename
regex_list.append('(?P<%s>%s)' % (fname, _get_regex(f)))
if debug:
debuglog.info("lex: Adding rule %s -> '%s' (state '%s')", fname, _get_regex(f), state)
# Now add all of the simple rules
for name, r in linfo.strsym[state]:
regex_list.append('(?P<%s>%s)' % (name, r))
if debug:
debuglog.info("lex: Adding rule %s -> '%s' (state '%s')", name, r, state)
regexs[state] = regex_list
# Build the master regular expressions
if debug:
debuglog.info('lex: ==== MASTER REGEXS FOLLOW ====')
for state in regexs:
lexre, re_text, re_names = _form_master_re(regexs[state], reflags, ldict, linfo.toknames)
lexobj.lexstatere[state] = lexre
lexobj.lexstateretext[state] = re_text
lexobj.lexstaterenames[state] = re_names
if debug:
for i, text in enumerate(re_text):
debuglog.info("lex: state '%s' : regex[%d] = '%s'", state, i, text)
# For inclusive states, we need to add the regular expressions from the INITIAL state
for state, stype in stateinfo.items():
if state != 'INITIAL' and stype == 'inclusive':
lexobj.lexstatere[state].extend(lexobj.lexstatere['INITIAL'])
lexobj.lexstateretext[state].extend(lexobj.lexstateretext['INITIAL'])
lexobj.lexstaterenames[state].extend(lexobj.lexstaterenames['INITIAL'])
lexobj.lexstateinfo = stateinfo
lexobj.lexre = lexobj.lexstatere['INITIAL']
lexobj.lexretext = lexobj.lexstateretext['INITIAL']
lexobj.lexreflags = reflags
# Set up ignore variables
lexobj.lexstateignore = linfo.ignore
lexobj.lexignore = lexobj.lexstateignore.get('INITIAL', '')
# Set up error functions
lexobj.lexstateerrorf = linfo.errorf
lexobj.lexerrorf = linfo.errorf.get('INITIAL', None)
if not lexobj.lexerrorf:
errorlog.warning('No t_error rule is defined')
# Set up eof functions
lexobj.lexstateeoff = linfo.eoff
lexobj.lexeoff = linfo.eoff.get('INITIAL', None)
# Check state information for ignore and error rules
for s, stype in stateinfo.items():
if stype == 'exclusive':
if s not in linfo.errorf:
errorlog.warning("No error rule is defined for exclusive state '%s'", s)
if s not in linfo.ignore and lexobj.lexignore:
errorlog.warning("No ignore rule is defined for exclusive state '%s'", s)
elif stype == 'inclusive':
if s not in linfo.errorf:
linfo.errorf[s] = linfo.errorf.get('INITIAL', None)
if s not in linfo.ignore:
linfo.ignore[s] = linfo.ignore.get('INITIAL', '')
# Create global versions of the token() and input() functions
token = lexobj.token
input = lexobj.input
lexer = lexobj
# If in optimize mode, we write the lextab
if lextab and optimize:
if outputdir is None:
# If no output directory is set, the location of the output files
# is determined according to the following rules:
# - If lextab specifies a package, files go into that package directory
# - Otherwise, files go in the same directory as the specifying module
if isinstance(lextab, types.ModuleType):
srcfile = lextab.__file__
else:
if '.' not in lextab:
srcfile = ldict['__file__']
else:
parts = lextab.split('.')
pkgname = '.'.join(parts[:-1])
exec('import %s' % pkgname)
srcfile = getattr(sys.modules[pkgname], '__file__', '')
outputdir = os.path.dirname(srcfile)
try:
lexobj.writetab(lextab, outputdir)
except IOError as e:
errorlog.warning("Couldn't write lextab module %r. %s" % (lextab, e))
return lexobj
# -----------------------------------------------------------------------------
# runmain()
#
# This runs the lexer as a main program
# -----------------------------------------------------------------------------
def runmain(lexer=None, data=None):
if not data:
try:
filename = sys.argv[1]
f = open(filename)
data = f.read()
f.close()
except IndexError:
sys.stdout.write('Reading from standard input (type EOF to end):\n')
data = sys.stdin.read()
if lexer:
_input = lexer.input
else:
_input = input
_input(data)
if lexer:
_token = lexer.token
else:
_token = token
while True:
tok = _token()
if not tok:
break
sys.stdout.write('(%s,%r,%d,%d)\n' % (tok.type, tok.value, tok.lineno, tok.lexpos))
# -----------------------------------------------------------------------------
# @TOKEN(regex)
#
# This decorator function can be used to set the regex expression on a function
# when its docstring might need to be set in an alternative way
# -----------------------------------------------------------------------------
def TOKEN(r):
def set_regex(f):
if hasattr(r, '__call__'):
f.regex = _get_regex(r)
else:
f.regex = r
return f
return set_regex
# Alternative spelling of the TOKEN decorator
Token = TOKEN
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/ply/lex.py | Python | apache-2.0 | 42,918 |
# -----------------------------------------------------------------------------
# ply: yacc.py
#
# Copyright (C) 2001-2017
# David M. Beazley (Dabeaz LLC)
# 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 the David Beazley or Dabeaz LLC 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.
# -----------------------------------------------------------------------------
#
# This implements an LR parser that is constructed from grammar rules defined
# as Python functions. The grammer is specified by supplying the BNF inside
# Python documentation strings. The inspiration for this technique was borrowed
# from John Aycock's Spark parsing system. PLY might be viewed as cross between
# Spark and the GNU bison utility.
#
# The current implementation is only somewhat object-oriented. The
# LR parser itself is defined in terms of an object (which allows multiple
# parsers to co-exist). However, most of the variables used during table
# construction are defined in terms of global variables. Users shouldn't
# notice unless they are trying to define multiple parsers at the same
# time using threads (in which case they should have their head examined).
#
# This implementation supports both SLR and LALR(1) parsing. LALR(1)
# support was originally implemented by Elias Ioup (ezioup@alumni.uchicago.edu),
# using the algorithm found in Aho, Sethi, and Ullman "Compilers: Principles,
# Techniques, and Tools" (The Dragon Book). LALR(1) has since been replaced
# by the more efficient DeRemer and Pennello algorithm.
#
# :::::::: WARNING :::::::
#
# Construction of LR parsing tables is fairly complicated and expensive.
# To make this module run fast, a *LOT* of work has been put into
# optimization---often at the expensive of readability and what might
# consider to be good Python "coding style." Modify the code at your
# own risk!
# ----------------------------------------------------------------------------
import re
import types
import sys
import os.path
import inspect
import base64
import warnings
__version__ = '3.10'
__tabversion__ = '3.10'
#-----------------------------------------------------------------------------
# === User configurable parameters ===
#
# Change these to modify the default behavior of yacc (if you wish)
#-----------------------------------------------------------------------------
yaccdebug = True # Debugging mode. If set, yacc generates a
# a 'parser.out' file in the current directory
debug_file = 'parser.out' # Default name of the debugging file
tab_module = 'parsetab' # Default name of the table module
default_lr = 'LALR' # Default LR table generation method
error_count = 3 # Number of symbols that must be shifted to leave recovery mode
yaccdevel = False # Set to True if developing yacc. This turns off optimized
# implementations of certain functions.
resultlimit = 40 # Size limit of results when running in debug mode.
pickle_protocol = 0 # Protocol to use when writing pickle files
# String type-checking compatibility
if sys.version_info[0] < 3:
string_types = basestring
else:
string_types = str
MAXINT = sys.maxsize
# This object is a stand-in for a logging object created by the
# logging module. PLY will use this by default to create things
# such as the parser.out file. If a user wants more detailed
# information, they can create their own logging object and pass
# it into PLY.
class PlyLogger(object):
def __init__(self, f):
self.f = f
def debug(self, msg, *args, **kwargs):
self.f.write((msg % args) + '\n')
info = debug
def warning(self, msg, *args, **kwargs):
self.f.write('WARNING: ' + (msg % args) + '\n')
def error(self, msg, *args, **kwargs):
self.f.write('ERROR: ' + (msg % args) + '\n')
critical = debug
# Null logger is used when no output is generated. Does nothing.
class NullLogger(object):
def __getattribute__(self, name):
return self
def __call__(self, *args, **kwargs):
return self
# Exception raised for yacc-related errors
class YaccError(Exception):
pass
# Format the result message that the parser produces when running in debug mode.
def format_result(r):
repr_str = repr(r)
if '\n' in repr_str:
repr_str = repr(repr_str)
if len(repr_str) > resultlimit:
repr_str = repr_str[:resultlimit] + ' ...'
result = '<%s @ 0x%x> (%s)' % (type(r).__name__, id(r), repr_str)
return result
# Format stack entries when the parser is running in debug mode
def format_stack_entry(r):
repr_str = repr(r)
if '\n' in repr_str:
repr_str = repr(repr_str)
if len(repr_str) < 16:
return repr_str
else:
return '<%s @ 0x%x>' % (type(r).__name__, id(r))
# Panic mode error recovery support. This feature is being reworked--much of the
# code here is to offer a deprecation/backwards compatible transition
_errok = None
_token = None
_restart = None
_warnmsg = '''PLY: Don't use global functions errok(), token(), and restart() in p_error().
Instead, invoke the methods on the associated parser instance:
def p_error(p):
...
# Use parser.errok(), parser.token(), parser.restart()
...
parser = yacc.yacc()
'''
def errok():
warnings.warn(_warnmsg)
return _errok()
def restart():
warnings.warn(_warnmsg)
return _restart()
def token():
warnings.warn(_warnmsg)
return _token()
# Utility function to call the p_error() function with some deprecation hacks
def call_errorfunc(errorfunc, token, parser):
global _errok, _token, _restart
_errok = parser.errok
_token = parser.token
_restart = parser.restart
r = errorfunc(token)
try:
del _errok, _token, _restart
except NameError:
pass
return r
#-----------------------------------------------------------------------------
# === LR Parsing Engine ===
#
# The following classes are used for the LR parser itself. These are not
# used during table construction and are independent of the actual LR
# table generation algorithm
#-----------------------------------------------------------------------------
# This class is used to hold non-terminal grammar symbols during parsing.
# It normally has the following attributes set:
# .type = Grammar symbol type
# .value = Symbol value
# .lineno = Starting line number
# .endlineno = Ending line number (optional, set automatically)
# .lexpos = Starting lex position
# .endlexpos = Ending lex position (optional, set automatically)
class YaccSymbol:
def __str__(self):
return self.type
def __repr__(self):
return str(self)
# This class is a wrapper around the objects actually passed to each
# grammar rule. Index lookup and assignment actually assign the
# .value attribute of the underlying YaccSymbol object.
# The lineno() method returns the line number of a given
# item (or 0 if not defined). The linespan() method returns
# a tuple of (startline,endline) representing the range of lines
# for a symbol. The lexspan() method returns a tuple (lexpos,endlexpos)
# representing the range of positional information for a symbol.
class YaccProduction:
def __init__(self, s, stack=None):
self.slice = s
self.stack = stack
self.lexer = None
self.parser = None
def __getitem__(self, n):
if isinstance(n, slice):
return [s.value for s in self.slice[n]]
elif n >= 0:
return self.slice[n].value
else:
return self.stack[n].value
def __setitem__(self, n, v):
self.slice[n].value = v
def __getslice__(self, i, j):
return [s.value for s in self.slice[i:j]]
def __len__(self):
return len(self.slice)
def lineno(self, n):
return getattr(self.slice[n], 'lineno', 0)
def set_lineno(self, n, lineno):
self.slice[n].lineno = lineno
def linespan(self, n):
startline = getattr(self.slice[n], 'lineno', 0)
endline = getattr(self.slice[n], 'endlineno', startline)
return startline, endline
def lexpos(self, n):
return getattr(self.slice[n], 'lexpos', 0)
def lexspan(self, n):
startpos = getattr(self.slice[n], 'lexpos', 0)
endpos = getattr(self.slice[n], 'endlexpos', startpos)
return startpos, endpos
def error(self):
raise SyntaxError
# -----------------------------------------------------------------------------
# == LRParser ==
#
# The LR Parsing engine.
# -----------------------------------------------------------------------------
class LRParser:
def __init__(self, lrtab, errorf):
self.productions = lrtab.lr_productions
self.action = lrtab.lr_action
self.goto = lrtab.lr_goto
self.errorfunc = errorf
self.set_defaulted_states()
self.errorok = True
def errok(self):
self.errorok = True
def restart(self):
del self.statestack[:]
del self.symstack[:]
sym = YaccSymbol()
sym.type = '$end'
self.symstack.append(sym)
self.statestack.append(0)
# Defaulted state support.
# This method identifies parser states where there is only one possible reduction action.
# For such states, the parser can make a choose to make a rule reduction without consuming
# the next look-ahead token. This delayed invocation of the tokenizer can be useful in
# certain kinds of advanced parsing situations where the lexer and parser interact with
# each other or change states (i.e., manipulation of scope, lexer states, etc.).
#
# See: https://www.gnu.org/software/bison/manual/html_node/Default-Reductions.html#Default-Reductions
def set_defaulted_states(self):
self.defaulted_states = {}
for state, actions in self.action.items():
rules = list(actions.values())
if len(rules) == 1 and rules[0] < 0:
self.defaulted_states[state] = rules[0]
def disable_defaulted_states(self):
self.defaulted_states = {}
def parse(self, input=None, lexer=None, debug=False, tracking=False, tokenfunc=None):
if debug or yaccdevel:
if isinstance(debug, int):
debug = PlyLogger(sys.stderr)
return self.parsedebug(input, lexer, debug, tracking, tokenfunc)
elif tracking:
return self.parseopt(input, lexer, debug, tracking, tokenfunc)
else:
return self.parseopt_notrack(input, lexer, debug, tracking, tokenfunc)
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# parsedebug().
#
# This is the debugging enabled version of parse(). All changes made to the
# parsing engine should be made here. Optimized versions of this function
# are automatically created by the ply/ygen.py script. This script cuts out
# sections enclosed in markers such as this:
#
# #--! DEBUG
# statements
# #--! DEBUG
#
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
def parsedebug(self, input=None, lexer=None, debug=False, tracking=False, tokenfunc=None):
#--! parsedebug-start
lookahead = None # Current lookahead symbol
lookaheadstack = [] # Stack of lookahead symbols
actions = self.action # Local reference to action table (to avoid lookup on self.)
goto = self.goto # Local reference to goto table (to avoid lookup on self.)
prod = self.productions # Local reference to production list (to avoid lookup on self.)
defaulted_states = self.defaulted_states # Local reference to defaulted states
pslice = YaccProduction(None) # Production object passed to grammar rules
errorcount = 0 # Used during error recovery
#--! DEBUG
debug.info('PLY: PARSE DEBUG START')
#--! DEBUG
# If no lexer was given, we will try to use the lex module
if not lexer:
from . import lex
lexer = lex.lexer
# Set up the lexer and parser objects on pslice
pslice.lexer = lexer
pslice.parser = self
# If input was supplied, pass to lexer
if input is not None:
lexer.input(input)
if tokenfunc is None:
# Tokenize function
get_token = lexer.token
else:
get_token = tokenfunc
# Set the parser() token method (sometimes used in error recovery)
self.token = get_token
# Set up the state and symbol stacks
statestack = [] # Stack of parsing states
self.statestack = statestack
symstack = [] # Stack of grammar symbols
self.symstack = symstack
pslice.stack = symstack # Put in the production
errtoken = None # Err token
# The start state is assumed to be (0,$end)
statestack.append(0)
sym = YaccSymbol()
sym.type = '$end'
symstack.append(sym)
state = 0
while True:
# Get the next symbol on the input. If a lookahead symbol
# is already set, we just use that. Otherwise, we'll pull
# the next token off of the lookaheadstack or from the lexer
#--! DEBUG
debug.debug('')
debug.debug('State : %s', state)
#--! DEBUG
if state not in defaulted_states:
if not lookahead:
if not lookaheadstack:
lookahead = get_token() # Get the next token
else:
lookahead = lookaheadstack.pop()
if not lookahead:
lookahead = YaccSymbol()
lookahead.type = '$end'
# Check the action table
ltype = lookahead.type
t = actions[state].get(ltype)
else:
t = defaulted_states[state]
#--! DEBUG
debug.debug('Defaulted state %s: Reduce using %d', state, -t)
#--! DEBUG
#--! DEBUG
debug.debug('Stack : %s',
('%s . %s' % (' '.join([xx.type for xx in symstack][1:]), str(lookahead))).lstrip())
#--! DEBUG
if t is not None:
if t > 0:
# shift a symbol on the stack
statestack.append(t)
state = t
#--! DEBUG
debug.debug('Action : Shift and goto state %s', t)
#--! DEBUG
symstack.append(lookahead)
lookahead = None
# Decrease error count on successful shift
if errorcount:
errorcount -= 1
continue
if t < 0:
# reduce a symbol on the stack, emit a production
p = prod[-t]
pname = p.name
plen = p.len
# Get production function
sym = YaccSymbol()
sym.type = pname # Production name
sym.value = None
#--! DEBUG
if plen:
debug.info('Action : Reduce rule [%s] with %s and goto state %d', p.str,
'['+','.join([format_stack_entry(_v.value) for _v in symstack[-plen:]])+']',
goto[statestack[-1-plen]][pname])
else:
debug.info('Action : Reduce rule [%s] with %s and goto state %d', p.str, [],
goto[statestack[-1]][pname])
#--! DEBUG
if plen:
targ = symstack[-plen-1:]
targ[0] = sym
#--! TRACKING
if tracking:
t1 = targ[1]
sym.lineno = t1.lineno
sym.lexpos = t1.lexpos
t1 = targ[-1]
sym.endlineno = getattr(t1, 'endlineno', t1.lineno)
sym.endlexpos = getattr(t1, 'endlexpos', t1.lexpos)
#--! TRACKING
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# The code enclosed in this section is duplicated
# below as a performance optimization. Make sure
# changes get made in both locations.
pslice.slice = targ
try:
# Call the grammar rule with our special slice object
del symstack[-plen:]
self.state = state
p.callable(pslice)
del statestack[-plen:]
#--! DEBUG
debug.info('Result : %s', format_result(pslice[0]))
#--! DEBUG
symstack.append(sym)
state = goto[statestack[-1]][pname]
statestack.append(state)
except SyntaxError:
# If an error was set. Enter error recovery state
lookaheadstack.append(lookahead) # Save the current lookahead token
symstack.extend(targ[1:-1]) # Put the production slice back on the stack
statestack.pop() # Pop back one state (before the reduce)
state = statestack[-1]
sym.type = 'error'
sym.value = 'error'
lookahead = sym
errorcount = error_count
self.errorok = False
continue
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
else:
#--! TRACKING
if tracking:
sym.lineno = lexer.lineno
sym.lexpos = lexer.lexpos
#--! TRACKING
targ = [sym]
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# The code enclosed in this section is duplicated
# above as a performance optimization. Make sure
# changes get made in both locations.
pslice.slice = targ
try:
# Call the grammar rule with our special slice object
self.state = state
p.callable(pslice)
#--! DEBUG
debug.info('Result : %s', format_result(pslice[0]))
#--! DEBUG
symstack.append(sym)
state = goto[statestack[-1]][pname]
statestack.append(state)
except SyntaxError:
# If an error was set. Enter error recovery state
lookaheadstack.append(lookahead) # Save the current lookahead token
statestack.pop() # Pop back one state (before the reduce)
state = statestack[-1]
sym.type = 'error'
sym.value = 'error'
lookahead = sym
errorcount = error_count
self.errorok = False
continue
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if t == 0:
n = symstack[-1]
result = getattr(n, 'value', None)
#--! DEBUG
debug.info('Done : Returning %s', format_result(result))
debug.info('PLY: PARSE DEBUG END')
#--! DEBUG
return result
if t is None:
#--! DEBUG
debug.error('Error : %s',
('%s . %s' % (' '.join([xx.type for xx in symstack][1:]), str(lookahead))).lstrip())
#--! DEBUG
# We have some kind of parsing error here. To handle
# this, we are going to push the current token onto
# the tokenstack and replace it with an 'error' token.
# If there are any synchronization rules, they may
# catch it.
#
# In addition to pushing the error token, we call call
# the user defined p_error() function if this is the
# first syntax error. This function is only called if
# errorcount == 0.
if errorcount == 0 or self.errorok:
errorcount = error_count
self.errorok = False
errtoken = lookahead
if errtoken.type == '$end':
errtoken = None # End of file!
if self.errorfunc:
if errtoken and not hasattr(errtoken, 'lexer'):
errtoken.lexer = lexer
self.state = state
tok = call_errorfunc(self.errorfunc, errtoken, self)
if self.errorok:
# User must have done some kind of panic
# mode recovery on their own. The
# returned token is the next lookahead
lookahead = tok
errtoken = None
continue
else:
if errtoken:
if hasattr(errtoken, 'lineno'):
lineno = lookahead.lineno
else:
lineno = 0
if lineno:
sys.stderr.write('yacc: Syntax error at line %d, token=%s\n' % (lineno, errtoken.type))
else:
sys.stderr.write('yacc: Syntax error, token=%s' % errtoken.type)
else:
sys.stderr.write('yacc: Parse error in input. EOF\n')
return
else:
errorcount = error_count
# case 1: the statestack only has 1 entry on it. If we're in this state, the
# entire parse has been rolled back and we're completely hosed. The token is
# discarded and we just keep going.
if len(statestack) <= 1 and lookahead.type != '$end':
lookahead = None
errtoken = None
state = 0
# Nuke the pushback stack
del lookaheadstack[:]
continue
# case 2: the statestack has a couple of entries on it, but we're
# at the end of the file. nuke the top entry and generate an error token
# Start nuking entries on the stack
if lookahead.type == '$end':
# Whoa. We're really hosed here. Bail out
return
if lookahead.type != 'error':
sym = symstack[-1]
if sym.type == 'error':
# Hmmm. Error is on top of stack, we'll just nuke input
# symbol and continue
#--! TRACKING
if tracking:
sym.endlineno = getattr(lookahead, 'lineno', sym.lineno)
sym.endlexpos = getattr(lookahead, 'lexpos', sym.lexpos)
#--! TRACKING
lookahead = None
continue
# Create the error symbol for the first time and make it the new lookahead symbol
t = YaccSymbol()
t.type = 'error'
if hasattr(lookahead, 'lineno'):
t.lineno = t.endlineno = lookahead.lineno
if hasattr(lookahead, 'lexpos'):
t.lexpos = t.endlexpos = lookahead.lexpos
t.value = lookahead
lookaheadstack.append(lookahead)
lookahead = t
else:
sym = symstack.pop()
#--! TRACKING
if tracking:
lookahead.lineno = sym.lineno
lookahead.lexpos = sym.lexpos
#--! TRACKING
statestack.pop()
state = statestack[-1]
continue
# Call an error function here
raise RuntimeError('yacc: internal parser error!!!\n')
#--! parsedebug-end
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# parseopt().
#
# Optimized version of parse() method. DO NOT EDIT THIS CODE DIRECTLY!
# This code is automatically generated by the ply/ygen.py script. Make
# changes to the parsedebug() method instead.
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
def parseopt(self, input=None, lexer=None, debug=False, tracking=False, tokenfunc=None):
#--! parseopt-start
lookahead = None # Current lookahead symbol
lookaheadstack = [] # Stack of lookahead symbols
actions = self.action # Local reference to action table (to avoid lookup on self.)
goto = self.goto # Local reference to goto table (to avoid lookup on self.)
prod = self.productions # Local reference to production list (to avoid lookup on self.)
defaulted_states = self.defaulted_states # Local reference to defaulted states
pslice = YaccProduction(None) # Production object passed to grammar rules
errorcount = 0 # Used during error recovery
# If no lexer was given, we will try to use the lex module
if not lexer:
from . import lex
lexer = lex.lexer
# Set up the lexer and parser objects on pslice
pslice.lexer = lexer
pslice.parser = self
# If input was supplied, pass to lexer
if input is not None:
lexer.input(input)
if tokenfunc is None:
# Tokenize function
get_token = lexer.token
else:
get_token = tokenfunc
# Set the parser() token method (sometimes used in error recovery)
self.token = get_token
# Set up the state and symbol stacks
statestack = [] # Stack of parsing states
self.statestack = statestack
symstack = [] # Stack of grammar symbols
self.symstack = symstack
pslice.stack = symstack # Put in the production
errtoken = None # Err token
# The start state is assumed to be (0,$end)
statestack.append(0)
sym = YaccSymbol()
sym.type = '$end'
symstack.append(sym)
state = 0
while True:
# Get the next symbol on the input. If a lookahead symbol
# is already set, we just use that. Otherwise, we'll pull
# the next token off of the lookaheadstack or from the lexer
if state not in defaulted_states:
if not lookahead:
if not lookaheadstack:
lookahead = get_token() # Get the next token
else:
lookahead = lookaheadstack.pop()
if not lookahead:
lookahead = YaccSymbol()
lookahead.type = '$end'
# Check the action table
ltype = lookahead.type
t = actions[state].get(ltype)
else:
t = defaulted_states[state]
if t is not None:
if t > 0:
# shift a symbol on the stack
statestack.append(t)
state = t
symstack.append(lookahead)
lookahead = None
# Decrease error count on successful shift
if errorcount:
errorcount -= 1
continue
if t < 0:
# reduce a symbol on the stack, emit a production
p = prod[-t]
pname = p.name
plen = p.len
# Get production function
sym = YaccSymbol()
sym.type = pname # Production name
sym.value = None
if plen:
targ = symstack[-plen-1:]
targ[0] = sym
#--! TRACKING
if tracking:
t1 = targ[1]
sym.lineno = t1.lineno
sym.lexpos = t1.lexpos
t1 = targ[-1]
sym.endlineno = getattr(t1, 'endlineno', t1.lineno)
sym.endlexpos = getattr(t1, 'endlexpos', t1.lexpos)
#--! TRACKING
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# The code enclosed in this section is duplicated
# below as a performance optimization. Make sure
# changes get made in both locations.
pslice.slice = targ
try:
# Call the grammar rule with our special slice object
del symstack[-plen:]
self.state = state
p.callable(pslice)
del statestack[-plen:]
symstack.append(sym)
state = goto[statestack[-1]][pname]
statestack.append(state)
except SyntaxError:
# If an error was set. Enter error recovery state
lookaheadstack.append(lookahead) # Save the current lookahead token
symstack.extend(targ[1:-1]) # Put the production slice back on the stack
statestack.pop() # Pop back one state (before the reduce)
state = statestack[-1]
sym.type = 'error'
sym.value = 'error'
lookahead = sym
errorcount = error_count
self.errorok = False
continue
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
else:
#--! TRACKING
if tracking:
sym.lineno = lexer.lineno
sym.lexpos = lexer.lexpos
#--! TRACKING
targ = [sym]
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# The code enclosed in this section is duplicated
# above as a performance optimization. Make sure
# changes get made in both locations.
pslice.slice = targ
try:
# Call the grammar rule with our special slice object
self.state = state
p.callable(pslice)
symstack.append(sym)
state = goto[statestack[-1]][pname]
statestack.append(state)
except SyntaxError:
# If an error was set. Enter error recovery state
lookaheadstack.append(lookahead) # Save the current lookahead token
statestack.pop() # Pop back one state (before the reduce)
state = statestack[-1]
sym.type = 'error'
sym.value = 'error'
lookahead = sym
errorcount = error_count
self.errorok = False
continue
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if t == 0:
n = symstack[-1]
result = getattr(n, 'value', None)
return result
if t is None:
# We have some kind of parsing error here. To handle
# this, we are going to push the current token onto
# the tokenstack and replace it with an 'error' token.
# If there are any synchronization rules, they may
# catch it.
#
# In addition to pushing the error token, we call call
# the user defined p_error() function if this is the
# first syntax error. This function is only called if
# errorcount == 0.
if errorcount == 0 or self.errorok:
errorcount = error_count
self.errorok = False
errtoken = lookahead
if errtoken.type == '$end':
errtoken = None # End of file!
if self.errorfunc:
if errtoken and not hasattr(errtoken, 'lexer'):
errtoken.lexer = lexer
self.state = state
tok = call_errorfunc(self.errorfunc, errtoken, self)
if self.errorok:
# User must have done some kind of panic
# mode recovery on their own. The
# returned token is the next lookahead
lookahead = tok
errtoken = None
continue
else:
if errtoken:
if hasattr(errtoken, 'lineno'):
lineno = lookahead.lineno
else:
lineno = 0
if lineno:
sys.stderr.write('yacc: Syntax error at line %d, token=%s\n' % (lineno, errtoken.type))
else:
sys.stderr.write('yacc: Syntax error, token=%s' % errtoken.type)
else:
sys.stderr.write('yacc: Parse error in input. EOF\n')
return
else:
errorcount = error_count
# case 1: the statestack only has 1 entry on it. If we're in this state, the
# entire parse has been rolled back and we're completely hosed. The token is
# discarded and we just keep going.
if len(statestack) <= 1 and lookahead.type != '$end':
lookahead = None
errtoken = None
state = 0
# Nuke the pushback stack
del lookaheadstack[:]
continue
# case 2: the statestack has a couple of entries on it, but we're
# at the end of the file. nuke the top entry and generate an error token
# Start nuking entries on the stack
if lookahead.type == '$end':
# Whoa. We're really hosed here. Bail out
return
if lookahead.type != 'error':
sym = symstack[-1]
if sym.type == 'error':
# Hmmm. Error is on top of stack, we'll just nuke input
# symbol and continue
#--! TRACKING
if tracking:
sym.endlineno = getattr(lookahead, 'lineno', sym.lineno)
sym.endlexpos = getattr(lookahead, 'lexpos', sym.lexpos)
#--! TRACKING
lookahead = None
continue
# Create the error symbol for the first time and make it the new lookahead symbol
t = YaccSymbol()
t.type = 'error'
if hasattr(lookahead, 'lineno'):
t.lineno = t.endlineno = lookahead.lineno
if hasattr(lookahead, 'lexpos'):
t.lexpos = t.endlexpos = lookahead.lexpos
t.value = lookahead
lookaheadstack.append(lookahead)
lookahead = t
else:
sym = symstack.pop()
#--! TRACKING
if tracking:
lookahead.lineno = sym.lineno
lookahead.lexpos = sym.lexpos
#--! TRACKING
statestack.pop()
state = statestack[-1]
continue
# Call an error function here
raise RuntimeError('yacc: internal parser error!!!\n')
#--! parseopt-end
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# parseopt_notrack().
#
# Optimized version of parseopt() with line number tracking removed.
# DO NOT EDIT THIS CODE DIRECTLY. This code is automatically generated
# by the ply/ygen.py script. Make changes to the parsedebug() method instead.
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
def parseopt_notrack(self, input=None, lexer=None, debug=False, tracking=False, tokenfunc=None):
#--! parseopt-notrack-start
lookahead = None # Current lookahead symbol
lookaheadstack = [] # Stack of lookahead symbols
actions = self.action # Local reference to action table (to avoid lookup on self.)
goto = self.goto # Local reference to goto table (to avoid lookup on self.)
prod = self.productions # Local reference to production list (to avoid lookup on self.)
defaulted_states = self.defaulted_states # Local reference to defaulted states
pslice = YaccProduction(None) # Production object passed to grammar rules
errorcount = 0 # Used during error recovery
# If no lexer was given, we will try to use the lex module
if not lexer:
from . import lex
lexer = lex.lexer
# Set up the lexer and parser objects on pslice
pslice.lexer = lexer
pslice.parser = self
# If input was supplied, pass to lexer
if input is not None:
lexer.input(input)
if tokenfunc is None:
# Tokenize function
get_token = lexer.token
else:
get_token = tokenfunc
# Set the parser() token method (sometimes used in error recovery)
self.token = get_token
# Set up the state and symbol stacks
statestack = [] # Stack of parsing states
self.statestack = statestack
symstack = [] # Stack of grammar symbols
self.symstack = symstack
pslice.stack = symstack # Put in the production
errtoken = None # Err token
# The start state is assumed to be (0,$end)
statestack.append(0)
sym = YaccSymbol()
sym.type = '$end'
symstack.append(sym)
state = 0
while True:
# Get the next symbol on the input. If a lookahead symbol
# is already set, we just use that. Otherwise, we'll pull
# the next token off of the lookaheadstack or from the lexer
if state not in defaulted_states:
if not lookahead:
if not lookaheadstack:
lookahead = get_token() # Get the next token
else:
lookahead = lookaheadstack.pop()
if not lookahead:
lookahead = YaccSymbol()
lookahead.type = '$end'
# Check the action table
ltype = lookahead.type
t = actions[state].get(ltype)
else:
t = defaulted_states[state]
if t is not None:
if t > 0:
# shift a symbol on the stack
statestack.append(t)
state = t
symstack.append(lookahead)
lookahead = None
# Decrease error count on successful shift
if errorcount:
errorcount -= 1
continue
if t < 0:
# reduce a symbol on the stack, emit a production
p = prod[-t]
pname = p.name
plen = p.len
# Get production function
sym = YaccSymbol()
sym.type = pname # Production name
sym.value = None
if plen:
targ = symstack[-plen-1:]
targ[0] = sym
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# The code enclosed in this section is duplicated
# below as a performance optimization. Make sure
# changes get made in both locations.
pslice.slice = targ
try:
# Call the grammar rule with our special slice object
del symstack[-plen:]
self.state = state
p.callable(pslice)
del statestack[-plen:]
symstack.append(sym)
state = goto[statestack[-1]][pname]
statestack.append(state)
except SyntaxError:
# If an error was set. Enter error recovery state
lookaheadstack.append(lookahead) # Save the current lookahead token
symstack.extend(targ[1:-1]) # Put the production slice back on the stack
statestack.pop() # Pop back one state (before the reduce)
state = statestack[-1]
sym.type = 'error'
sym.value = 'error'
lookahead = sym
errorcount = error_count
self.errorok = False
continue
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
else:
targ = [sym]
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# The code enclosed in this section is duplicated
# above as a performance optimization. Make sure
# changes get made in both locations.
pslice.slice = targ
try:
# Call the grammar rule with our special slice object
self.state = state
p.callable(pslice)
symstack.append(sym)
state = goto[statestack[-1]][pname]
statestack.append(state)
except SyntaxError:
# If an error was set. Enter error recovery state
lookaheadstack.append(lookahead) # Save the current lookahead token
statestack.pop() # Pop back one state (before the reduce)
state = statestack[-1]
sym.type = 'error'
sym.value = 'error'
lookahead = sym
errorcount = error_count
self.errorok = False
continue
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if t == 0:
n = symstack[-1]
result = getattr(n, 'value', None)
return result
if t is None:
# We have some kind of parsing error here. To handle
# this, we are going to push the current token onto
# the tokenstack and replace it with an 'error' token.
# If there are any synchronization rules, they may
# catch it.
#
# In addition to pushing the error token, we call call
# the user defined p_error() function if this is the
# first syntax error. This function is only called if
# errorcount == 0.
if errorcount == 0 or self.errorok:
errorcount = error_count
self.errorok = False
errtoken = lookahead
if errtoken.type == '$end':
errtoken = None # End of file!
if self.errorfunc:
if errtoken and not hasattr(errtoken, 'lexer'):
errtoken.lexer = lexer
self.state = state
tok = call_errorfunc(self.errorfunc, errtoken, self)
if self.errorok:
# User must have done some kind of panic
# mode recovery on their own. The
# returned token is the next lookahead
lookahead = tok
errtoken = None
continue
else:
if errtoken:
if hasattr(errtoken, 'lineno'):
lineno = lookahead.lineno
else:
lineno = 0
if lineno:
sys.stderr.write('yacc: Syntax error at line %d, token=%s\n' % (lineno, errtoken.type))
else:
sys.stderr.write('yacc: Syntax error, token=%s' % errtoken.type)
else:
sys.stderr.write('yacc: Parse error in input. EOF\n')
return
else:
errorcount = error_count
# case 1: the statestack only has 1 entry on it. If we're in this state, the
# entire parse has been rolled back and we're completely hosed. The token is
# discarded and we just keep going.
if len(statestack) <= 1 and lookahead.type != '$end':
lookahead = None
errtoken = None
state = 0
# Nuke the pushback stack
del lookaheadstack[:]
continue
# case 2: the statestack has a couple of entries on it, but we're
# at the end of the file. nuke the top entry and generate an error token
# Start nuking entries on the stack
if lookahead.type == '$end':
# Whoa. We're really hosed here. Bail out
return
if lookahead.type != 'error':
sym = symstack[-1]
if sym.type == 'error':
# Hmmm. Error is on top of stack, we'll just nuke input
# symbol and continue
lookahead = None
continue
# Create the error symbol for the first time and make it the new lookahead symbol
t = YaccSymbol()
t.type = 'error'
if hasattr(lookahead, 'lineno'):
t.lineno = t.endlineno = lookahead.lineno
if hasattr(lookahead, 'lexpos'):
t.lexpos = t.endlexpos = lookahead.lexpos
t.value = lookahead
lookaheadstack.append(lookahead)
lookahead = t
else:
sym = symstack.pop()
statestack.pop()
state = statestack[-1]
continue
# Call an error function here
raise RuntimeError('yacc: internal parser error!!!\n')
#--! parseopt-notrack-end
# -----------------------------------------------------------------------------
# === Grammar Representation ===
#
# The following functions, classes, and variables are used to represent and
# manipulate the rules that make up a grammar.
# -----------------------------------------------------------------------------
# regex matching identifiers
_is_identifier = re.compile(r'^[a-zA-Z0-9_-]+$')
# -----------------------------------------------------------------------------
# class Production:
#
# This class stores the raw information about a single production or grammar rule.
# A grammar rule refers to a specification such as this:
#
# expr : expr PLUS term
#
# Here are the basic attributes defined on all productions
#
# name - Name of the production. For example 'expr'
# prod - A list of symbols on the right side ['expr','PLUS','term']
# prec - Production precedence level
# number - Production number.
# func - Function that executes on reduce
# file - File where production function is defined
# lineno - Line number where production function is defined
#
# The following attributes are defined or optional.
#
# len - Length of the production (number of symbols on right hand side)
# usyms - Set of unique symbols found in the production
# -----------------------------------------------------------------------------
class Production(object):
reduced = 0
def __init__(self, number, name, prod, precedence=('right', 0), func=None, file='', line=0):
self.name = name
self.prod = tuple(prod)
self.number = number
self.func = func
self.callable = None
self.file = file
self.line = line
self.prec = precedence
# Internal settings used during table construction
self.len = len(self.prod) # Length of the production
# Create a list of unique production symbols used in the production
self.usyms = []
for s in self.prod:
if s not in self.usyms:
self.usyms.append(s)
# List of all LR items for the production
self.lr_items = []
self.lr_next = None
# Create a string representation
if self.prod:
self.str = '%s -> %s' % (self.name, ' '.join(self.prod))
else:
self.str = '%s -> <empty>' % self.name
def __str__(self):
return self.str
def __repr__(self):
return 'Production(' + str(self) + ')'
def __len__(self):
return len(self.prod)
def __nonzero__(self):
return 1
def __getitem__(self, index):
return self.prod[index]
# Return the nth lr_item from the production (or None if at the end)
def lr_item(self, n):
if n > len(self.prod):
return None
p = LRItem(self, n)
# Precompute the list of productions immediately following.
try:
p.lr_after = Prodnames[p.prod[n+1]]
except (IndexError, KeyError):
p.lr_after = []
try:
p.lr_before = p.prod[n-1]
except IndexError:
p.lr_before = None
return p
# Bind the production function name to a callable
def bind(self, pdict):
if self.func:
self.callable = pdict[self.func]
# This class serves as a minimal standin for Production objects when
# reading table data from files. It only contains information
# actually used by the LR parsing engine, plus some additional
# debugging information.
class MiniProduction(object):
def __init__(self, str, name, len, func, file, line):
self.name = name
self.len = len
self.func = func
self.callable = None
self.file = file
self.line = line
self.str = str
def __str__(self):
return self.str
def __repr__(self):
return 'MiniProduction(%s)' % self.str
# Bind the production function name to a callable
def bind(self, pdict):
if self.func:
self.callable = pdict[self.func]
# -----------------------------------------------------------------------------
# class LRItem
#
# This class represents a specific stage of parsing a production rule. For
# example:
#
# expr : expr . PLUS term
#
# In the above, the "." represents the current location of the parse. Here
# basic attributes:
#
# name - Name of the production. For example 'expr'
# prod - A list of symbols on the right side ['expr','.', 'PLUS','term']
# number - Production number.
#
# lr_next Next LR item. Example, if we are ' expr -> expr . PLUS term'
# then lr_next refers to 'expr -> expr PLUS . term'
# lr_index - LR item index (location of the ".") in the prod list.
# lookaheads - LALR lookahead symbols for this item
# len - Length of the production (number of symbols on right hand side)
# lr_after - List of all productions that immediately follow
# lr_before - Grammar symbol immediately before
# -----------------------------------------------------------------------------
class LRItem(object):
def __init__(self, p, n):
self.name = p.name
self.prod = list(p.prod)
self.number = p.number
self.lr_index = n
self.lookaheads = {}
self.prod.insert(n, '.')
self.prod = tuple(self.prod)
self.len = len(self.prod)
self.usyms = p.usyms
def __str__(self):
if self.prod:
s = '%s -> %s' % (self.name, ' '.join(self.prod))
else:
s = '%s -> <empty>' % self.name
return s
def __repr__(self):
return 'LRItem(' + str(self) + ')'
# -----------------------------------------------------------------------------
# rightmost_terminal()
#
# Return the rightmost terminal from a list of symbols. Used in add_production()
# -----------------------------------------------------------------------------
def rightmost_terminal(symbols, terminals):
i = len(symbols) - 1
while i >= 0:
if symbols[i] in terminals:
return symbols[i]
i -= 1
return None
# -----------------------------------------------------------------------------
# === GRAMMAR CLASS ===
#
# The following class represents the contents of the specified grammar along
# with various computed properties such as first sets, follow sets, LR items, etc.
# This data is used for critical parts of the table generation process later.
# -----------------------------------------------------------------------------
class GrammarError(YaccError):
pass
class Grammar(object):
def __init__(self, terminals):
self.Productions = [None] # A list of all of the productions. The first
# entry is always reserved for the purpose of
# building an augmented grammar
self.Prodnames = {} # A dictionary mapping the names of nonterminals to a list of all
# productions of that nonterminal.
self.Prodmap = {} # A dictionary that is only used to detect duplicate
# productions.
self.Terminals = {} # A dictionary mapping the names of terminal symbols to a
# list of the rules where they are used.
for term in terminals:
self.Terminals[term] = []
self.Terminals['error'] = []
self.Nonterminals = {} # A dictionary mapping names of nonterminals to a list
# of rule numbers where they are used.
self.First = {} # A dictionary of precomputed FIRST(x) symbols
self.Follow = {} # A dictionary of precomputed FOLLOW(x) symbols
self.Precedence = {} # Precedence rules for each terminal. Contains tuples of the
# form ('right',level) or ('nonassoc', level) or ('left',level)
self.UsedPrecedence = set() # Precedence rules that were actually used by the grammer.
# This is only used to provide error checking and to generate
# a warning about unused precedence rules.
self.Start = None # Starting symbol for the grammar
def __len__(self):
return len(self.Productions)
def __getitem__(self, index):
return self.Productions[index]
# -----------------------------------------------------------------------------
# set_precedence()
#
# Sets the precedence for a given terminal. assoc is the associativity such as
# 'left','right', or 'nonassoc'. level is a numeric level.
#
# -----------------------------------------------------------------------------
def set_precedence(self, term, assoc, level):
assert self.Productions == [None], 'Must call set_precedence() before add_production()'
if term in self.Precedence:
raise GrammarError('Precedence already specified for terminal %r' % term)
if assoc not in ['left', 'right', 'nonassoc']:
raise GrammarError("Associativity must be one of 'left','right', or 'nonassoc'")
self.Precedence[term] = (assoc, level)
# -----------------------------------------------------------------------------
# add_production()
#
# Given an action function, this function assembles a production rule and
# computes its precedence level.
#
# The production rule is supplied as a list of symbols. For example,
# a rule such as 'expr : expr PLUS term' has a production name of 'expr' and
# symbols ['expr','PLUS','term'].
#
# Precedence is determined by the precedence of the right-most non-terminal
# or the precedence of a terminal specified by %prec.
#
# A variety of error checks are performed to make sure production symbols
# are valid and that %prec is used correctly.
# -----------------------------------------------------------------------------
def add_production(self, prodname, syms, func=None, file='', line=0):
if prodname in self.Terminals:
raise GrammarError('%s:%d: Illegal rule name %r. Already defined as a token' % (file, line, prodname))
if prodname == 'error':
raise GrammarError('%s:%d: Illegal rule name %r. error is a reserved word' % (file, line, prodname))
if not _is_identifier.match(prodname):
raise GrammarError('%s:%d: Illegal rule name %r' % (file, line, prodname))
# Look for literal tokens
for n, s in enumerate(syms):
if s[0] in "'\"":
try:
c = eval(s)
if (len(c) > 1):
raise GrammarError('%s:%d: Literal token %s in rule %r may only be a single character' %
(file, line, s, prodname))
if c not in self.Terminals:
self.Terminals[c] = []
syms[n] = c
continue
except SyntaxError:
pass
if not _is_identifier.match(s) and s != '%prec':
raise GrammarError('%s:%d: Illegal name %r in rule %r' % (file, line, s, prodname))
# Determine the precedence level
if '%prec' in syms:
if syms[-1] == '%prec':
raise GrammarError('%s:%d: Syntax error. Nothing follows %%prec' % (file, line))
if syms[-2] != '%prec':
raise GrammarError('%s:%d: Syntax error. %%prec can only appear at the end of a grammar rule' %
(file, line))
precname = syms[-1]
prodprec = self.Precedence.get(precname)
if not prodprec:
raise GrammarError('%s:%d: Nothing known about the precedence of %r' % (file, line, precname))
else:
self.UsedPrecedence.add(precname)
del syms[-2:] # Drop %prec from the rule
else:
# If no %prec, precedence is determined by the rightmost terminal symbol
precname = rightmost_terminal(syms, self.Terminals)
prodprec = self.Precedence.get(precname, ('right', 0))
# See if the rule is already in the rulemap
map = '%s -> %s' % (prodname, syms)
if map in self.Prodmap:
m = self.Prodmap[map]
raise GrammarError('%s:%d: Duplicate rule %s. ' % (file, line, m) +
'Previous definition at %s:%d' % (m.file, m.line))
# From this point on, everything is valid. Create a new Production instance
pnumber = len(self.Productions)
if prodname not in self.Nonterminals:
self.Nonterminals[prodname] = []
# Add the production number to Terminals and Nonterminals
for t in syms:
if t in self.Terminals:
self.Terminals[t].append(pnumber)
else:
if t not in self.Nonterminals:
self.Nonterminals[t] = []
self.Nonterminals[t].append(pnumber)
# Create a production and add it to the list of productions
p = Production(pnumber, prodname, syms, prodprec, func, file, line)
self.Productions.append(p)
self.Prodmap[map] = p
# Add to the global productions list
try:
self.Prodnames[prodname].append(p)
except KeyError:
self.Prodnames[prodname] = [p]
# -----------------------------------------------------------------------------
# set_start()
#
# Sets the starting symbol and creates the augmented grammar. Production
# rule 0 is S' -> start where start is the start symbol.
# -----------------------------------------------------------------------------
def set_start(self, start=None):
if not start:
start = self.Productions[1].name
if start not in self.Nonterminals:
raise GrammarError('start symbol %s undefined' % start)
self.Productions[0] = Production(0, "S'", [start])
self.Nonterminals[start].append(0)
self.Start = start
# -----------------------------------------------------------------------------
# find_unreachable()
#
# Find all of the nonterminal symbols that can't be reached from the starting
# symbol. Returns a list of nonterminals that can't be reached.
# -----------------------------------------------------------------------------
def find_unreachable(self):
# Mark all symbols that are reachable from a symbol s
def mark_reachable_from(s):
if s in reachable:
return
reachable.add(s)
for p in self.Prodnames.get(s, []):
for r in p.prod:
mark_reachable_from(r)
reachable = set()
mark_reachable_from(self.Productions[0].prod[0])
return [s for s in self.Nonterminals if s not in reachable]
# -----------------------------------------------------------------------------
# infinite_cycles()
#
# This function looks at the various parsing rules and tries to detect
# infinite recursion cycles (grammar rules where there is no possible way
# to derive a string of only terminals).
# -----------------------------------------------------------------------------
def infinite_cycles(self):
terminates = {}
# Terminals:
for t in self.Terminals:
terminates[t] = True
terminates['$end'] = True
# Nonterminals:
# Initialize to false:
for n in self.Nonterminals:
terminates[n] = False
# Then propagate termination until no change:
while True:
some_change = False
for (n, pl) in self.Prodnames.items():
# Nonterminal n terminates iff any of its productions terminates.
for p in pl:
# Production p terminates iff all of its rhs symbols terminate.
for s in p.prod:
if not terminates[s]:
# The symbol s does not terminate,
# so production p does not terminate.
p_terminates = False
break
else:
# didn't break from the loop,
# so every symbol s terminates
# so production p terminates.
p_terminates = True
if p_terminates:
# symbol n terminates!
if not terminates[n]:
terminates[n] = True
some_change = True
# Don't need to consider any more productions for this n.
break
if not some_change:
break
infinite = []
for (s, term) in terminates.items():
if not term:
if s not in self.Prodnames and s not in self.Terminals and s != 'error':
# s is used-but-not-defined, and we've already warned of that,
# so it would be overkill to say that it's also non-terminating.
pass
else:
infinite.append(s)
return infinite
# -----------------------------------------------------------------------------
# undefined_symbols()
#
# Find all symbols that were used the grammar, but not defined as tokens or
# grammar rules. Returns a list of tuples (sym, prod) where sym in the symbol
# and prod is the production where the symbol was used.
# -----------------------------------------------------------------------------
def undefined_symbols(self):
result = []
for p in self.Productions:
if not p:
continue
for s in p.prod:
if s not in self.Prodnames and s not in self.Terminals and s != 'error':
result.append((s, p))
return result
# -----------------------------------------------------------------------------
# unused_terminals()
#
# Find all terminals that were defined, but not used by the grammar. Returns
# a list of all symbols.
# -----------------------------------------------------------------------------
def unused_terminals(self):
unused_tok = []
for s, v in self.Terminals.items():
if s != 'error' and not v:
unused_tok.append(s)
return unused_tok
# ------------------------------------------------------------------------------
# unused_rules()
#
# Find all grammar rules that were defined, but not used (maybe not reachable)
# Returns a list of productions.
# ------------------------------------------------------------------------------
def unused_rules(self):
unused_prod = []
for s, v in self.Nonterminals.items():
if not v:
p = self.Prodnames[s][0]
unused_prod.append(p)
return unused_prod
# -----------------------------------------------------------------------------
# unused_precedence()
#
# Returns a list of tuples (term,precedence) corresponding to precedence
# rules that were never used by the grammar. term is the name of the terminal
# on which precedence was applied and precedence is a string such as 'left' or
# 'right' corresponding to the type of precedence.
# -----------------------------------------------------------------------------
def unused_precedence(self):
unused = []
for termname in self.Precedence:
if not (termname in self.Terminals or termname in self.UsedPrecedence):
unused.append((termname, self.Precedence[termname][0]))
return unused
# -------------------------------------------------------------------------
# _first()
#
# Compute the value of FIRST1(beta) where beta is a tuple of symbols.
#
# During execution of compute_first1, the result may be incomplete.
# Afterward (e.g., when called from compute_follow()), it will be complete.
# -------------------------------------------------------------------------
def _first(self, beta):
# We are computing First(x1,x2,x3,...,xn)
result = []
for x in beta:
x_produces_empty = False
# Add all the non-<empty> symbols of First[x] to the result.
for f in self.First[x]:
if f == '<empty>':
x_produces_empty = True
else:
if f not in result:
result.append(f)
if x_produces_empty:
# We have to consider the next x in beta,
# i.e. stay in the loop.
pass
else:
# We don't have to consider any further symbols in beta.
break
else:
# There was no 'break' from the loop,
# so x_produces_empty was true for all x in beta,
# so beta produces empty as well.
result.append('<empty>')
return result
# -------------------------------------------------------------------------
# compute_first()
#
# Compute the value of FIRST1(X) for all symbols
# -------------------------------------------------------------------------
def compute_first(self):
if self.First:
return self.First
# Terminals:
for t in self.Terminals:
self.First[t] = [t]
self.First['$end'] = ['$end']
# Nonterminals:
# Initialize to the empty set:
for n in self.Nonterminals:
self.First[n] = []
# Then propagate symbols until no change:
while True:
some_change = False
for n in self.Nonterminals:
for p in self.Prodnames[n]:
for f in self._first(p.prod):
if f not in self.First[n]:
self.First[n].append(f)
some_change = True
if not some_change:
break
return self.First
# ---------------------------------------------------------------------
# compute_follow()
#
# Computes all of the follow sets for every non-terminal symbol. The
# follow set is the set of all symbols that might follow a given
# non-terminal. See the Dragon book, 2nd Ed. p. 189.
# ---------------------------------------------------------------------
def compute_follow(self, start=None):
# If already computed, return the result
if self.Follow:
return self.Follow
# If first sets not computed yet, do that first.
if not self.First:
self.compute_first()
# Add '$end' to the follow list of the start symbol
for k in self.Nonterminals:
self.Follow[k] = []
if not start:
start = self.Productions[1].name
self.Follow[start] = ['$end']
while True:
didadd = False
for p in self.Productions[1:]:
# Here is the production set
for i, B in enumerate(p.prod):
if B in self.Nonterminals:
# Okay. We got a non-terminal in a production
fst = self._first(p.prod[i+1:])
hasempty = False
for f in fst:
if f != '<empty>' and f not in self.Follow[B]:
self.Follow[B].append(f)
didadd = True
if f == '<empty>':
hasempty = True
if hasempty or i == (len(p.prod)-1):
# Add elements of follow(a) to follow(b)
for f in self.Follow[p.name]:
if f not in self.Follow[B]:
self.Follow[B].append(f)
didadd = True
if not didadd:
break
return self.Follow
# -----------------------------------------------------------------------------
# build_lritems()
#
# This function walks the list of productions and builds a complete set of the
# LR items. The LR items are stored in two ways: First, they are uniquely
# numbered and placed in the list _lritems. Second, a linked list of LR items
# is built for each production. For example:
#
# E -> E PLUS E
#
# Creates the list
#
# [E -> . E PLUS E, E -> E . PLUS E, E -> E PLUS . E, E -> E PLUS E . ]
# -----------------------------------------------------------------------------
def build_lritems(self):
for p in self.Productions:
lastlri = p
i = 0
lr_items = []
while True:
if i > len(p):
lri = None
else:
lri = LRItem(p, i)
# Precompute the list of productions immediately following
try:
lri.lr_after = self.Prodnames[lri.prod[i+1]]
except (IndexError, KeyError):
lri.lr_after = []
try:
lri.lr_before = lri.prod[i-1]
except IndexError:
lri.lr_before = None
lastlri.lr_next = lri
if not lri:
break
lr_items.append(lri)
lastlri = lri
i += 1
p.lr_items = lr_items
# -----------------------------------------------------------------------------
# == Class LRTable ==
#
# This basic class represents a basic table of LR parsing information.
# Methods for generating the tables are not defined here. They are defined
# in the derived class LRGeneratedTable.
# -----------------------------------------------------------------------------
class VersionError(YaccError):
pass
class LRTable(object):
def __init__(self):
self.lr_action = None
self.lr_goto = None
self.lr_productions = None
self.lr_method = None
def read_table(self, module):
if isinstance(module, types.ModuleType):
parsetab = module
else:
exec('import %s' % module)
parsetab = sys.modules[module]
if parsetab._tabversion != __tabversion__:
raise VersionError('yacc table file version is out of date')
self.lr_action = parsetab._lr_action
self.lr_goto = parsetab._lr_goto
self.lr_productions = []
for p in parsetab._lr_productions:
self.lr_productions.append(MiniProduction(*p))
self.lr_method = parsetab._lr_method
return parsetab._lr_signature
def read_pickle(self, filename):
try:
import cPickle as pickle
except ImportError:
import pickle
if not os.path.exists(filename):
raise ImportError
in_f = open(filename, 'rb')
tabversion = pickle.load(in_f)
if tabversion != __tabversion__:
raise VersionError('yacc table file version is out of date')
self.lr_method = pickle.load(in_f)
signature = pickle.load(in_f)
self.lr_action = pickle.load(in_f)
self.lr_goto = pickle.load(in_f)
productions = pickle.load(in_f)
self.lr_productions = []
for p in productions:
self.lr_productions.append(MiniProduction(*p))
in_f.close()
return signature
# Bind all production function names to callable objects in pdict
def bind_callables(self, pdict):
for p in self.lr_productions:
p.bind(pdict)
# -----------------------------------------------------------------------------
# === LR Generator ===
#
# The following classes and functions are used to generate LR parsing tables on
# a grammar.
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# digraph()
# traverse()
#
# The following two functions are used to compute set valued functions
# of the form:
#
# F(x) = F'(x) U U{F(y) | x R y}
#
# This is used to compute the values of Read() sets as well as FOLLOW sets
# in LALR(1) generation.
#
# Inputs: X - An input set
# R - A relation
# FP - Set-valued function
# ------------------------------------------------------------------------------
def digraph(X, R, FP):
N = {}
for x in X:
N[x] = 0
stack = []
F = {}
for x in X:
if N[x] == 0:
traverse(x, N, stack, F, X, R, FP)
return F
def traverse(x, N, stack, F, X, R, FP):
stack.append(x)
d = len(stack)
N[x] = d
F[x] = FP(x) # F(X) <- F'(x)
rel = R(x) # Get y's related to x
for y in rel:
if N[y] == 0:
traverse(y, N, stack, F, X, R, FP)
N[x] = min(N[x], N[y])
for a in F.get(y, []):
if a not in F[x]:
F[x].append(a)
if N[x] == d:
N[stack[-1]] = MAXINT
F[stack[-1]] = F[x]
element = stack.pop()
while element != x:
N[stack[-1]] = MAXINT
F[stack[-1]] = F[x]
element = stack.pop()
class LALRError(YaccError):
pass
# -----------------------------------------------------------------------------
# == LRGeneratedTable ==
#
# This class implements the LR table generation algorithm. There are no
# public methods except for write()
# -----------------------------------------------------------------------------
class LRGeneratedTable(LRTable):
def __init__(self, grammar, method='LALR', log=None):
if method not in ['SLR', 'LALR']:
raise LALRError('Unsupported method %s' % method)
self.grammar = grammar
self.lr_method = method
# Set up the logger
if not log:
log = NullLogger()
self.log = log
# Internal attributes
self.lr_action = {} # Action table
self.lr_goto = {} # Goto table
self.lr_productions = grammar.Productions # Copy of grammar Production array
self.lr_goto_cache = {} # Cache of computed gotos
self.lr0_cidhash = {} # Cache of closures
self._add_count = 0 # Internal counter used to detect cycles
# Diagonistic information filled in by the table generator
self.sr_conflict = 0
self.rr_conflict = 0
self.conflicts = [] # List of conflicts
self.sr_conflicts = []
self.rr_conflicts = []
# Build the tables
self.grammar.build_lritems()
self.grammar.compute_first()
self.grammar.compute_follow()
self.lr_parse_table()
# Compute the LR(0) closure operation on I, where I is a set of LR(0) items.
def lr0_closure(self, I):
self._add_count += 1
# Add everything in I to J
J = I[:]
didadd = True
while didadd:
didadd = False
for j in J:
for x in j.lr_after:
if getattr(x, 'lr0_added', 0) == self._add_count:
continue
# Add B --> .G to J
J.append(x.lr_next)
x.lr0_added = self._add_count
didadd = True
return J
# Compute the LR(0) goto function goto(I,X) where I is a set
# of LR(0) items and X is a grammar symbol. This function is written
# in a way that guarantees uniqueness of the generated goto sets
# (i.e. the same goto set will never be returned as two different Python
# objects). With uniqueness, we can later do fast set comparisons using
# id(obj) instead of element-wise comparison.
def lr0_goto(self, I, x):
# First we look for a previously cached entry
g = self.lr_goto_cache.get((id(I), x))
if g:
return g
# Now we generate the goto set in a way that guarantees uniqueness
# of the result
s = self.lr_goto_cache.get(x)
if not s:
s = {}
self.lr_goto_cache[x] = s
gs = []
for p in I:
n = p.lr_next
if n and n.lr_before == x:
s1 = s.get(id(n))
if not s1:
s1 = {}
s[id(n)] = s1
gs.append(n)
s = s1
g = s.get('$end')
if not g:
if gs:
g = self.lr0_closure(gs)
s['$end'] = g
else:
s['$end'] = gs
self.lr_goto_cache[(id(I), x)] = g
return g
# Compute the LR(0) sets of item function
def lr0_items(self):
C = [self.lr0_closure([self.grammar.Productions[0].lr_next])]
i = 0
for I in C:
self.lr0_cidhash[id(I)] = i
i += 1
# Loop over the items in C and each grammar symbols
i = 0
while i < len(C):
I = C[i]
i += 1
# Collect all of the symbols that could possibly be in the goto(I,X) sets
asyms = {}
for ii in I:
for s in ii.usyms:
asyms[s] = None
for x in asyms:
g = self.lr0_goto(I, x)
if not g or id(g) in self.lr0_cidhash:
continue
self.lr0_cidhash[id(g)] = len(C)
C.append(g)
return C
# -----------------------------------------------------------------------------
# ==== LALR(1) Parsing ====
#
# LALR(1) parsing is almost exactly the same as SLR except that instead of
# relying upon Follow() sets when performing reductions, a more selective
# lookahead set that incorporates the state of the LR(0) machine is utilized.
# Thus, we mainly just have to focus on calculating the lookahead sets.
#
# The method used here is due to DeRemer and Pennelo (1982).
#
# DeRemer, F. L., and T. J. Pennelo: "Efficient Computation of LALR(1)
# Lookahead Sets", ACM Transactions on Programming Languages and Systems,
# Vol. 4, No. 4, Oct. 1982, pp. 615-649
#
# Further details can also be found in:
#
# J. Tremblay and P. Sorenson, "The Theory and Practice of Compiler Writing",
# McGraw-Hill Book Company, (1985).
#
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# compute_nullable_nonterminals()
#
# Creates a dictionary containing all of the non-terminals that might produce
# an empty production.
# -----------------------------------------------------------------------------
def compute_nullable_nonterminals(self):
nullable = set()
num_nullable = 0
while True:
for p in self.grammar.Productions[1:]:
if p.len == 0:
nullable.add(p.name)
continue
for t in p.prod:
if t not in nullable:
break
else:
nullable.add(p.name)
if len(nullable) == num_nullable:
break
num_nullable = len(nullable)
return nullable
# -----------------------------------------------------------------------------
# find_nonterminal_trans(C)
#
# Given a set of LR(0) items, this functions finds all of the non-terminal
# transitions. These are transitions in which a dot appears immediately before
# a non-terminal. Returns a list of tuples of the form (state,N) where state
# is the state number and N is the nonterminal symbol.
#
# The input C is the set of LR(0) items.
# -----------------------------------------------------------------------------
def find_nonterminal_transitions(self, C):
trans = []
for stateno, state in enumerate(C):
for p in state:
if p.lr_index < p.len - 1:
t = (stateno, p.prod[p.lr_index+1])
if t[1] in self.grammar.Nonterminals:
if t not in trans:
trans.append(t)
return trans
# -----------------------------------------------------------------------------
# dr_relation()
#
# Computes the DR(p,A) relationships for non-terminal transitions. The input
# is a tuple (state,N) where state is a number and N is a nonterminal symbol.
#
# Returns a list of terminals.
# -----------------------------------------------------------------------------
def dr_relation(self, C, trans, nullable):
dr_set = {}
state, N = trans
terms = []
g = self.lr0_goto(C[state], N)
for p in g:
if p.lr_index < p.len - 1:
a = p.prod[p.lr_index+1]
if a in self.grammar.Terminals:
if a not in terms:
terms.append(a)
# This extra bit is to handle the start state
if state == 0 and N == self.grammar.Productions[0].prod[0]:
terms.append('$end')
return terms
# -----------------------------------------------------------------------------
# reads_relation()
#
# Computes the READS() relation (p,A) READS (t,C).
# -----------------------------------------------------------------------------
def reads_relation(self, C, trans, empty):
# Look for empty transitions
rel = []
state, N = trans
g = self.lr0_goto(C[state], N)
j = self.lr0_cidhash.get(id(g), -1)
for p in g:
if p.lr_index < p.len - 1:
a = p.prod[p.lr_index + 1]
if a in empty:
rel.append((j, a))
return rel
# -----------------------------------------------------------------------------
# compute_lookback_includes()
#
# Determines the lookback and includes relations
#
# LOOKBACK:
#
# This relation is determined by running the LR(0) state machine forward.
# For example, starting with a production "N : . A B C", we run it forward
# to obtain "N : A B C ." We then build a relationship between this final
# state and the starting state. These relationships are stored in a dictionary
# lookdict.
#
# INCLUDES:
#
# Computes the INCLUDE() relation (p,A) INCLUDES (p',B).
#
# This relation is used to determine non-terminal transitions that occur
# inside of other non-terminal transition states. (p,A) INCLUDES (p', B)
# if the following holds:
#
# B -> LAT, where T -> epsilon and p' -L-> p
#
# L is essentially a prefix (which may be empty), T is a suffix that must be
# able to derive an empty string. State p' must lead to state p with the string L.
#
# -----------------------------------------------------------------------------
def compute_lookback_includes(self, C, trans, nullable):
lookdict = {} # Dictionary of lookback relations
includedict = {} # Dictionary of include relations
# Make a dictionary of non-terminal transitions
dtrans = {}
for t in trans:
dtrans[t] = 1
# Loop over all transitions and compute lookbacks and includes
for state, N in trans:
lookb = []
includes = []
for p in C[state]:
if p.name != N:
continue
# Okay, we have a name match. We now follow the production all the way
# through the state machine until we get the . on the right hand side
lr_index = p.lr_index
j = state
while lr_index < p.len - 1:
lr_index = lr_index + 1
t = p.prod[lr_index]
# Check to see if this symbol and state are a non-terminal transition
if (j, t) in dtrans:
# Yes. Okay, there is some chance that this is an includes relation
# the only way to know for certain is whether the rest of the
# production derives empty
li = lr_index + 1
while li < p.len:
if p.prod[li] in self.grammar.Terminals:
break # No forget it
if p.prod[li] not in nullable:
break
li = li + 1
else:
# Appears to be a relation between (j,t) and (state,N)
includes.append((j, t))
g = self.lr0_goto(C[j], t) # Go to next set
j = self.lr0_cidhash.get(id(g), -1) # Go to next state
# When we get here, j is the final state, now we have to locate the production
for r in C[j]:
if r.name != p.name:
continue
if r.len != p.len:
continue
i = 0
# This look is comparing a production ". A B C" with "A B C ."
while i < r.lr_index:
if r.prod[i] != p.prod[i+1]:
break
i = i + 1
else:
lookb.append((j, r))
for i in includes:
if i not in includedict:
includedict[i] = []
includedict[i].append((state, N))
lookdict[(state, N)] = lookb
return lookdict, includedict
# -----------------------------------------------------------------------------
# compute_read_sets()
#
# Given a set of LR(0) items, this function computes the read sets.
#
# Inputs: C = Set of LR(0) items
# ntrans = Set of nonterminal transitions
# nullable = Set of empty transitions
#
# Returns a set containing the read sets
# -----------------------------------------------------------------------------
def compute_read_sets(self, C, ntrans, nullable):
FP = lambda x: self.dr_relation(C, x, nullable)
R = lambda x: self.reads_relation(C, x, nullable)
F = digraph(ntrans, R, FP)
return F
# -----------------------------------------------------------------------------
# compute_follow_sets()
#
# Given a set of LR(0) items, a set of non-terminal transitions, a readset,
# and an include set, this function computes the follow sets
#
# Follow(p,A) = Read(p,A) U U {Follow(p',B) | (p,A) INCLUDES (p',B)}
#
# Inputs:
# ntrans = Set of nonterminal transitions
# readsets = Readset (previously computed)
# inclsets = Include sets (previously computed)
#
# Returns a set containing the follow sets
# -----------------------------------------------------------------------------
def compute_follow_sets(self, ntrans, readsets, inclsets):
FP = lambda x: readsets[x]
R = lambda x: inclsets.get(x, [])
F = digraph(ntrans, R, FP)
return F
# -----------------------------------------------------------------------------
# add_lookaheads()
#
# Attaches the lookahead symbols to grammar rules.
#
# Inputs: lookbacks - Set of lookback relations
# followset - Computed follow set
#
# This function directly attaches the lookaheads to productions contained
# in the lookbacks set
# -----------------------------------------------------------------------------
def add_lookaheads(self, lookbacks, followset):
for trans, lb in lookbacks.items():
# Loop over productions in lookback
for state, p in lb:
if state not in p.lookaheads:
p.lookaheads[state] = []
f = followset.get(trans, [])
for a in f:
if a not in p.lookaheads[state]:
p.lookaheads[state].append(a)
# -----------------------------------------------------------------------------
# add_lalr_lookaheads()
#
# This function does all of the work of adding lookahead information for use
# with LALR parsing
# -----------------------------------------------------------------------------
def add_lalr_lookaheads(self, C):
# Determine all of the nullable nonterminals
nullable = self.compute_nullable_nonterminals()
# Find all non-terminal transitions
trans = self.find_nonterminal_transitions(C)
# Compute read sets
readsets = self.compute_read_sets(C, trans, nullable)
# Compute lookback/includes relations
lookd, included = self.compute_lookback_includes(C, trans, nullable)
# Compute LALR FOLLOW sets
followsets = self.compute_follow_sets(trans, readsets, included)
# Add all of the lookaheads
self.add_lookaheads(lookd, followsets)
# -----------------------------------------------------------------------------
# lr_parse_table()
#
# This function constructs the parse tables for SLR or LALR
# -----------------------------------------------------------------------------
def lr_parse_table(self):
Productions = self.grammar.Productions
Precedence = self.grammar.Precedence
goto = self.lr_goto # Goto array
action = self.lr_action # Action array
log = self.log # Logger for output
actionp = {} # Action production array (temporary)
log.info('Parsing method: %s', self.lr_method)
# Step 1: Construct C = { I0, I1, ... IN}, collection of LR(0) items
# This determines the number of states
C = self.lr0_items()
if self.lr_method == 'LALR':
self.add_lalr_lookaheads(C)
# Build the parser table, state by state
st = 0
for I in C:
# Loop over each production in I
actlist = [] # List of actions
st_action = {}
st_actionp = {}
st_goto = {}
log.info('')
log.info('state %d', st)
log.info('')
for p in I:
log.info(' (%d) %s', p.number, p)
log.info('')
for p in I:
if p.len == p.lr_index + 1:
if p.name == "S'":
# Start symbol. Accept!
st_action['$end'] = 0
st_actionp['$end'] = p
else:
# We are at the end of a production. Reduce!
if self.lr_method == 'LALR':
laheads = p.lookaheads[st]
else:
laheads = self.grammar.Follow[p.name]
for a in laheads:
actlist.append((a, p, 'reduce using rule %d (%s)' % (p.number, p)))
r = st_action.get(a)
if r is not None:
# Whoa. Have a shift/reduce or reduce/reduce conflict
if r > 0:
# Need to decide on shift or reduce here
# By default we favor shifting. Need to add
# some precedence rules here.
# Shift precedence comes from the token
sprec, slevel = Precedence.get(a, ('right', 0))
# Reduce precedence comes from rule being reduced (p)
rprec, rlevel = Productions[p.number].prec
if (slevel < rlevel) or ((slevel == rlevel) and (rprec == 'left')):
# We really need to reduce here.
st_action[a] = -p.number
st_actionp[a] = p
if not slevel and not rlevel:
log.info(' ! shift/reduce conflict for %s resolved as reduce', a)
self.sr_conflicts.append((st, a, 'reduce'))
Productions[p.number].reduced += 1
elif (slevel == rlevel) and (rprec == 'nonassoc'):
st_action[a] = None
else:
# Hmmm. Guess we'll keep the shift
if not rlevel:
log.info(' ! shift/reduce conflict for %s resolved as shift', a)
self.sr_conflicts.append((st, a, 'shift'))
elif r < 0:
# Reduce/reduce conflict. In this case, we favor the rule
# that was defined first in the grammar file
oldp = Productions[-r]
pp = Productions[p.number]
if oldp.line > pp.line:
st_action[a] = -p.number
st_actionp[a] = p
chosenp, rejectp = pp, oldp
Productions[p.number].reduced += 1
Productions[oldp.number].reduced -= 1
else:
chosenp, rejectp = oldp, pp
self.rr_conflicts.append((st, chosenp, rejectp))
log.info(' ! reduce/reduce conflict for %s resolved using rule %d (%s)',
a, st_actionp[a].number, st_actionp[a])
else:
raise LALRError('Unknown conflict in state %d' % st)
else:
st_action[a] = -p.number
st_actionp[a] = p
Productions[p.number].reduced += 1
else:
i = p.lr_index
a = p.prod[i+1] # Get symbol right after the "."
if a in self.grammar.Terminals:
g = self.lr0_goto(I, a)
j = self.lr0_cidhash.get(id(g), -1)
if j >= 0:
# We are in a shift state
actlist.append((a, p, 'shift and go to state %d' % j))
r = st_action.get(a)
if r is not None:
# Whoa have a shift/reduce or shift/shift conflict
if r > 0:
if r != j:
raise LALRError('Shift/shift conflict in state %d' % st)
elif r < 0:
# Do a precedence check.
# - if precedence of reduce rule is higher, we reduce.
# - if precedence of reduce is same and left assoc, we reduce.
# - otherwise we shift
# Shift precedence comes from the token
sprec, slevel = Precedence.get(a, ('right', 0))
# Reduce precedence comes from the rule that could have been reduced
rprec, rlevel = Productions[st_actionp[a].number].prec
if (slevel > rlevel) or ((slevel == rlevel) and (rprec == 'right')):
# We decide to shift here... highest precedence to shift
Productions[st_actionp[a].number].reduced -= 1
st_action[a] = j
st_actionp[a] = p
if not rlevel:
log.info(' ! shift/reduce conflict for %s resolved as shift', a)
self.sr_conflicts.append((st, a, 'shift'))
elif (slevel == rlevel) and (rprec == 'nonassoc'):
st_action[a] = None
else:
# Hmmm. Guess we'll keep the reduce
if not slevel and not rlevel:
log.info(' ! shift/reduce conflict for %s resolved as reduce', a)
self.sr_conflicts.append((st, a, 'reduce'))
else:
raise LALRError('Unknown conflict in state %d' % st)
else:
st_action[a] = j
st_actionp[a] = p
# Print the actions associated with each terminal
_actprint = {}
for a, p, m in actlist:
if a in st_action:
if p is st_actionp[a]:
log.info(' %-15s %s', a, m)
_actprint[(a, m)] = 1
log.info('')
# Print the actions that were not used. (debugging)
not_used = 0
for a, p, m in actlist:
if a in st_action:
if p is not st_actionp[a]:
if not (a, m) in _actprint:
log.debug(' ! %-15s [ %s ]', a, m)
not_used = 1
_actprint[(a, m)] = 1
if not_used:
log.debug('')
# Construct the goto table for this state
nkeys = {}
for ii in I:
for s in ii.usyms:
if s in self.grammar.Nonterminals:
nkeys[s] = None
for n in nkeys:
g = self.lr0_goto(I, n)
j = self.lr0_cidhash.get(id(g), -1)
if j >= 0:
st_goto[n] = j
log.info(' %-30s shift and go to state %d', n, j)
action[st] = st_action
actionp[st] = st_actionp
goto[st] = st_goto
st += 1
# -----------------------------------------------------------------------------
# write()
#
# This function writes the LR parsing tables to a file
# -----------------------------------------------------------------------------
def write_table(self, tabmodule, outputdir='', signature=''):
if isinstance(tabmodule, types.ModuleType):
raise IOError("Won't overwrite existing tabmodule")
basemodulename = tabmodule.split('.')[-1]
filename = os.path.join(outputdir, basemodulename) + '.py'
try:
f = open(filename, 'w')
f.write('''
# %s
# This file is automatically generated. Do not edit.
_tabversion = %r
_lr_method = %r
_lr_signature = %r
''' % (os.path.basename(filename), __tabversion__, self.lr_method, signature))
# Change smaller to 0 to go back to original tables
smaller = 1
# Factor out names to try and make smaller
if smaller:
items = {}
for s, nd in self.lr_action.items():
for name, v in nd.items():
i = items.get(name)
if not i:
i = ([], [])
items[name] = i
i[0].append(s)
i[1].append(v)
f.write('\n_lr_action_items = {')
for k, v in items.items():
f.write('%r:([' % k)
for i in v[0]:
f.write('%r,' % i)
f.write('],[')
for i in v[1]:
f.write('%r,' % i)
f.write(']),')
f.write('}\n')
f.write('''
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
''')
else:
f.write('\n_lr_action = { ')
for k, v in self.lr_action.items():
f.write('(%r,%r):%r,' % (k[0], k[1], v))
f.write('}\n')
if smaller:
# Factor out names to try and make smaller
items = {}
for s, nd in self.lr_goto.items():
for name, v in nd.items():
i = items.get(name)
if not i:
i = ([], [])
items[name] = i
i[0].append(s)
i[1].append(v)
f.write('\n_lr_goto_items = {')
for k, v in items.items():
f.write('%r:([' % k)
for i in v[0]:
f.write('%r,' % i)
f.write('],[')
for i in v[1]:
f.write('%r,' % i)
f.write(']),')
f.write('}\n')
f.write('''
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto: _lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
''')
else:
f.write('\n_lr_goto = { ')
for k, v in self.lr_goto.items():
f.write('(%r,%r):%r,' % (k[0], k[1], v))
f.write('}\n')
# Write production table
f.write('_lr_productions = [\n')
for p in self.lr_productions:
if p.func:
f.write(' (%r,%r,%d,%r,%r,%d),\n' % (p.str, p.name, p.len,
p.func, os.path.basename(p.file), p.line))
else:
f.write(' (%r,%r,%d,None,None,None),\n' % (str(p), p.name, p.len))
f.write(']\n')
f.close()
except IOError as e:
raise
# -----------------------------------------------------------------------------
# pickle_table()
#
# This function pickles the LR parsing tables to a supplied file object
# -----------------------------------------------------------------------------
def pickle_table(self, filename, signature=''):
try:
import cPickle as pickle
except ImportError:
import pickle
with open(filename, 'wb') as outf:
pickle.dump(__tabversion__, outf, pickle_protocol)
pickle.dump(self.lr_method, outf, pickle_protocol)
pickle.dump(signature, outf, pickle_protocol)
pickle.dump(self.lr_action, outf, pickle_protocol)
pickle.dump(self.lr_goto, outf, pickle_protocol)
outp = []
for p in self.lr_productions:
if p.func:
outp.append((p.str, p.name, p.len, p.func, os.path.basename(p.file), p.line))
else:
outp.append((str(p), p.name, p.len, None, None, None))
pickle.dump(outp, outf, pickle_protocol)
# -----------------------------------------------------------------------------
# === INTROSPECTION ===
#
# The following functions and classes are used to implement the PLY
# introspection features followed by the yacc() function itself.
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# get_caller_module_dict()
#
# This function returns a dictionary containing all of the symbols defined within
# a caller further down the call stack. This is used to get the environment
# associated with the yacc() call if none was provided.
# -----------------------------------------------------------------------------
def get_caller_module_dict(levels):
f = sys._getframe(levels)
ldict = f.f_globals.copy()
if f.f_globals != f.f_locals:
ldict.update(f.f_locals)
return ldict
# -----------------------------------------------------------------------------
# parse_grammar()
#
# This takes a raw grammar rule string and parses it into production data
# -----------------------------------------------------------------------------
def parse_grammar(doc, file, line):
grammar = []
# Split the doc string into lines
pstrings = doc.splitlines()
lastp = None
dline = line
for ps in pstrings:
dline += 1
p = ps.split()
if not p:
continue
try:
if p[0] == '|':
# This is a continuation of a previous rule
if not lastp:
raise SyntaxError("%s:%d: Misplaced '|'" % (file, dline))
prodname = lastp
syms = p[1:]
else:
prodname = p[0]
lastp = prodname
syms = p[2:]
assign = p[1]
if assign != ':' and assign != '::=':
raise SyntaxError("%s:%d: Syntax error. Expected ':'" % (file, dline))
grammar.append((file, dline, prodname, syms))
except SyntaxError:
raise
except Exception:
raise SyntaxError('%s:%d: Syntax error in rule %r' % (file, dline, ps.strip()))
return grammar
# -----------------------------------------------------------------------------
# ParserReflect()
#
# This class represents information extracted for building a parser including
# start symbol, error function, tokens, precedence list, action functions,
# etc.
# -----------------------------------------------------------------------------
class ParserReflect(object):
def __init__(self, pdict, log=None):
self.pdict = pdict
self.start = None
self.error_func = None
self.tokens = None
self.modules = set()
self.grammar = []
self.error = False
if log is None:
self.log = PlyLogger(sys.stderr)
else:
self.log = log
# Get all of the basic information
def get_all(self):
self.get_start()
self.get_error_func()
self.get_tokens()
self.get_precedence()
self.get_pfunctions()
# Validate all of the information
def validate_all(self):
self.validate_start()
self.validate_error_func()
self.validate_tokens()
self.validate_precedence()
self.validate_pfunctions()
self.validate_modules()
return self.error
# Compute a signature over the grammar
def signature(self):
parts = []
try:
if self.start:
parts.append(self.start)
if self.prec:
parts.append(''.join([''.join(p) for p in self.prec]))
if self.tokens:
parts.append(' '.join(self.tokens))
for f in self.pfuncs:
if f[3]:
parts.append(f[3])
except (TypeError, ValueError):
pass
return ''.join(parts)
# -----------------------------------------------------------------------------
# validate_modules()
#
# This method checks to see if there are duplicated p_rulename() functions
# in the parser module file. Without this function, it is really easy for
# users to make mistakes by cutting and pasting code fragments (and it's a real
# bugger to try and figure out why the resulting parser doesn't work). Therefore,
# we just do a little regular expression pattern matching of def statements
# to try and detect duplicates.
# -----------------------------------------------------------------------------
def validate_modules(self):
# Match def p_funcname(
fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(')
for module in self.modules:
try:
lines, linen = inspect.getsourcelines(module)
except IOError:
continue
counthash = {}
for linen, line in enumerate(lines):
linen += 1
m = fre.match(line)
if m:
name = m.group(1)
prev = counthash.get(name)
if not prev:
counthash[name] = linen
else:
filename = inspect.getsourcefile(module)
self.log.warning('%s:%d: Function %s redefined. Previously defined on line %d',
filename, linen, name, prev)
# Get the start symbol
def get_start(self):
self.start = self.pdict.get('start')
# Validate the start symbol
def validate_start(self):
if self.start is not None:
if not isinstance(self.start, string_types):
self.log.error("'start' must be a string")
# Look for error handler
def get_error_func(self):
self.error_func = self.pdict.get('p_error')
# Validate the error function
def validate_error_func(self):
if self.error_func:
if isinstance(self.error_func, types.FunctionType):
ismethod = 0
elif isinstance(self.error_func, types.MethodType):
ismethod = 1
else:
self.log.error("'p_error' defined, but is not a function or method")
self.error = True
return
eline = self.error_func.__code__.co_firstlineno
efile = self.error_func.__code__.co_filename
module = inspect.getmodule(self.error_func)
self.modules.add(module)
argcount = self.error_func.__code__.co_argcount - ismethod
if argcount != 1:
self.log.error('%s:%d: p_error() requires 1 argument', efile, eline)
self.error = True
# Get the tokens map
def get_tokens(self):
tokens = self.pdict.get('tokens')
if not tokens:
self.log.error('No token list is defined')
self.error = True
return
if not isinstance(tokens, (list, tuple)):
self.log.error('tokens must be a list or tuple')
self.error = True
return
if not tokens:
self.log.error('tokens is empty')
self.error = True
return
self.tokens = tokens
# Validate the tokens
def validate_tokens(self):
# Validate the tokens.
if 'error' in self.tokens:
self.log.error("Illegal token name 'error'. Is a reserved word")
self.error = True
return
terminals = set()
for n in self.tokens:
if n in terminals:
self.log.warning('Token %r multiply defined', n)
terminals.add(n)
# Get the precedence map (if any)
def get_precedence(self):
self.prec = self.pdict.get('precedence')
# Validate and parse the precedence map
def validate_precedence(self):
preclist = []
if self.prec:
if not isinstance(self.prec, (list, tuple)):
self.log.error('precedence must be a list or tuple')
self.error = True
return
for level, p in enumerate(self.prec):
if not isinstance(p, (list, tuple)):
self.log.error('Bad precedence table')
self.error = True
return
if len(p) < 2:
self.log.error('Malformed precedence entry %s. Must be (assoc, term, ..., term)', p)
self.error = True
return
assoc = p[0]
if not isinstance(assoc, string_types):
self.log.error('precedence associativity must be a string')
self.error = True
return
for term in p[1:]:
if not isinstance(term, string_types):
self.log.error('precedence items must be strings')
self.error = True
return
preclist.append((term, assoc, level+1))
self.preclist = preclist
# Get all p_functions from the grammar
def get_pfunctions(self):
p_functions = []
for name, item in self.pdict.items():
if not name.startswith('p_') or name == 'p_error':
continue
if isinstance(item, (types.FunctionType, types.MethodType)):
line = getattr(item, 'co_firstlineno', item.__code__.co_firstlineno)
module = inspect.getmodule(item)
p_functions.append((line, module, name, item.__doc__))
# Sort all of the actions by line number; make sure to stringify
# modules to make them sortable, since `line` may not uniquely sort all
# p functions
p_functions.sort(key=lambda p_function: (
p_function[0],
str(p_function[1]),
p_function[2],
p_function[3]))
self.pfuncs = p_functions
# Validate all of the p_functions
def validate_pfunctions(self):
grammar = []
# Check for non-empty symbols
if len(self.pfuncs) == 0:
self.log.error('no rules of the form p_rulename are defined')
self.error = True
return
for line, module, name, doc in self.pfuncs:
file = inspect.getsourcefile(module)
func = self.pdict[name]
if isinstance(func, types.MethodType):
reqargs = 2
else:
reqargs = 1
if func.__code__.co_argcount > reqargs:
self.log.error('%s:%d: Rule %r has too many arguments', file, line, func.__name__)
self.error = True
elif func.__code__.co_argcount < reqargs:
self.log.error('%s:%d: Rule %r requires an argument', file, line, func.__name__)
self.error = True
elif not func.__doc__:
self.log.warning('%s:%d: No documentation string specified in function %r (ignored)',
file, line, func.__name__)
else:
try:
parsed_g = parse_grammar(doc, file, line)
for g in parsed_g:
grammar.append((name, g))
except SyntaxError as e:
self.log.error(str(e))
self.error = True
# Looks like a valid grammar rule
# Mark the file in which defined.
self.modules.add(module)
# Secondary validation step that looks for p_ definitions that are not functions
# or functions that look like they might be grammar rules.
for n, v in self.pdict.items():
if n.startswith('p_') and isinstance(v, (types.FunctionType, types.MethodType)):
continue
if n.startswith('t_'):
continue
if n.startswith('p_') and n != 'p_error':
self.log.warning('%r not defined as a function', n)
if ((isinstance(v, types.FunctionType) and v.__code__.co_argcount == 1) or
(isinstance(v, types.MethodType) and v.__func__.__code__.co_argcount == 2)):
if v.__doc__:
try:
doc = v.__doc__.split(' ')
if doc[1] == ':':
self.log.warning('%s:%d: Possible grammar rule %r defined without p_ prefix',
v.__code__.co_filename, v.__code__.co_firstlineno, n)
except IndexError:
pass
self.grammar = grammar
# -----------------------------------------------------------------------------
# yacc(module)
#
# Build a parser
# -----------------------------------------------------------------------------
def yacc(method='LALR', debug=yaccdebug, module=None, tabmodule=tab_module, start=None,
check_recursion=True, optimize=False, write_tables=True, debugfile=debug_file,
outputdir=None, debuglog=None, errorlog=None, picklefile=None):
if tabmodule is None:
tabmodule = tab_module
# Reference to the parsing method of the last built parser
global parse
# If pickling is enabled, table files are not created
if picklefile:
write_tables = 0
if errorlog is None:
errorlog = PlyLogger(sys.stderr)
# Get the module dictionary used for the parser
if module:
_items = [(k, getattr(module, k)) for k in dir(module)]
pdict = dict(_items)
# If no __file__ attribute is available, try to obtain it from the __module__ instead
if '__file__' not in pdict:
pdict['__file__'] = sys.modules[pdict['__module__']].__file__
else:
pdict = get_caller_module_dict(2)
if outputdir is None:
# If no output directory is set, the location of the output files
# is determined according to the following rules:
# - If tabmodule specifies a package, files go into that package directory
# - Otherwise, files go in the same directory as the specifying module
if isinstance(tabmodule, types.ModuleType):
srcfile = tabmodule.__file__
else:
if '.' not in tabmodule:
srcfile = pdict['__file__']
else:
parts = tabmodule.split('.')
pkgname = '.'.join(parts[:-1])
exec('import %s' % pkgname)
srcfile = getattr(sys.modules[pkgname], '__file__', '')
outputdir = os.path.dirname(srcfile)
# Determine if the module is package of a package or not.
# If so, fix the tabmodule setting so that tables load correctly
pkg = pdict.get('__package__')
if pkg and isinstance(tabmodule, str):
if '.' not in tabmodule:
tabmodule = pkg + '.' + tabmodule
# Set start symbol if it's specified directly using an argument
if start is not None:
pdict['start'] = start
# Collect parser information from the dictionary
pinfo = ParserReflect(pdict, log=errorlog)
pinfo.get_all()
if pinfo.error:
raise YaccError('Unable to build parser')
# Check signature against table files (if any)
signature = pinfo.signature()
# Read the tables
try:
lr = LRTable()
if picklefile:
read_signature = lr.read_pickle(picklefile)
else:
read_signature = lr.read_table(tabmodule)
if optimize or (read_signature == signature):
try:
lr.bind_callables(pinfo.pdict)
parser = LRParser(lr, pinfo.error_func)
parse = parser.parse
return parser
except Exception as e:
errorlog.warning('There was a problem loading the table file: %r', e)
except VersionError as e:
errorlog.warning(str(e))
except ImportError:
pass
if debuglog is None:
if debug:
try:
debuglog = PlyLogger(open(os.path.join(outputdir, debugfile), 'w'))
except IOError as e:
errorlog.warning("Couldn't open %r. %s" % (debugfile, e))
debuglog = NullLogger()
else:
debuglog = NullLogger()
debuglog.info('Created by PLY version %s (http://www.dabeaz.com/ply)', __version__)
errors = False
# Validate the parser information
if pinfo.validate_all():
raise YaccError('Unable to build parser')
if not pinfo.error_func:
errorlog.warning('no p_error() function is defined')
# Create a grammar object
grammar = Grammar(pinfo.tokens)
# Set precedence level for terminals
for term, assoc, level in pinfo.preclist:
try:
grammar.set_precedence(term, assoc, level)
except GrammarError as e:
errorlog.warning('%s', e)
# Add productions to the grammar
for funcname, gram in pinfo.grammar:
file, line, prodname, syms = gram
try:
grammar.add_production(prodname, syms, funcname, file, line)
except GrammarError as e:
errorlog.error('%s', e)
errors = True
# Set the grammar start symbols
try:
if start is None:
grammar.set_start(pinfo.start)
else:
grammar.set_start(start)
except GrammarError as e:
errorlog.error(str(e))
errors = True
if errors:
raise YaccError('Unable to build parser')
# Verify the grammar structure
undefined_symbols = grammar.undefined_symbols()
for sym, prod in undefined_symbols:
errorlog.error('%s:%d: Symbol %r used, but not defined as a token or a rule', prod.file, prod.line, sym)
errors = True
unused_terminals = grammar.unused_terminals()
if unused_terminals:
debuglog.info('')
debuglog.info('Unused terminals:')
debuglog.info('')
for term in unused_terminals:
errorlog.warning('Token %r defined, but not used', term)
debuglog.info(' %s', term)
# Print out all productions to the debug log
if debug:
debuglog.info('')
debuglog.info('Grammar')
debuglog.info('')
for n, p in enumerate(grammar.Productions):
debuglog.info('Rule %-5d %s', n, p)
# Find unused non-terminals
unused_rules = grammar.unused_rules()
for prod in unused_rules:
errorlog.warning('%s:%d: Rule %r defined, but not used', prod.file, prod.line, prod.name)
if len(unused_terminals) == 1:
errorlog.warning('There is 1 unused token')
if len(unused_terminals) > 1:
errorlog.warning('There are %d unused tokens', len(unused_terminals))
if len(unused_rules) == 1:
errorlog.warning('There is 1 unused rule')
if len(unused_rules) > 1:
errorlog.warning('There are %d unused rules', len(unused_rules))
if debug:
debuglog.info('')
debuglog.info('Terminals, with rules where they appear')
debuglog.info('')
terms = list(grammar.Terminals)
terms.sort()
for term in terms:
debuglog.info('%-20s : %s', term, ' '.join([str(s) for s in grammar.Terminals[term]]))
debuglog.info('')
debuglog.info('Nonterminals, with rules where they appear')
debuglog.info('')
nonterms = list(grammar.Nonterminals)
nonterms.sort()
for nonterm in nonterms:
debuglog.info('%-20s : %s', nonterm, ' '.join([str(s) for s in grammar.Nonterminals[nonterm]]))
debuglog.info('')
if check_recursion:
unreachable = grammar.find_unreachable()
for u in unreachable:
errorlog.warning('Symbol %r is unreachable', u)
infinite = grammar.infinite_cycles()
for inf in infinite:
errorlog.error('Infinite recursion detected for symbol %r', inf)
errors = True
unused_prec = grammar.unused_precedence()
for term, assoc in unused_prec:
errorlog.error('Precedence rule %r defined for unknown symbol %r', assoc, term)
errors = True
if errors:
raise YaccError('Unable to build parser')
# Run the LRGeneratedTable on the grammar
if debug:
errorlog.debug('Generating %s tables', method)
lr = LRGeneratedTable(grammar, method, debuglog)
if debug:
num_sr = len(lr.sr_conflicts)
# Report shift/reduce and reduce/reduce conflicts
if num_sr == 1:
errorlog.warning('1 shift/reduce conflict')
elif num_sr > 1:
errorlog.warning('%d shift/reduce conflicts', num_sr)
num_rr = len(lr.rr_conflicts)
if num_rr == 1:
errorlog.warning('1 reduce/reduce conflict')
elif num_rr > 1:
errorlog.warning('%d reduce/reduce conflicts', num_rr)
# Write out conflicts to the output file
if debug and (lr.sr_conflicts or lr.rr_conflicts):
debuglog.warning('')
debuglog.warning('Conflicts:')
debuglog.warning('')
for state, tok, resolution in lr.sr_conflicts:
debuglog.warning('shift/reduce conflict for %s in state %d resolved as %s', tok, state, resolution)
already_reported = set()
for state, rule, rejected in lr.rr_conflicts:
if (state, id(rule), id(rejected)) in already_reported:
continue
debuglog.warning('reduce/reduce conflict in state %d resolved using rule (%s)', state, rule)
debuglog.warning('rejected rule (%s) in state %d', rejected, state)
errorlog.warning('reduce/reduce conflict in state %d resolved using rule (%s)', state, rule)
errorlog.warning('rejected rule (%s) in state %d', rejected, state)
already_reported.add((state, id(rule), id(rejected)))
warned_never = []
for state, rule, rejected in lr.rr_conflicts:
if not rejected.reduced and (rejected not in warned_never):
debuglog.warning('Rule (%s) is never reduced', rejected)
errorlog.warning('Rule (%s) is never reduced', rejected)
warned_never.append(rejected)
# Write the table file if requested
if write_tables:
try:
lr.write_table(tabmodule, outputdir, signature)
except IOError as e:
errorlog.warning("Couldn't create %r. %s" % (tabmodule, e))
# Write a pickled version of the tables
if picklefile:
try:
lr.pickle_table(picklefile, signature)
except IOError as e:
errorlog.warning("Couldn't create %r. %s" % (picklefile, e))
# Build the parser
lr.bind_callables(pinfo.pdict)
parser = LRParser(lr, pinfo.error_func)
parse = parser.parse
return parser
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/ply/yacc.py | Python | apache-2.0 | 137,323 |
# ply: ygen.py
#
# This is a support program that auto-generates different versions of the YACC parsing
# function with different features removed for the purposes of performance.
#
# Users should edit the method LParser.parsedebug() in yacc.py. The source code
# for that method is then used to create the other methods. See the comments in
# yacc.py for further details.
import os.path
import shutil
def get_source_range(lines, tag):
srclines = enumerate(lines)
start_tag = '#--! %s-start' % tag
end_tag = '#--! %s-end' % tag
for start_index, line in srclines:
if line.strip().startswith(start_tag):
break
for end_index, line in srclines:
if line.strip().endswith(end_tag):
break
return (start_index + 1, end_index)
def filter_section(lines, tag):
filtered_lines = []
include = True
tag_text = '#--! %s' % tag
for line in lines:
if line.strip().startswith(tag_text):
include = not include
elif include:
filtered_lines.append(line)
return filtered_lines
def main():
dirname = os.path.dirname(__file__)
shutil.copy2(os.path.join(dirname, 'yacc.py'), os.path.join(dirname, 'yacc.py.bak'))
with open(os.path.join(dirname, 'yacc.py'), 'r') as f:
lines = f.readlines()
parse_start, parse_end = get_source_range(lines, 'parsedebug')
parseopt_start, parseopt_end = get_source_range(lines, 'parseopt')
parseopt_notrack_start, parseopt_notrack_end = get_source_range(lines, 'parseopt-notrack')
# Get the original source
orig_lines = lines[parse_start:parse_end]
# Filter the DEBUG sections out
parseopt_lines = filter_section(orig_lines, 'DEBUG')
# Filter the TRACKING sections out
parseopt_notrack_lines = filter_section(parseopt_lines, 'TRACKING')
# Replace the parser source sections with updated versions
lines[parseopt_notrack_start:parseopt_notrack_end] = parseopt_notrack_lines
lines[parseopt_start:parseopt_end] = parseopt_lines
lines = [line.rstrip()+'\n' for line in lines]
with open(os.path.join(dirname, 'yacc.py'), 'w') as f:
f.writelines(lines)
print('Updated yacc.py')
if __name__ == '__main__':
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/ply/ygen.py | Python | apache-2.0 | 2,251 |
#-----------------------------------------------------------------
# plyparser.py
#
# PLYParser class and other utilites for simplifying programming
# parsers with PLY
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#-----------------------------------------------------------------
import warnings
class Coord(object):
""" Coordinates of a syntactic element. Consists of:
- File name
- Line number
- (optional) column number, for the Lexer
"""
__slots__ = ('file', 'line', 'column', '__weakref__')
def __init__(self, file, line, column=None):
self.file = file
self.line = line
self.column = column
def __str__(self):
str = "%s:%s" % (self.file, self.line)
if self.column: str += ":%s" % self.column
return str
class ParseError(Exception): pass
class PLYParser(object):
def _create_opt_rule(self, rulename):
""" Given a rule name, creates an optional ply.yacc rule
for it. The name of the optional rule is
<rulename>_opt
"""
optname = rulename + '_opt'
def optrule(self, p):
p[0] = p[1]
optrule.__doc__ = '%s : empty\n| %s' % (optname, rulename)
optrule.__name__ = 'p_%s' % optname
setattr(self.__class__, optrule.__name__, optrule)
def _coord(self, lineno, column=None):
return Coord(
file=self.clex.filename,
line=lineno,
column=column)
def _token_coord(self, p, token_idx):
""" Returns the coordinates for the YaccProduction objet 'p' indexed
with 'token_idx'. The coordinate includes the 'lineno' and
'column'. Both follow the lex semantic, starting from 1.
"""
last_cr = p.lexer.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
if last_cr < 0:
last_cr = -1
column = (p.lexpos(token_idx) - (last_cr))
return self._coord(p.lineno(token_idx), column)
def _parse_error(self, msg, coord):
raise ParseError("%s: %s" % (coord, msg))
def parameterized(*params):
""" Decorator to create parameterized rules.
Parameterized rule methods must be named starting with 'p_' and contain
'xxx', and their docstrings may contain 'xxx' and 'yyy'. These will be
replaced by the given parameter tuples. For example, ``p_xxx_rule()`` with
docstring 'xxx_rule : yyy' when decorated with
``@parameterized(('id', 'ID'))`` produces ``p_id_rule()`` with the docstring
'id_rule : ID'. Using multiple tuples produces multiple rules.
"""
def decorate(rule_func):
rule_func._params = params
return rule_func
return decorate
def template(cls):
""" Class decorator to generate rules from parameterized rule templates.
See `parameterized` for more information on parameterized rules.
"""
issued_nodoc_warning = False
for attr_name in dir(cls):
if attr_name.startswith('p_'):
method = getattr(cls, attr_name)
if hasattr(method, '_params'):
# Remove the template method
delattr(cls, attr_name)
# Create parameterized rules from this method; only run this if
# the method has a docstring. This is to address an issue when
# pycparser's users are installed in -OO mode which strips
# docstrings away.
# See: https://github.com/eliben/pycparser/pull/198/ and
# https://github.com/eliben/pycparser/issues/197
# for discussion.
if method.__doc__ is not None:
_create_param_rules(cls, method)
elif not issued_nodoc_warning:
warnings.warn(
'parsing methods must have __doc__ for pycparser to work properly',
RuntimeWarning,
stacklevel=2)
issued_nodoc_warning = True
return cls
def _create_param_rules(cls, func):
""" Create ply.yacc rules based on a parameterized rule function
Generates new methods (one per each pair of parameters) based on the
template rule function `func`, and attaches them to `cls`. The rule
function's parameters must be accessible via its `_params` attribute.
"""
for xxx, yyy in func._params:
# Use the template method's body for each new method
def param_rule(self, p):
func(self, p)
# Substitute in the params for the grammar rule and function name
param_rule.__doc__ = func.__doc__.replace('xxx', xxx).replace('yyy', yyy)
param_rule.__name__ = func.__name__.replace('xxx', xxx)
# Attach the new method to the class
setattr(cls, param_rule.__name__, param_rule)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/pycparser/plyparser.py | Python | apache-2.0 | 4,873 |
import os, sys
try:
from setuptools import setup
from setuptools.command.install import install as _install
from setuptools.command.sdist import sdist as _sdist
except ImportError:
from distutils.core import setup
from distutils.command.install import install as _install
from distutils.command.sdist import sdist as _sdist
def _run_build_tables(dir):
from subprocess import check_call
# This is run inside the install staging directory (that had no .pyc files)
# We don't want to generate any.
# https://github.com/eliben/pycparser/pull/135
check_call([sys.executable, '-B', '_build_tables.py'],
cwd=os.path.join(dir, 'pycparser'))
class install(_install):
def run(self):
_install.run(self)
self.execute(_run_build_tables, (self.install_lib,),
msg="Build the lexing/parsing tables")
class sdist(_sdist):
def make_release_tree(self, basedir, files):
_sdist.make_release_tree(self, basedir, files)
self.execute(_run_build_tables, (basedir,),
msg="Build the lexing/parsing tables")
setup(
# metadata
name='pycparser',
description='C parser in Python',
long_description="""
pycparser is a complete parser of the C language, written in
pure Python using the PLY parsing library.
It parses C code into an AST and can serve as a front-end for
C compilers or analysis tools.
""",
license='BSD',
version='2.20',
author='Eli Bendersky',
maintainer='Eli Bendersky',
author_email='eliben@gmail.com',
url='https://github.com/eliben/pycparser',
platforms='Cross Platform',
classifiers = [
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
],
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
packages=['pycparser', 'pycparser.ply'],
package_data={'pycparser': ['*.cfg']},
cmdclass={'install': install, 'sdist': sdist},
)
| YifuLiu/AliOS-Things | components/py_engine/engine/lib/lv_bindings/pycparser/setup.py | Python | apache-2.0 | 2,464 |